query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
IsRedirect returns true when this get role internal server error response has a 3xx status code
func (o *GetRoleInternalServerError) IsRedirect() bool { return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *GetRoleNotFound) IsRedirect() bool {\n\treturn false\n}", "func (o *GetRoleOK) IsRedirect() bool {\n\treturn false\n}", "func (o *GetAccountsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetRoleUnauthorized) IsRedirect() bool {\n\treturn false\n}", "func (o *MetroclusterSvmGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *PutACLInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *UserRolesActionV1InternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *UpdateMTOServiceItemStatusInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *DescribeDNSServerInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetInteractionsInviteInviteCodeStatusDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetSecurityGroupInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetRoleForbidden) IsRedirect() bool {\n\treturn false\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetAccountsBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *GetMeDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *IpspacesGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *WebModifyDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *ObjectsGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetSilenceInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *SearchAclsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *V2ResetClusterInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetInteractionsInteractionFidDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *MoveClustersBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *DeleteACLInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *WebSvmGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *QueryAWSAccountsForIDsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetAzureTenantConfigInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *OpenAPIDiscoveryInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *DescribeServerInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func IsRedirect(code int) bool {\n\treturn http.StatusMultipleChoices <= code && code < http.StatusBadRequest\n}", "func (o *V2GetPresignedForClusterCredentialsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudVolumegroupsGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *QueryApplicationsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *DescribeDNSServerBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *ObjectsGetBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *UpdateMTOServiceItemStatusBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *GetCustomNameByProjectIDBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *GetAlertsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *UnclaimTrafficFilterLinkIDInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *V2GetPreflightRequirementsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *ListServerGroupInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *AwsKmsRekeyExternalDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *V2RegisterClusterInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *EmsDestinationModifyDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *DescribeServerBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudImagesGetallInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetCustomIntegrationVersionByIDUsingGETInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetInfraEnvPresignedFileURLInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudVpnconnectionsNetworksGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *AddServerGroupInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetAlertsBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *GetVersionDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetRunDownstreamLineageDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *CreateMoveTaskOrderInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *DcimInterfacesReadDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetAzureTenantConfigBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *ResetPasswordDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *ClusterNtpKeysGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *UpdateIOAExclusionsV1InternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *BackupsCreateStatusInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *RemoveServerGroupInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *NvmeServiceCollectionGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *V2GetPresignedForClusterCredentialsBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *QueryPolicyRulesBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *PostMalQueryHuntV1InternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *ReorderSecurityRealmsBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *PatchServiceAccountTokenDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *V2ImportClusterInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *ListServerGroupBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *ListPeerFoldersInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *QueryGroupMembersInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudPvminstancesVolumesGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudV1CloudinstancesCosimagesGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *SchemaObjectsShardsGetInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *CreateMoveTaskOrderBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *SnmpTraphostsGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetSecurityGroupBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *AddServerGroupBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *UpdateMTOPostCounselingInformationInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *RetrieveEmailsByCIDBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *QueryAWSAccountsForIDsBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *UpdateMTOServiceItemStatusNotFound) IsRedirect() bool {\n\treturn false\n}", "func (o *IscsiCredentialsCollectionGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *NodesGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *PcloudPvminstancesPutInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudImagesGetallBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *InstallEventsInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *GetVersionStagesDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *NvmeSubsystemMapCollectionGetDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETUnauthorized) IsRedirect() bool {\n\treturn false\n}", "func (o *RemoveServerGroupBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *NvmeSubsystemMapCreateDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *PatchEndpointIDConfigFailed) IsRedirect() bool {\n\treturn false\n}", "func (o *UpdateIOAExclusionsV1BadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *DeleteServiceIDFailure) IsRedirect() bool {\n\treturn false\n}", "func (o *UnclaimTrafficFilterLinkIDBadRequest) IsRedirect() bool {\n\treturn false\n}", "func (o *PcloudCloudinstancesSnapshotsGetallInternalServerError) IsRedirect() bool {\n\treturn false\n}", "func (o *WebSvmGetOK) IsRedirect() bool {\n\treturn false\n}", "func (o *EmsConfigModifyDefault) IsRedirect() bool {\n\treturn o._statusCode/100 == 3\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETForbidden) IsRedirect() bool {\n\treturn false\n}" ]
[ "0.76386875", "0.7577183", "0.75582683", "0.7545615", "0.7474727", "0.7441477", "0.742897", "0.74265766", "0.74233115", "0.7418163", "0.74164855", "0.74089986", "0.74070257", "0.74066335", "0.74022365", "0.7395396", "0.73934156", "0.738409", "0.73813367", "0.7379404", "0.737806", "0.7375577", "0.73730755", "0.73662007", "0.73584527", "0.735845", "0.73579174", "0.7343034", "0.734118", "0.73343223", "0.7331564", "0.7331153", "0.7329238", "0.7329128", "0.73189855", "0.7314144", "0.73139596", "0.7305524", "0.7299982", "0.72995156", "0.7296864", "0.72937584", "0.72862124", "0.7275208", "0.7274352", "0.72734505", "0.72712886", "0.72711617", "0.72705454", "0.7262003", "0.72485095", "0.72476953", "0.7247227", "0.724712", "0.72456294", "0.7237192", "0.7236495", "0.7230612", "0.72267103", "0.72264004", "0.7224237", "0.72242105", "0.7223076", "0.7217102", "0.72148293", "0.72050166", "0.71955496", "0.71953225", "0.71930045", "0.71921664", "0.7188302", "0.7188252", "0.7184856", "0.71804523", "0.7175502", "0.71749544", "0.7173348", "0.7171511", "0.71672654", "0.71615237", "0.7159198", "0.7157665", "0.7153377", "0.71470207", "0.7146602", "0.7144426", "0.714023", "0.71384865", "0.71373385", "0.71373177", "0.71322984", "0.71262354", "0.71253794", "0.7123018", "0.71210164", "0.71178097", "0.7117607", "0.7116696", "0.7115424", "0.7114655" ]
0.79430205
0
IsCode returns true when this get role internal server error response a status code equal to that given
func (o *GetRoleInternalServerError) IsCode(code int) bool { return code == 500 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *GetExecutionByIndexAndPipelineIDUsingGETInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PatchEndpointIDConfigFailed) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2GetPresignedForClusterCredentialsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetRoleOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *GetCustomIntegrationVersionByIDUsingGETInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2GetPreflightRequirementsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETUnauthorized) IsCode(code int) bool {\n\treturn code == 401\n}", "func (o *WebSvmGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *GetSecurityGroupInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetRunDownstreamLineageOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *PcloudVolumegroupsGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetInfraEnvPresignedFileURLInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeDNSServerBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *PutACLInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeDNSServerInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *UserRolesActionV1InternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudCloudinstancesVolumesRemoteCopyRelationshipGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudVpnconnectionsNetworksGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeServerInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *ListAvailableStreamsOAuth2InternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeServerNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *GetAccountsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *UpdateMTOServiceItemStatusInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *AddServerGroupInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeServerBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *AddServerGroupNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *UpdateFirewallPoliciesInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudPvminstancesVolumesGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetMeOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *SearchAclsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *ObjectsGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *MetroclusterSvmGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *UnclaimTrafficFilterLinkIDInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *IpspacesGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *GetAzureTenantConfigInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *GetAlertsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetSilenceInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DescribeServerOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *UpdateDockerRegistryWebhookByNameUsingPUTInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetRunDownstreamLineageNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *WebModifyOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *QueryApplicationsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *OpenAPIDiscoveryInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudCloudinstancesSnapshotsGetallInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DeleteServiceIDFailure) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *ListServerGroupInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *QueryGroupMembersInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2ResetClusterInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2RegisterClusterInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *UpdateGerritListenerByNameUsingPUTInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *RemoveServerGroupInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudImagesGetallInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2UpdateClusterUISettingsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *SchemaObjectsShardsGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *VerifyConnectionOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *ListPeerFoldersInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetRoleNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *SnmpTraphostsGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *UpdateMTOServiceItemStatusPreconditionFailed) IsCode(code int) bool {\n\treturn code == 412\n}", "func (o *PcloudVolumeOnboardingPostInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PatchDockerRegistryWebhookByIDUsingPATCHInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *UpdateSensorUpdatePoliciesV2InternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *QueryAWSAccountsForIDsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *DeleteACLInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *InstallEventsInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetCustomNameByProjectIDBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *AddServerGroupBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *GetMachineSnapshotsOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *MoveClustersBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *DescribeDNSServerNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *PcloudVpnconnectionsPutInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PcloudV1CloudinstancesCosimagesGetInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetRoleUnauthorized) IsCode(code int) bool {\n\treturn code == 401\n}", "func (o *PcloudPvminstancesPutInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *ObjectsGetBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *DescribeDNSServerOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *ListServerGroupBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *UserGetMeServiceUnavailable) IsCode(code int) bool {\n\treturn code == 503\n}", "func (o *UpdateIOAExclusionsV1InternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *UserGetMeOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *SchedulerActionFormDiscoveryInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *CreateMoveTaskOrderInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *PostMalQueryHuntV1InternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *GetCustomIntegrationVersionByIDUsingGETUnauthorized) IsCode(code int) bool {\n\treturn code == 401\n}", "func (o *SearchLogQueryBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *V2GetPresignedForClusterCredentialsBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *GetSecurityGroupNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *LdapGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *BackupsCreateStatusInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *NvmeServiceCollectionGetOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *UpdateMTOServiceItemStatusUnauthorized) IsCode(code int) bool {\n\treturn code == 401\n}", "func (o *UpdateMTOPostCounselingInformationInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *V2ImportClusterInternalServerError) IsCode(code int) bool {\n\treturn code == 500\n}", "func (o *RemoveServerGroupNotFound) IsCode(code int) bool {\n\treturn code == 404\n}", "func (o *GetAccountsBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *ReorderSecurityRealmsBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}", "func (o *ListServerGroupOK) IsCode(code int) bool {\n\treturn code == 200\n}", "func (o *UpdateMTOServiceItemStatusBadRequest) IsCode(code int) bool {\n\treturn code == 400\n}" ]
[ "0.8057951", "0.78796047", "0.7813867", "0.7811948", "0.7790003", "0.77811015", "0.7778378", "0.7769259", "0.7757357", "0.7745845", "0.77433157", "0.7742567", "0.7728937", "0.772882", "0.7723544", "0.7721266", "0.77017015", "0.7689687", "0.768575", "0.76828927", "0.768283", "0.7676631", "0.766968", "0.76694924", "0.76676196", "0.7666803", "0.765786", "0.7653185", "0.76494807", "0.7647338", "0.76431173", "0.764119", "0.7631128", "0.7629581", "0.76294893", "0.7623238", "0.76218694", "0.7615708", "0.76146597", "0.7606614", "0.7605805", "0.7598049", "0.75966525", "0.75926113", "0.7591125", "0.7590256", "0.75870293", "0.75845075", "0.7580172", "0.7579736", "0.757074", "0.75668126", "0.75642496", "0.756379", "0.75635844", "0.7562882", "0.7557425", "0.7556904", "0.7554545", "0.754951", "0.7548936", "0.75455886", "0.7538777", "0.7536842", "0.75347716", "0.75305617", "0.7527064", "0.75267696", "0.7526282", "0.75243497", "0.7521884", "0.75215757", "0.75134176", "0.751238", "0.7512026", "0.7507952", "0.75052536", "0.75017494", "0.7500402", "0.74951744", "0.74908185", "0.74882275", "0.7488138", "0.7478417", "0.7478242", "0.7477862", "0.74772936", "0.7471768", "0.74711096", "0.7470409", "0.74693716", "0.7468749", "0.74685115", "0.74643916", "0.74597746", "0.7458552", "0.7449922", "0.74479735", "0.7447451", "0.74464035" ]
0.80082095
1
BenchmarkPlainStreaming measures endtoend plaintext streaming performance for fasthttp client and server. It issues http requests over a small number of keepalive connections.
func BenchmarkPlainStreaming(b *testing.B) { benchmark(b, streamingHandler, false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func BenchmarkTLSStreaming(b *testing.B) {\n\tbenchmark(b, streamingHandler, true)\n}", "func runEchoStream(b *testing.B, chunkCnt, payloadSize int, random bool) {\n\tb.ReportAllocs()\n\tinternal.CallEchoStream(b, ctx, serverAddr, b.N, chunkCnt, payloadSize, random, benchmark.AddStats(b, 16))\n}", "func Benchmark_Pool_Echo_Batched(b *testing.B) {\n\tctx := context.Background()\n\tp, err := Initialize(\n\t\tctx,\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/client.php\", \"echo\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: uint64(runtime.NumCPU()),\n\t\t\tAllocateTimeout: time.Second * 100,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\tassert.NoError(b, err)\n\tdefer p.Destroy(ctx)\n\n\tbd := make([]byte, 1024)\n\tc := make([]byte, 1024)\n\n\tpld := &payload.Payload{\n\t\tContext: c,\n\t\tBody: bd,\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < b.N; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tif _, err := p.Exec(pld); err != nil {\n\t\t\t\tb.Fail()\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}()\n\t}\n\n\twg.Wait()\n}", "func BenchmarkPlainHandshake(b *testing.B) {\n\tbenchmark(b, handshakeHandler, false)\n}", "func Benchmark_Pool_Echo(b *testing.B) {\n\tctx := context.Background()\n\tp, err := Initialize(\n\t\tctx,\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/client.php\", \"echo\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\tcfg,\n\t)\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tbd := make([]byte, 1024)\n\tc := make([]byte, 1024)\n\n\tpld := &payload.Payload{\n\t\tContext: c,\n\t\tBody: bd,\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor n := 0; n < b.N; n++ {\n\t\tif _, err := p.Exec(pld); err != nil {\n\t\t\tb.Fail()\n\t\t}\n\t}\n}", "func main() {\n\tstartBenchmark := time.Now()\n\tnc, err := nats.Connect(nats.DefaultURL)\n\tL.PanicIf(err, `nats.Connect`)\n\tjs, err := nc.JetStream(nats.PublishAsyncMaxPending(256))\n\tL.PanicIf(err, `nc.JetStream`)\n\tdefer nc.Close()\n\n\t// create stream\n\tstream, err := js.StreamInfo(TOPIC)\n\tL.IsError(err, `js.StreamInfo`)\n\tif stream == nil {\n\t\tlog.Printf(\"creating stream %q and subjects %q\", TOPIC, TOPIC)\n\t\t_, err = js.AddStream(&nats.StreamConfig{\n\t\t\tName: TOPIC,\n\t\t\tSubjects: []string{TOPIC},\n\t\t})\n\t\tL.IsError(err, `js.AddStream`)\n\t}\n\n\twgConsume := &sync.WaitGroup{}\n\twgConsume.Add(PRODUCERS * MSGS) // includes consuming\n\tfailConsume := int64(0)\n\tdoubleConsume := int64(0)\n\tdurConsume := int64(0)\n\tmaxLatency := int64(0)\n\tconsumed := int64(0)\n\tconsume := sync.Map{}\n\n\tgo func() {\n\t\tfor z := 0; z < CONSUMERS; z++ {\n\t\t\tgo func(z int) {\n\t\t\t\tnc, err := nats.Connect(nats.DefaultURL)\n\t\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\t\tjs, err := nc.JetStream()\n\t\t\t\tL.PanicIf(err, `nc.JetStream`)\n\t\t\t\t//defer nc.Close() // don't close or it will not consume\n\t\t\t\t//fmt.Println(`Consumer spawned`, z)\n\t\t\t\t_, err = js.QueueSubscribe(TOPIC, ``, func(msg *nats.Msg) {\n\t\t\t\t\t//atomic.AddInt64(&failConsume, int64(len(errs)))\n\t\t\t\t\t//L.Print(errs)\n\t\t\t\t\tm := M.SX{}\n\t\t\t\t\terr := json.Unmarshal(msg.Data, &m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tatomic.AddInt64(&failConsume, 1)\n\t\t\t\t\t\tL.Print(err)\n\t\t\t\t\t}\n\t\t\t\t\tif _, exists := consume.LoadOrStore(m.GetInt(`idx`), struct{}{}); !exists {\n\t\t\t\t\t\tdur := time.Now().UnixNano() - m.GetInt(`when`)\n\t\t\t\t\t\tatomic.AddInt64(&durConsume, dur) // bottleneck, TODO: change to channel\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\told := maxLatency\n\t\t\t\t\t\t\tif dur <= old {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif atomic.CompareAndSwapInt64(&maxLatency, old, dur) {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif atomic.AddInt64(&consumed, 1)%PROGRESS == 0 {\n\t\t\t\t\t\t\tfmt.Print(\"C\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_ = msg.Ack()\n\t\t\t\t\t\twgConsume.Done()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt64(&doubleConsume, 1)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tL.PanicIf(err, `js.Subscribe %d`, z)\n\t\t\t}(z)\n\t\t}\n\t}()\n\n\twgProduce := &sync.WaitGroup{}\n\twgProduce.Add(PRODUCERS * MSGS)\n\tfailProduce := int64(0)\n\tdurProduce := int64(0)\n\tproduced := int64(0)\n\n\tstartProduce := time.Now().UnixNano()\n\tfor z := 0; z < PRODUCERS; z++ {\n\t\tgo func(z int) {\n\t\t\t// multiple producers works fast\n\t\t\tnc, err := nats.Connect(nats.DefaultURL)\n\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\tjs, err := nc.JetStream()\n\t\t\tL.PanicIf(err, `nc.JetStream`)\n\t\t\t_, _ = js.AddStream(&nats.StreamConfig{\n\t\t\t\tName: TOPIC,\n\t\t\t\tSubjects: []string{TOPIC},\n\t\t\t\tReplicas: 1,\n\t\t\t})\n\t\t\tdefer nc.Close()\n\t\t\t//fmt.Println(`Producer spawned`, z)\n\t\t\tfor y := 0; y < MSGS; y++ {\n\t\t\t\t_, err := js.Publish(TOPIC, []byte(M.SX{\n\t\t\t\t\t`when`: time.Now().UnixNano(),\n\t\t\t\t\t`idx`: z*MSGS + y,\n\t\t\t\t}.ToJson()))\n\t\t\t\tif err != nil {\n\t\t\t\t\tatomic.AddInt64(&failProduce, 1)\n\t\t\t\t\tL.Print(err, z)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twgProduce.Done()\n\t\t\t\tif atomic.AddInt64(&produced, 1)%PROGRESS == 0 {\n\t\t\t\t\tfmt.Print(\"P\")\n\t\t\t\t}\n\t\t\t}\n\t\t}(z)\n\t}\n\n\twgProduce.Wait()\n\tdurProduce = time.Now().UnixNano() - startProduce\n\twgConsume.Wait()\n\n\tfmt.Println(`FailProduce: `, failProduce)\n\tfmt.Println(`FailConsume: `, failConsume)\n\tfmt.Println(`DoubleConsume: `, doubleConsume)\n\tfmt.Println(`Produced (ms): `, durProduce/1000/1000)\n\tfmt.Println(`MaxLatency (ms): `, maxLatency/1000/1000)\n\tfmt.Println(`AvgLatency (ms): `, durConsume/PRODUCERS/MSGS/1000/1000)\n\tfmt.Println(`Total (s)`, time.Since(startBenchmark))\n}", "func BenchmarkNewFetchHTTP_Parallel(b *testing.B) {\n\t// This parent benchmark function runs only once as soon as there is another\n\t// sub-benchmark.\n\n\t// Full integration benchmark test which starts a HTTP file server and uses\n\t// TCP to query it on the localhost.\n\tconst backendURL = \"http://127.0.0.1:8283/cart_example.html\"\n\tconst lenCartExampleHTML = 21601\n\n\t// grpc_server_main also reads the file from the disk so stay conistent when\n\t// running benchmarks.\n\tcmd := esitesting.StartProcess(\"go\", \"run\", \"http_server_main.go\")\n\tgo cmd.Wait() // waits forever until killed\n\tdefer cmd.Process.Kill() // kills the go process but not the main startet server\n\tdefer esitesting.KillZombieProcess(\"http_server_main\")\n\n\t// Wait until http server has been started\n\tfor i := 300; ; i = i + 100 {\n\t\td := time.Duration(i) * time.Millisecond\n\t\ttime.Sleep(d)\n\t\t_, err := http.Get(backendURL)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"BenchmarkNewFetchHTTP_Parallel: %s => Sleept %s\\n\", err, d)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tb.Run(\"Insecure\", func(b *testing.B) {\n\n\t\tfh := backend.NewFetchHTTP(backend.DefaultHTTPTransport)\n\t\trfa := &esitag.ResourceArgs{\n\t\t\tExternalReq: getExternalReqWithExtendedHeaders(),\n\t\t\tURL: backendURL,\n\t\t\tTag: esitag.Config{\n\t\t\t\tTimeout: time.Second,\n\t\t\t\tMaxBodySize: 22001,\n\t\t\t},\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tb.ReportAllocs()\n\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\tvar content []byte\n\t\t\tvar hdr http.Header\n\t\t\tvar err error\n\n\t\t\tfor pb.Next() {\n\t\t\t\thdr, content, err = fh.DoRequest(rfa)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"%+v\", err)\n\t\t\t\t}\n\t\t\t\tif hdr != nil {\n\t\t\t\t\tb.Fatal(\"Header should be nil\")\n\t\t\t\t}\n\t\t\t\tif len(content) != lenCartExampleHTML {\n\t\t\t\t\tb.Fatalf(\"Want %d\\nHave %d\", lenCartExampleHTML, len(content))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "func doClientStreaming(c calculatorpb.CalculatorServiceClient) {\n\tfmt.Println(\"Client Streaming RPC for Calculator Service\")\n\n\trequests := []*calculatorpb.ComputeAverageRequest{\n\t\t&calculatorpb.ComputeAverageRequest{\n\t\t\tNumber: 1,\n\t\t},\n\t\t&calculatorpb.ComputeAverageRequest{\n\t\t\tNumber: 2,\n\t\t},\n\t\t&calculatorpb.ComputeAverageRequest{\n\t\t\tNumber: 3,\n\t\t},\n\t\t&calculatorpb.ComputeAverageRequest{\n\t\t\tNumber: 4,\n\t\t},\n\t}\n\t// stream\n\tstream, err := c.ComputeAverage(context.Background())\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while recieving result from server: %v\", err)\n\t}\n\n\tfor _, req := range requests {\n\t\tstream.Send(req)\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\t// Recieving the response\n\tres, err := stream.CloseAndRecv()\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error from server: %v\", err)\n\t}\n\n\t//All good\n\tfmt.Println(\"Response from server: \", res)\n}", "func BenchmarkReceive(b *testing.B) {\n\tclientConn, serverConn := net.Pipe()\n\n\tserver := &Server{}\n\tsession := server.newSession(serverConn)\n\tgo session.serve()\n\n\treader := bufio.NewReader(clientConn)\n\t_, _ = reader.ReadString('\\n') // Read greeting message first.\n\n\tb.ResetTimer()\n\n\t// Benchmark a full mail transaction.\n\tfor i := 0; i < b.N; i++ {\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"HELO host.example.com\")\n\t\t_, _ = reader.ReadString('\\n')\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"MAIL FROM:<[email protected]>\")\n\t\t_, _ = reader.ReadString('\\n')\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"RCPT TO:<[email protected]>\")\n\t\t_, _ = reader.ReadString('\\n')\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"DATA\")\n\t\t_, _ = reader.ReadString('\\n')\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"Test message.\\r\\n.\")\n\t\t_, _ = reader.ReadString('\\n')\n\t\tfmt.Fprintf(clientConn, \"%s\\r\\n\", \"QUIT\")\n\t\t_, _ = reader.ReadString('\\n')\n\t}\n}", "func BenchmarkStreamPipeline(b *testing.B) {\n\tb.ReportAllocs()\n\tnumbers := gen(1_000_000)\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, num := range numbers {\n\t\t\tsMultiply(sAdd(sMultiply(num, 2), 1), 2)\n\t\t}\n\t}\n}", "func TestBigData(t *testing.T) {\n\tclient, server := pair(t)\n\n\tserverReads := sinkReads(server)\n\tclientReads := sinkReads(client)\n\n\tconst sz = 15 * 1024 // 15KiB\n\tclientStr := strings.Repeat(\"abcde\", sz/5)\n\tserverStr := strings.Repeat(\"fghij\", sz/5*2)\n\n\tif _, err := io.WriteString(client, clientStr); err != nil {\n\t\tt.Fatalf(\"writing client>server: %v\", err)\n\t}\n\tif _, err := io.WriteString(server, serverStr); err != nil {\n\t\tt.Fatalf(\"writing server>client: %v\", err)\n\t}\n\n\tif serverGot := serverReads.String(sz); serverGot != clientStr {\n\t\tt.Error(\"server didn't receive what client sent\")\n\t}\n\tif clientGot := clientReads.String(2 * sz); clientGot != serverStr {\n\t\tt.Error(\"client didn't receive what server sent\")\n\t}\n\n\tgetNonce := func(n [chp.NonceSize]byte) uint64 {\n\t\tif binary.BigEndian.Uint32(n[:4]) != 0 {\n\t\t\tpanic(\"unexpected nonce\")\n\t\t}\n\t\treturn binary.BigEndian.Uint64(n[4:])\n\t}\n\n\t// Reach into the Conns and verify the cipher nonces advanced as\n\t// expected.\n\tif getNonce(client.tx.nonce) != getNonce(server.rx.nonce) {\n\t\tt.Error(\"desynchronized client tx nonce\")\n\t}\n\tif getNonce(server.tx.nonce) != getNonce(client.rx.nonce) {\n\t\tt.Error(\"desynchronized server tx nonce\")\n\t}\n\tif n := getNonce(client.tx.nonce); n != 4 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 4\", n)\n\t}\n\tif n := getNonce(server.tx.nonce); n != 8 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 8\", n)\n\t}\n}", "func Test_Ctx_SendStream(t *testing.T) {\n\tt.Parallel()\n\tapp := New()\n\tctx := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(ctx)\n\n\tctx.SendStream(bytes.NewReader([]byte(\"Don't crash please\")))\n\tutils.AssertEqual(t, \"Don't crash please\", string(ctx.Fasthttp.Response.Body()))\n\n\tctx.SendStream(bytes.NewReader([]byte(\"Don't crash please\")), len([]byte(\"Don't crash please\")))\n\tutils.AssertEqual(t, \"Don't crash please\", string(ctx.Fasthttp.Response.Body()))\n\n\tctx.SendStream(bufio.NewReader(bytes.NewReader([]byte(\"Hello bufio\"))))\n\tutils.AssertEqual(t, \"Hello bufio\", string(ctx.Fasthttp.Response.Body()))\n\n\tfile, err := os.Open(\"./.github/index.html\")\n\tutils.AssertEqual(t, nil, err)\n\tctx.SendStream(bufio.NewReader(file))\n\tutils.AssertEqual(t, true, (ctx.Fasthttp.Response.Header.ContentLength() > 200))\n}", "func BenchmarkTCPConnWithoutPool(b *testing.B) {\n\tb.ReportAllocs()\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr = write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\n\t\t\t\terr = write(conn, \"close\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error closing: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func main() {\n\ttestsize := 10000\n\tt0 := time.Now()\n\tStatePass(testsize)\n\tt1 := time.Now()\n\tfmt.Println(\"StatePass: \", t1.Sub(t0))\n\t\n\tt2 := time.Now()\n\tstream := Stream(testsize)\n\tfor {\n\t\tif _, ok := <- stream; !ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tt3 := time.Now()\t\n\tfmt.Println(\"Stream: \", t3.Sub(t2))\n}", "func BenchmarkSingleLine(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tpump := &mock.Pump{\n\t\t\tLimit: 862 * bufferSize,\n\t\t\tNumChannels: 2,\n\t\t}\n\t\tproc1 := &mock.Processor{}\n\t\tproc2 := &mock.Processor{}\n\t\tsink1 := &mock.Sink{\n\t\t\tDiscard: true,\n\t\t}\n\t\tsink2 := &mock.Sink{\n\t\t\tDiscard: true,\n\t\t}\n\n\t\tl, _ := pipe.New(\n\t\t\t&pipe.Line{\n\t\t\t\tPump: pump,\n\t\t\t\tProcessors: pipe.Processors(proc1, proc2),\n\t\t\t\tSinks: pipe.Sinks(sink1, sink2),\n\t\t\t},\n\t\t)\n\t\tpipe.Wait(l.Run(context.Background(), bufferSize))\n\t\tpipe.Wait(l.Close())\n\t}\n}", "func testReadWithCustomServer(t *testing.T, testData []byte, serverFunc func(conn *WSConn)) {\n\t// Start the server.\n\twst := newWSTester(serverFunc)\n\tdefer wst.Close()\n\n\t// Connect a client that reads all of the data at once.\n\tclient, err := wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treadBuf := make([]byte, len(testData))\n\t_, err = io.ReadFull(client, readBuf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n\n\t// Connect a client that reads 2 times 50% of the data.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[:len(readBuf)/2])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[len(readBuf)/2:])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n\n\t// Connect a client that reads more than the available data.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn, err := client.Read(readBuf)\n\tif n != 0 || err != nil {\n\t\tt.Fatal(\"expecte n == 0 and err == nil\", n, err)\n\t}\n\n\t// Connect a client that reads only half the data without closing the conn.\n\t// This shouldn't block the next client.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[:len(readBuf)/2])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Connect a client that does random reading until all of the data is read.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar readBytes int\n\tfor remainingBytes := len(testData) - readBytes; remainingBytes > 0; remainingBytes = len(testData) - readBytes {\n\t\ttoRead := fastrand.Intn(remainingBytes) + 1\n\t\t_, err = io.ReadFull(client, readBuf[readBytes:][:toRead])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\treadBytes += toRead\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n}", "func (e *MyTest) Stream(ctx context.Context, req *myTest.StreamingRequest, stream myTest.MyTest_StreamStream) error {\n\tlog.Logf(\"Received MyTest.Stream request with count: %d\", req.Count)\n\n\tfor i := 0; i < int(req.Count); i++ {\n\t\tlog.Logf(\"Responding: %d\", i)\n\t\tif err := stream.Send(&myTest.StreamingResponse{\n\t\t\tCount: int64(i),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Benchmark_Pool_Echo_Replaced(b *testing.B) {\n\tctx := context.Background()\n\tp, err := Initialize(\n\t\tctx,\n\t\tfunc() *exec.Cmd { return exec.Command(\"php\", \"../tests/client.php\", \"echo\", \"pipes\") },\n\t\tpipe.NewPipeFactory(),\n\t\t&Config{\n\t\t\tNumWorkers: 1,\n\t\t\tMaxJobs: 1,\n\t\t\tAllocateTimeout: time.Second,\n\t\t\tDestroyTimeout: time.Second,\n\t\t},\n\t)\n\tassert.NoError(b, err)\n\tdefer p.Destroy(ctx)\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\tif _, err := p.Exec(&payload.Payload{Body: []byte(\"hello\")}); err != nil {\n\t\t\tb.Fail()\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func (self *nntpConnection) handleStreaming(daemon NNTPDaemon, reader bool, conn *textproto.Conn) (err error) {\n for err == nil {\n ev := <- self.stream\n log.Println(self.name, ev)\n if ValidMessageID(ev.MessageID()) {\n cmd , msgid := ev.Command(), ev.MessageID()\n if cmd == \"TAKETHIS\" {\n fname := daemon.store.GetFilename(msgid)\n if CheckFile(fname) {\n f, err := os.Open(fname)\n if err == nil {\n err = conn.PrintfLine(\"%s\", ev)\n // time to send\n dw := conn.DotWriter()\n _ , err = io.Copy(dw, f)\n err = dw.Close()\n f.Close()\n }\n } else {\n log.Println(self.name, \"didn't send\", msgid, \"we don't have it locally\")\n }\n } else if cmd == \"CHECK\" {\n conn.PrintfLine(\"%s\", ev)\n } else {\n log.Println(\"invalid stream command\", ev)\n }\n }\n }\n return\n}", "func main() {\n\tflag.Parse()\n\n\tif MultiProcess() {\n\t\treturn\n\t}\n\n\tvar (\n\t\tmsg = link.Bytes(make([]byte, *messageSize))\n\t\ttimeout = time.Now().Add(time.Second * time.Duration(*runTime))\n\t\tinitWait = new(sync.WaitGroup)\n\t\tstartChan = make(chan int)\n\t\tresultChan = make(chan ClientResult)\n\t\tpool = link.NewMemPool(10, 1, 10)\n\t)\n\n\tlink.DefaultConfig.RequestBufferSize = 1024\n\tlink.DefaultConfig.ResponseBufferSize = 1024\n\tlink.DefaultConfig.SendChanSize = *asyncChan\n\n\tfor i := 0; i < *clientNum; i++ {\n\t\tinitWait.Add(1)\n\t\tconn, err := net.DialTimeout(\"tcp\", *serverAddr, time.Second*3)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tgo client(initWait, &CountConn{Conn: conn}, startChan, resultChan, timeout, msg, pool)\n\t}\n\n\tinitWait.Wait()\n\tclose(startChan)\n\n\tvar (\n\t\tsendCount = 0\n\t\treadCount = 0\n\t\twriteCount = 0\n\t)\n\tfor i := 0; i < *clientNum; i++ {\n\t\tresult := <-resultChan\n\t\tsendCount += result.SendCount\n\t\treadCount += result.ReadCount\n\t\twriteCount += result.WriteCount\n\t}\n\n\tfmt.Printf(OutputFormat,\n\t\tsendCount, sendCount*(*messageSize), readCount, writeCount,\n\t)\n}", "func TestServerShortLivedConn(t *testing.T) {\n\tserver := newTestServer()\n\tdefer server.Stop()\n\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(\"can't listen:\", err)\n\t}\n\tdefer listener.Close()\n\tgo server.ServeListener(listener)\n\n\tvar (\n\t\trequest = `{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"rpc_modules\"}` + \"\\n\"\n\t\twantResp = `{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"nftest\":\"1.0\",\"rpc\":\"1.0\",\"test\":\"1.0\"}}` + \"\\n\"\n\t\tdeadline = time.Now().Add(10 * time.Second)\n\t)\n\tfor i := 0; i < 20; i++ {\n\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(\"can't dial:\", err)\n\t\t}\n\t\tdefer conn.Close()\n\t\tconn.SetDeadline(deadline)\n\t\t// Write the request, then half-close the connection so the server stops reading.\n\t\tconn.Write([]byte(request))\n\t\tconn.(*net.TCPConn).CloseWrite()\n\t\t// Now try to get the response.\n\t\tbuf := make([]byte, 2000)\n\t\tn, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"read error:\", err)\n\t\t}\n\t\tif !bytes.Equal(buf[:n], []byte(wantResp)) {\n\t\t\tt.Fatalf(\"wrong response: %s\", buf[:n])\n\t\t}\n\t}\n}", "func BenchmarkPingPong_2MB_valyala(b *testing.B) {\n\tgorpc.RegisterType(&PostingList{})\n\n\ts := gorpc.NewTCPServer(\":12345\", PingPong)\n\tif err := s.Start(); err != nil {\n\t\tb.Fatal(\"While starting server on port 12345\")\n\t\treturn\n\t}\n\tdefer s.Stop()\n\n\treq := NewRequest(mb2)\n\tc := gorpc.NewTCPClient(\":12345\")\n\tc.Start()\n\tdefer c.Stop()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := c.Call(req)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"While running request: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func dualStream(target net.Conn, clientReader io.ReadCloser, clientWriter io.Writer, padding bool) error {\n\tstream := func(w io.Writer, r io.Reader, paddingType int) error {\n\t\t// copy bytes from r to w\n\t\tbuf := bufferPool.Get().([]byte)\n\t\tbuf = buf[0:cap(buf)]\n\t\t_, _err := flushingIoCopy(w, r, buf, paddingType)\n\t\tbufferPool.Put(buf)\n\t\tif cw, ok := w.(closeWriter); ok {\n\t\t\tcw.CloseWrite()\n\t\t}\n\t\treturn _err\n\t}\n\tif padding {\n\t\tgo stream(target, clientReader, RemovePadding)\n\t\treturn stream(clientWriter, target, AddPadding)\n\t} else {\n\t\tgo stream(target, clientReader, NoPadding)\n\t\treturn stream(clientWriter, target, NoPadding)\n\t}\n}", "func RunTestReadWrite(t *testing.T, e1, e2 streams.StreamProvider) {\n\tserver := func(provider streams.StreamProvider) error {\n\t\tstream, err := provider.Listen(nil).Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor i := 1; ; i++ {\n\t\t\tb := make([]byte, i)\n\t\t\tn, err := stream.Read(b)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tif n, err := stream.Write([]byte(\"goodbye\")); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t} else if n != 7 {\n\t\t\t\t\t\treturn fmt.Errorf(\"Unexpected number of bytes written: %d, expected 7\", n)\n\t\t\t\t\t}\n\t\t\t\t\treturn stream.Close()\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n != i {\n\t\t\t\treturn fmt.Errorf(\"Unexpected number of bytes read: %d, expected %d\", n, i)\n\t\t\t}\n\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\tif b[j] != byte(j) {\n\t\t\t\t\treturn fmt.Errorf(\"Unexpected byte value: %x, expected %x\", b[j], j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tclient := func(provider streams.StreamProvider) error {\n\t\tstream, err := provider.NewStream(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 1; i < 254; i++ {\n\t\t\tb := make([]byte, i)\n\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\tb[j] = byte(j)\n\t\t\t}\n\t\t\tn, err := stream.Write(b)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n != i {\n\t\t\t\treturn fmt.Errorf(\"Unexpected number of bytes written: %d, expected %d\", n, i)\n\t\t\t}\n\t\t}\n\t\t// Half close\n\t\tif err := stream.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb := make([]byte, 7)\n\t\tn, err := stream.Read(b)\n\t\tif n != 7 {\n\t\t\treturn fmt.Errorf(\"Unexpected number of bytes read: %d, expected %d\", n, 7)\n\t\t}\n\t\tif expected := \"goodbye\"; string(b) != expected {\n\t\t\treturn fmt.Errorf(\"Unexpected value read: %s, expected %s\", b, expected)\n\t\t}\n\t\treturn nil\n\t}\n\trunTest(t, e1, e2, client, server)\n}", "func runPerChunk(b *testing.B, payloadSize int, random bool) {\n\tb.ReportAllocs()\n\tinternal.CallEchoStream(b, ctx, serverAddr, 1, b.N, payloadSize, random, benchmark.NewStats(1))\n}", "func TestServer_Query_Chunked(t *testing.T) {\n\tt.Parallel()\n\ts := OpenServer(t)\n\tdefer s.Close()\n\n\twrites := []string{\n\t\tfmt.Sprintf(`cpu,host=foo value=1.0 %d`, mustParseTime(time.RFC3339Nano, \"2000-01-01T01:00:00Z\").UnixNano()),\n\t\tfmt.Sprintf(`cpu,host=bar value=1.0 %d`, mustParseTime(time.RFC3339Nano, \"2000-01-02T01:00:00Z\").UnixNano()),\n\t}\n\n\ttest := NewTest(\"db0\", \"rp0\")\n\ttest.writes = Writes{\n\t\t&Write{data: strings.Join(writes, \"\\n\")},\n\t}\n\n\ttest.addQueries([]*Query{\n\t\t{\n\t\t\tname: \"query is chunked\",\n\t\t\tparams: url.Values{\"db\": []string{\"db0\"}, \"chunked\": []string{\"true\"}, \"chunk_size\": []string{\"1\"}},\n\t\t\tcommand: `SELECT value FROM cpu`,\n\t\t\texp: `{\"results\":[{\"statement_id\":0,\"series\":[{\"name\":\"cpu\",\"columns\":[\"time\",\"value\"],\"values\":[[\"2000-01-01T01:00:00Z\",1]],\"partial\":true}],\"partial\":true}]}\n{\"results\":[{\"statement_id\":0,\"series\":[{\"name\":\"cpu\",\"columns\":[\"time\",\"value\"],\"values\":[[\"2000-01-02T01:00:00Z\",1]]}]}]}`,\n\t\t},\n\t\t{\n\t\t\tname: \"query is not chunked\",\n\t\t\tparams: url.Values{\"db\": []string{\"db0\"}, \"chunked\": []string{\"false\"}, \"chunk_size\": []string{\"1\"}},\n\t\t\tcommand: `SELECT value FROM cpu`,\n\t\t\texp: `{\"results\":[{\"statement_id\":0,\"series\":[{\"name\":\"cpu\",\"columns\":[\"time\",\"value\"],\"values\":[[\"2000-01-01T01:00:00Z\",1],[\"2000-01-02T01:00:00Z\",1]]}]}]}`,\n\t\t},\n\t}...)\n\n\tctx := context.Background()\n\ttest.Run(ctx, t, s)\n}", "func BenchmarkPipe(b *testing.B) {\n\tf := pipe.StageFunc(func(x pipe.Item) pipe.Item {\n\t\tfor _ = range x.(string) {\n\t\t\ttime.Sleep(time.Second / 10)\n\t\t}\n\t\treturn x\n\t})\n\tp := pipe.New(f, f, f)\n\tp.Receive(\"cat\")\n\tp.Receive(\"wolf\")\n\tp.Receive(\"mouse\")\n\tp.Deliver()\n\tp.Deliver()\n\tp.Deliver()\n}", "func stream_copy(src io.Reader, dst io.Writer) <-chan int {\n\tbuf := make([]byte, 3948)\n\tsync_channel := make(chan int)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif con, ok := dst.(net.Conn); ok {\n\t\t\t\tcon.Close()\n\t\t\t\tlog.Printf(\"Connection from %v is closed\\n\", con.RemoteAddr())\n\t\t\t}\n\t\t\tsync_channel <- 0 // Notify that processing is finished\n\t\t}()\n\t\tstart := time.Now() // tiempo total\n\t\tpartial := time.Now() // tiempo parcial\n\t\ttotalBytes := 0\n\t\toldbitrate := float64(0)\n\t\tstarted := true\n\t\tpos := 0\n\t\tfor {\n\t\t\tvar nBytes int\n\t\t\tvar err error\n\t\t\tnBytes, err = src.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tlog.Printf(\"Read error: %s\\n\", err)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif started { // sync with MPEG-2 TS start = 0x47\n\t\t\t\tpos = bytes.IndexByte(buf, 0x47)\n\t\t\t\tif (pos < 0) || (pos >= nBytes) { // sync not found in this read\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (pos + 188) >= nBytes {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif buf[pos+188] != 0x47 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t_, err = dst.Write(buf[pos:nBytes])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Write error: %s\\n\", err)\n\t\t\t\t}\n\t\t\t\tstarted = false\n\t\t\t} else {\n\t\t\t\t_, err = dst.Write(buf[0:nBytes])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Write error: %s\\n\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttotalBytes = totalBytes + nBytes\n\t\t\tt := time.Since(partial).Nanoseconds()\n\t\t\tif t > 500000000 { // half a second\n\t\t\t\tbitrate := float64(totalBytes * 8000000.0 / int(t))\n\t\t\t\tif oldbitrate == 0 {\n\t\t\t\t\toldbitrate = bitrate\n\t\t\t\t}\n\t\t\t\tc := 0.99*oldbitrate + 0.01*bitrate\n\t\t\t\tfmt.Fprintf(os.Stderr, \"time=%.2f bitrate=%.0fkbits/s\\n\", time.Since(start).Seconds(), c)\n\t\t\t\t// reiniciamos todos los contadores\n\t\t\t\toldbitrate = c\n\t\t\t\ttotalBytes = 0\n\t\t\t\tpartial = time.Now()\n\t\t\t}\n\t\t}\n\t}()\n\treturn sync_channel\n}", "func TestLineBufferParallel(t *testing.T) {\n\tsrc := &sourceTailer{lines: make(chan string)}\n\tbuffered := BufferedTailerWithMetrics(src)\n\tvar wg sync.WaitGroup\n\tgo func() {\n\t\tstart := time.Now()\n\t\tfor i := 0; i < 10000; i++ {\n\t\t\tsrc.lines <- fmt.Sprintf(\"This is line number %v.\", i)\n\t\t\tif rand.Int()%64 == 0 { // Sleep from time to time\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Producer took %v.\\n\", time.Since(start))\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tstart := time.Now()\n\t\tfor i := 0; i < 10000; i++ {\n\t\t\tline := <-buffered.Lines()\n\t\t\tif line != fmt.Sprintf(\"This is line number %v.\", i) {\n\t\t\t\tt.Errorf(\"Expected 'This is line number %v', but got '%v'.\", i, line)\n\t\t\t}\n\t\t\tif rand.Int()%64 == 0 { // Sleep from time to time\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Consumer took %v.\\n\", time.Since(start))\n\t\twg.Done()\n\t}()\n\twg.Add(2)\n\twg.Wait()\n\tbuffered.Close()\n\t_, stillOpen := <-buffered.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Buffered tailer was not closed.\")\n\t}\n\t_, stillOpen = <-src.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Source tailer was not closed.\")\n\t}\n}", "func TestDataTrickle(t *testing.T) {\n\ts1, s2 := memnet.NewConn(\"noise\", 128000)\n\tclient, server := pairWithConns(t, s1, readerConn{s2, iotest.OneByteReader(s2)})\n\tserverReads := sinkReads(server)\n\n\tconst sz = 10000\n\tclientStr := strings.Repeat(\"abcde\", sz/5)\n\tif _, err := io.WriteString(client, clientStr); err != nil {\n\t\tt.Fatalf(\"writing client>server: %v\", err)\n\t}\n\n\tserverGot := serverReads.String(sz)\n\tif serverGot != clientStr {\n\t\tt.Error(\"server didn't receive what client sent\")\n\t}\n}", "func serverStream(client pbclient.MySpannerClient) error {\n\tfmt.Printf(\"Getting all docs with server stream\\n\\n\")\n\tstream, err := client.ServerStream(ctx, &pb.Name{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tdoc, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"%+v\\n\", doc)\n\t}\n\tfmt.Printf(\"recieved all serverStreamed docs\\n\\n\")\n\treturn nil\n}", "func TestServerStdoutRespectsMaxPacketSize(t *testing.T) {\n\tconn := dial(largeSendHandler, t)\n\tdefer conn.Close()\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to request new session: %v\", err)\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to connect to Stdout: %v\", err)\n\t}\n\tif err := session.Shell(); err != nil {\n\t\tt.Fatalf(\"Unable to execute command: %v\", err)\n\t}\n\tif _, err := ioutil.ReadAll(out); err != nil {\n\t\tt.Fatalf(\"failed to read: %v\", err)\n\t}\n}", "func BenchmarkDialTCP(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tDialTCP(TEST_HOST, TEST_USER, TEST_PASSWD, TEST_DBNAME)\n\t}\n}", "func BenchmarkStreamingDecode_JSON(b *testing.B) {\n\tframe := getTestFrame(b, TypeJSON, 10000)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\ttestDecodingFrame(b, frame, TypeJSON)\n\t\t}\n\t})\n}", "func TestWriteBigChunked(t *testing.T) {\n\trandData := make([]byte, 4096)\n\tif _, err := rand.Read(randData); err != nil {\n\t\tt.Errorf(\"cannot get random data: %s\", err)\n\t\treturn\n\t}\n\tmsgData := \"awesomesauce\\n\" + base64.StdEncoding.EncodeToString(randData)\n\n\tfor _, i := range []CompressType{CompressGzip, CompressZlib} {\n\t\tmsg, err := sendAndRecv(msgData, i)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"sendAndRecv: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif msg.Short != \"awesomesauce\" {\n\t\t\tt.Errorf(\"msg.Short: expected %s, got %s\", msgData, msg.Full)\n\t\t\treturn\n\t\t}\n\n\t\tif msg.Full != msgData {\n\t\t\tt.Errorf(\"msg.Full: expected %s, got %s\", msgData, msg.Full)\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestPlainHTTPServer(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{\n\t\t// The default context uses embedded certs.\n\t\tInsecure: true,\n\t})\n\tdefer s.Stopper().Stop()\n\tts := s.(*TestServer)\n\n\thttpClient, err := s.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thttpURL := \"http://\" + ts.Ctx.HTTPAddr + healthPath\n\tif resp, err := httpClient.Get(httpURL); err != nil {\n\t\tt.Fatalf(\"error requesting health at %s: %s\", httpURL, err)\n\t} else {\n\t\tdefer resp.Body.Close()\n\t\tvar data serverpb.HealthResponse\n\t\tif err := jsonpb.Unmarshal(resp.Body, &data); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\thttpsURL := \"https://\" + ts.Ctx.HTTPAddr + healthPath\n\tif _, err := httpClient.Get(httpsURL); err == nil {\n\t\tt.Fatalf(\"unexpected success fetching %s\", httpsURL)\n\t}\n}", "func TestFastPath(t *testing.T) {\n\ts1, s2 := memnet.NewConn(\"noise\", 128000)\n\tb := &bufferedWriteConn{s1, bufio.NewWriterSize(s1, 10000), false}\n\tclient, server := pairWithConns(t, b, s2)\n\n\tb.manualFlush = true\n\n\tsb := sinkReads(server)\n\n\tconst packets = 10\n\ts := \"test\"\n\tfor i := 0; i < packets; i++ {\n\t\t// Many separate writes, to force separate Noise frames that\n\t\t// all get buffered up and then all sent as a single slice to\n\t\t// the server.\n\t\tif _, err := io.WriteString(client, s); err != nil {\n\t\t\tt.Fatalf(\"client write1 failed: %v\", err)\n\t\t}\n\t}\n\tif err := b.w.Flush(); err != nil {\n\t\tt.Fatalf(\"client flush failed: %v\", err)\n\t}\n\tclient.Close()\n\n\twant := strings.Repeat(s, packets)\n\tif got := sb.String(len(want)); got != want {\n\t\tt.Fatalf(\"wrong content received: got %q, want %q\", got, want)\n\t}\n\tif err := sb.Error(); err != io.EOF {\n\t\tt.Fatalf(\"client close wasn't seen by server\")\n\t}\n}", "func TestNoRaceAvoidSlowConsumerBigMessages(t *testing.T) {\n\topts := DefaultOptions() // Use defaults to make sure they avoid pending slow consumer.\n\ts := RunServer(opts)\n\tdefer s.Shutdown()\n\n\tnc1, err := nats.Connect(fmt.Sprintf(\"nats://%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tt.Fatalf(\"Error on connect: %v\", err)\n\t}\n\tdefer nc1.Close()\n\n\tnc2, err := nats.Connect(fmt.Sprintf(\"nats://%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tt.Fatalf(\"Error on connect: %v\", err)\n\t}\n\tdefer nc2.Close()\n\n\tdata := make([]byte, 1024*1024) // 1MB payload\n\trand.Read(data)\n\n\texpected := int32(500)\n\treceived := int32(0)\n\n\tdone := make(chan bool)\n\n\t// Create Subscription.\n\tnc1.Subscribe(\"slow.consumer\", func(m *nats.Msg) {\n\t\t// Just eat it so that we are not measuring\n\t\t// code time, just delivery.\n\t\tatomic.AddInt32(&received, 1)\n\t\tif received >= expected {\n\t\t\tdone <- true\n\t\t}\n\t})\n\n\t// Create Error handler\n\tnc1.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {\n\t\tt.Fatalf(\"Received an error on the subscription's connection: %v\\n\", err)\n\t})\n\n\tnc1.Flush()\n\n\tfor i := 0; i < int(expected); i++ {\n\t\tnc2.Publish(\"slow.consumer\", data)\n\t}\n\tnc2.Flush()\n\n\tselect {\n\tcase <-done:\n\t\treturn\n\tcase <-time.After(10 * time.Second):\n\t\tr := atomic.LoadInt32(&received)\n\t\tif s.NumSlowConsumers() > 0 {\n\t\t\tt.Fatalf(\"Did not receive all large messages due to slow consumer status: %d of %d\", r, expected)\n\t\t}\n\t\tt.Fatalf(\"Failed to receive all large messages: %d of %d\\n\", r, expected)\n\t}\n}", "func HTTPAPIServerStreamHLSTS(c *gin.Context) {\n\trequestLogger := log.WithFields(logrus.Fields{\n\t\t\"module\": \"http_hls\",\n\t\t\"stream\": c.Param(\"uuid\"),\n\t\t\"channel\": c.Param(\"channel\"),\n\t\t\"func\": \"HTTPAPIServerStreamHLSTS\",\n\t})\n\n\tif !Storage.StreamChannelExist(c.Param(\"uuid\"), c.Param(\"channel\")) {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotFound.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamChannelExist\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\tcodecs, err := Storage.StreamChannelCodecs(c.Param(\"uuid\"), c.Param(\"channel\"))\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamCodecs\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\toutfile := bytes.NewBuffer([]byte{})\n\tMuxer := ts.NewMuxer(outfile)\n\tMuxer.PaddingToMakeCounterCont = true\n\terr = Muxer.WriteHeader(codecs)\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"WriteHeader\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\tseqData, err := Storage.StreamHLSTS(c.Param(\"uuid\"), c.Param(\"channel\"), stringToInt(c.Param(\"seq\")))\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamHLSTS\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\tif len(seqData) == 0 {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotHLSSegments.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"seqData\",\n\t\t}).Errorln(ErrorStreamNotHLSSegments.Error())\n\t\treturn\n\t}\n\tfor _, v := range seqData {\n\t\tv.CompositionTime = 1\n\t\terr = Muxer.WritePacket(*v)\n\t\tif err != nil {\n\t\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\"call\": \"WritePacket\",\n\t\t\t}).Errorln(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\terr = Muxer.WriteTrailer()\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"WriteTrailer\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\t_, err = c.Writer.Write(outfile.Bytes())\n\tif err != nil {\n\t\tc.IndentedJSON(400, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"Write\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\n}", "func BenchmarkStreamingDecode_Protobuf(b *testing.B) {\n\tframe := getTestFrame(b, TypeProtobuf, 10000)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\ttestDecodingFrame(b, frame, TypeProtobuf)\n\t\t}\n\t})\n}", "func TestPerConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tserver1, server2 := startAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// setting bandwidth limit per connection\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 2\n\tserver1.conn.SetReadCPS(reqSpeed1)\n\treqSpeed2 := reqSpeedC / 3\n\tserver2.conn.SetReadCPS(reqSpeed2)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func connStream(t *testing.T) {\n}", "func runEchoServerTPC(b *testing.B, payloadSize int) {\n\tb.ReportAllocs()\n\tinternal.CallEcho(b, ctx, tpcServerAddr, b.N, payloadSize, false, benchmark.AddStats(b, 16))\n}", "func BenchmarkClientServerRoundTripSmallMsg(b *testing.B) {\n\t_, client := runPingPongGrid(b)\n\tb.ResetTimer()\n\tbenchRunner(b, client, requestSmallMsg)\n}", "func TestMaxConnectionAge(t *testing.T) {\n\tt.Parallel()\n\tconst maxAge = 3 * time.Second\n\tsrv := &test.GrpcTestingServer{\n\t\tStreamingFunc: func(server test.Testing_StreamingRequestResponseServer) error {\n\t\t\t//start := time.Now()\n\t\t\t//ctx := server.Context()\n\t\t\t//<-ctx.Done()\n\t\t\t//t.Logf(\"ctx.Err() = %v after %s\", ctx.Err(), time.Since(start))\n\t\t\t//return ctx.Err()\n\t\t\ttime.Sleep(maxAge + maxAge*2/10) // +20%\n\t\t\treturn nil\n\t\t},\n\t}\n\ttestClient := func(t *testing.T, client test.TestingClient) {\n\t\tstart := time.Now()\n\t\tresp, err := client.StreamingRequestResponse(context.Background())\n\t\trequire.NoError(t, err)\n\t\t_, err = resp.Recv()\n\t\trequire.Equal(t, io.EOF, err, \"%s. Elapsed: %s\", err, time.Since(start))\n\t}\n\tkp := keepalive.ServerParameters{\n\t\tMaxConnectionAge: maxAge,\n\t\tMaxConnectionAgeGrace: maxAge,\n\t}\n\tsh := NewJoinStatHandlers()\n\tt.Run(\"gRPC\", func(t *testing.T) {\n\t\ttestKeepalive(t, false, kp, sh, srv, testClient)\n\t})\n\tt.Run(\"WebSocket\", func(t *testing.T) {\n\t\ttestKeepalive(t, true, kp, sh, srv, testClient)\n\t})\n}", "func bufStream(t *testing.T) {\n\tnumTests := 100 // number of random data tests to run.\n\tvar size int64 = 1024 // size of the data being encrypted for every test.\n\n\tfor i := 0; i < numTests; i++ {\n\t\t// get random key and data\n\t\tdata := bytes.NewBuffer(nil)\n\t\tkey := bytes.NewBuffer(nil)\n\t\tmustCopyN(key, rand.Reader, size)\n\t\tmustCopyN(data, rand.Reader, size)\n\n\t\t// simulated readwriter\n\t\trw := bytes.NewBuffer(nil)\n\n\t\t// fill key and data with random data\n\t\tmustCopyN(data, rand.Reader, size)\n\n\t\trwXOR := NewReadWriter(rw, key)\n\n\t\t// write the data\n\t\tmustCopyN(rwXOR, data, size)\n\n\t\t// read the data\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tbuf.Grow(int(size))\n\t\tmustCopyN(buf, rwXOR, size)\n\n\t\tif !bytes.Equal(buf.Bytes(), data.Bytes()) {\n\t\t\tt.Fatalf(\"buf is not equal to data.Bytes()\\nbuf(%X)\\ndata(%X)\",\n\t\t\t\tbuf.Bytes(), data.Bytes())\n\t\t}\n\t}\n}", "func TestTCPSimple(t *testing.T) {\n name := \"hi.txt\"\n contents := \"bye\"\n exptime := 300000\n conn, err := net.Dial(\"tcp\", \"localhost:8080\")\n if err != nil {\n t.Error(err.Error()) // report error through testing framework\n }\n scanner := bufio.NewScanner(conn)\n\n // Write a file\n _,err = fmt.Fprintf(conn, \"write %v %v %v\\r\\n%v\\r\\n\", name, len(contents), exptime ,contents)\n if err !=nil {\n fmt.Printf(\"error in writing in buffer\\n\")\n }\n scanner.Scan() // read first line\n resp := scanner.Text() // extract the text from the buffer\n version := VerifyWriteSucess(t,resp)\n\n // try read now\n fmt.Fprintf(conn, \"read %v\\r\\n\", name)\n scanner.Scan()\n output := scanner.Text()\n scanner.Scan() \n VerifyReadSucess(t,output,version,contents,scanner.Text())\n}", "func TestPerServer(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tstartAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// setting bandwidth limit per server\n\treqSpeedC := int64(speedC) / 10\n\tl.(*netlisten.Listener).ReadLimiter().SetCommonCPS(reqSpeedC)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviationC := (speedC - float64(reqSpeedC)) / float64(reqSpeedC)\n\n\tfmt.Printf(\"Limits: common %d: speed 1: %f, speed 2: %f, common: %f (d: %3.3f) \\n\", reqSpeedC, speed1, speed2, speedC, deviationC)\n\n\tif math.Abs(deviationC) > MaxDeviation {\n\t\tt.Errorf(\"common deviation too big: %3.3f\", deviationC)\n\t}\n}", "func writeTweetStream(w io.Writer) {\n\thttpstream.SetLogger(log.New(os.Stdout, \"\", log.Ldate|log.Ltime|log.Lshortfile), \"info\")\n\tstream := make(chan []byte, 1000)\n\tdone := make(chan bool)\n\tclient := httpstream.NewBasicAuthClient(vafanConf.twitter.user, vafanConf.twitter.password, func(line []byte) {\n\t\tstream <- line\n\t})\n\terr := client.Filter([]int64{twSaulHowardID, twConvictFilmsID}, []string{\"brightonwok\", \"brighton wok\", \"convictfilms\", \"convict films\"}, false, done)\n\t// this opens a go routine that is effectively thread 1\n\t// err := client.Sample(done)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n\t// 2nd thread\n\tgo func() {\n\t\tfor {\n\t\t\tline := <-stream\n\t\t\twriteTweet(w, line)\n\t\t}\n\t}()\n\t// 3rd thread\n\tfor {\n\t\tline := <-stream\n\t\twriteTweet(w, line)\n\t}\n}", "func TestConnMemoryOverhead(t *testing.T) {\n\tnum := 1000\n\tif testing.Short() {\n\t\tnum = 100\n\t}\n\tng0 := runtime.NumGoroutine()\n\n\truntime.GC()\n\tvar ms0 runtime.MemStats\n\truntime.ReadMemStats(&ms0)\n\n\tvar closers []io.Closer\n\tcloseAll := func() {\n\t\tfor _, c := range closers {\n\t\t\tc.Close()\n\t\t}\n\t\tclosers = nil\n\t}\n\tdefer closeAll()\n\n\tfor i := 0; i < num; i++ {\n\t\tclient, server := pair(t)\n\t\tclosers = append(closers, client, server)\n\t\tgo func() {\n\t\t\tvar buf [1]byte\n\t\t\tclient.Read(buf[:])\n\t\t}()\n\t}\n\n\tt0 := time.Now()\n\tdeadline := t0.Add(3 * time.Second)\n\tvar ngo int\n\tfor time.Now().Before(deadline) {\n\t\truntime.GC()\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo >= num {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo < num {\n\t\tt.Fatalf(\"only %v goroutines; expected %v+\", ngo, num)\n\t}\n\truntime.GC()\n\tvar ms runtime.MemStats\n\truntime.ReadMemStats(&ms)\n\tgrowthTotal := int64(ms.HeapAlloc) - int64(ms0.HeapAlloc)\n\tgrowthEach := float64(growthTotal) / float64(num)\n\tt.Logf(\"Alloced %v bytes, %.2f B/each\", growthTotal, growthEach)\n\tconst max = 2000\n\tif growthEach > max {\n\t\tt.Errorf(\"allocated more than expected; want max %v bytes/each\", max)\n\t}\n\n\tcloseAll()\n\n\t// And make sure our goroutines go away too.\n\tdeadline = time.Now().Add(3 * time.Second)\n\tfor time.Now().Before(deadline) {\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo < ng0+num/10 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo >= ng0+num/10 {\n\t\tt.Errorf(\"goroutines didn't go back down; started at %v, now %v\", ng0, ngo)\n\t}\n}", "func main() {\n addrPtr := flag.String(\"addr\", \"127.0.0.1\", \"IP address and port number of client\")\n configPathPtr := flag.String(\"config\", \"config\", \"Path to config file\")\n commPercentPtr := flag.Int(\"comm\", 100, \"x/100 requests are commutative\")\n nPtr := flag.Int(\"n\", 100, \"total number of requests\")\n parallelPtr := flag.Bool(\"parallel\", false, \"true if requests are parallelized, false if serial\")\n\n flag.Parse()\n\n config, err := utils.ReadConfig(*configPathPtr)\n if err != nil {\n fmt.Fprintf(os.Stderr, \"Error reading config at %s: %s\", *configPathPtr, err)\n return\n }\n servers := config.Servers\n n := *nPtr\n results := make(chan int64, n)\n\n start := time.Now()\n go runClient(n, *commPercentPtr, *addrPtr, servers, *parallelPtr, &results)\n\n resultList := make([]int64, n)\n for i := 0; i < n; i++ {\n elem := <-results\n resultList[i] = elem\n }\n elapsed := time.Since(start)\n\n // Print results\n for _,result := range resultList {\n fmt.Println(result)\n }\n seconds := float64(elapsed.Seconds()) + (float64(elapsed.Nanoseconds()) / 1000000000.0)\n throughput := float64(n) / seconds\n fmt.Println(\"THROUGHPUT: \", throughput)\n\n\n}", "func doServerStreams(t *testing.T, prefix string, stdin io.Reader, stdout, stderr io.Writer) {\n\tif stderr != nil {\n\t\twriteExpected(t, \"server stderr\", stderr, prefix+testErr)\n\t}\n\treadExpected(t, \"server stdin\", stdin, prefix+testInput)\n\twriteExpected(t, \"server stdout\", stdout, prefix+testOutput)\n}", "func TestAllConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tstartAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// changing limits in runtime (applies to all existing connections)\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 3\n\treqSpeed2 := reqSpeedC / 3\n\tl.(*netlisten.Listener).ReadLimiter().SetPerChildCPS(reqSpeed1)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func Benchmark_Ctx_Send(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar str = \"Hello, World!\"\n\tvar byt = []byte(\"Hello, World!\")\n\tvar nmb = 123\n\tvar bol = true\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.Send(str)\n\t\tc.Send(byt)\n\t\tc.Send(nmb)\n\t\tc.Send(bol)\n\t}\n\tutils.AssertEqual(b, \"true\", string(c.Fasthttp.Response.Body()))\n}", "func fastBenchmarkHTTP(ctx *fasthttp.RequestCtx) {\n\t_, err := ctx.Write([]byte(\"Retry !\"))\n\tcommonutils.Check(err, \"fastBenchmarkHTTP\")\n}", "func BenchmarkGetWithQueryClient_NoNetwork(b *testing.B) {\n\t// Create the server for http transport, but without actually having it\n\t// serve HTTP requests. Instead we're going to pass it a pre-constructed\n\t// HTTP request directly.\n\tvar service pb.TransportPermutationsServer\n\t{\n\t\tservice = handlers.NewService()\n\t\t// Wrap Service with middlewares. See handlers/service_middlewares.go\n\t\tservice = handlers.WrapService(service)\n\t}\n\tvar getwithqueryEndpoint = svc.MakeGetWithQueryEndpoint(service)\n\tendpoints := svc.Endpoints{\n\t\tGetWithQueryEndpoint: getwithqueryEndpoint,\n\t}\n\tctx := context.WithValue(context.Background(), \"request-url\", \"/getwithquery\")\n\tctx = context.WithValue(ctx, \"transport\", \"HTTPJSON\")\n\tserver := httptransport.NewServer(\n\t\t// This is definitely a hack\n\t\tendpoints.GetWithQueryEndpoint,\n\t\tsvc.DecodeHTTPGetWithQueryZeroRequest,\n\t\tsvc.EncodeHTTPGenericResponse,\n\t)\n\tvar req pb.GetWithQueryRequest\n\treq.A = 12\n\treq.B = 45360\n\n\tvar testData []ServerTestData\n\tfor i := 0; i < b.N; i++ {\n\t\thttpreq, _ := http.NewRequest(\"GET\", \"http://localhost/getwithquery\", strings.NewReader(string(\"\")))\n\t\thttpclient.EncodeHTTPGetWithQueryZeroRequest(context.Background(), httpreq, &req)\n\t\tresprecorder := httptest.NewRecorder()\n\n\t\titem := ServerTestData{\n\t\t\tr: httpreq,\n\t\t\trecorder: resprecorder,\n\t\t}\n\n\t\ttestData = append(testData, item)\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tserver.ServeHTTP(testData[i].recorder, testData[i].r)\n\t}\n}", "func (s *Service) Stream(stream pb.TestService_StreamServer) error {\n\tfor {\n\t\t_, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\treturn stream.SendAndClose(&pb.TestResponse{\n\t\t\t\tSuccess: true,\n\t\t\t})\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func BenchmarkTCPConnWithPool(b *testing.B) {\n\tb.ReportAllocs()\n\tpool := &sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t}\n\t\t\treturn conn\n\t\t},\n\t}\n\tpool.Put(pool.New())\n\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn := pool.Get().(*net.TCPConn)\n\t\t\t\tpool.Put(conn)\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr := write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func BenchmarkClientEncoding(b *testing.B) {\n\tvar req pb.GetWithQueryRequest\n\treq.A = 12\n\treq.B = 45360\n\tfor i := 0; i < b.N; i++ {\n\t\thttpreq, _ := http.NewRequest(\"GET\", \"http://localhost/getwithquery\", strings.NewReader(string(\"\")))\n\t\thttpclient.EncodeHTTPGetWithQueryZeroRequest(context.Background(), httpreq, &req)\n\t}\n}", "func doServerStreaming(cc api.RegisterServiceClient) {\n\treq := &api.RegisterStreamRequest{\n\t\tRegister: &api.Register{\n\t\t\tFirstName: \"Peter\",\n\t\t\tLastName: \"Donvon\",\n\t\t\tEmail: \"[email protected]\",\n\t\t},\n\t}\n\tstream, err := cc.RegisterationManyTimes(context.Background(), req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor {\n\t\tres, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Printf(\"response %v \\n\", res.GetResponse())\n\t}\n}", "func TestStream(t *testing.T) {\n\tconst numReaders = 16\n\tconst dataSize = 1024 * 1024 // 1 MiB\n\n\tstream := New(NewBuffer())\n\n\twg := new(sync.WaitGroup)\n\twg.Add(numReaders)\n\n\tr := rand.New(rand.NewSource(123))\n\tbuffer := new(bytes.Buffer)\n\tio.CopyN(buffer, r, dataSize)\n\tcontent := buffer.Bytes()\n\n\tfor i := 0; i < numReaders; i++ {\n\t\tgo func(i int) {\n\t\t\tr, err := stream.NewReader()\n\t\t\tdefer wg.Done()\n\t\t\ttime.Sleep(time.Duration(i) * 50 * time.Millisecond)\n\t\t\trequire.Nil(t, err)\n\t\t\tdata, err := ioutil.ReadAll(r)\n\t\t\trequire.Nil(t, err)\n\t\t\tassert.Equal(t, data, content)\n\t\t}(i)\n\t}\n\n\tio.Copy(stream, bytes.NewBuffer(content))\n\terr := stream.CloseWrite()\n\tassert.Nil(t, err)\n\twg.Wait()\n}", "func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {\n\tselect {\n\tcase <-s.ctx.Done():\n\t\treturn ContextErr(s.ctx.Err())\n\tcase <-t.ctx.Done():\n\t\treturn ErrConnClosing\n\tdefault:\n\t}\n\n\tif hdr == nil && data == nil && opts.Last {\n\n\t\tt.controlBuf.put(&dataFrame{streamID: s.id, endStream: true, f: func() {}})\n\t\treturn nil\n\t}\n\n\temptyLen := http2MaxFrameLen - len(hdr)\n\tif emptyLen > len(data) {\n\t\temptyLen = len(data)\n\t}\n\thdr = append(hdr, data[:emptyLen]...)\n\tdata = data[emptyLen:]\n\tvar (\n\t\tstreamQuota int\n\t\tstreamQuotaVer uint32\n\t\terr error\n\t)\n\tfor idx, r := range [][]byte{hdr, data} {\n\t\tfor len(r) > 0 {\n\t\t\tsize := http2MaxFrameLen\n\t\t\tif size > len(r) {\n\t\t\t\tsize = len(r)\n\t\t\t}\n\t\t\tif streamQuota == 0 { // Used up all the locally cached stream quota.\n\n\t\t\t\tstreamQuota, streamQuotaVer, err = s.sendQuotaPool.get(math.MaxInt32, s.waiters)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif size > streamQuota {\n\t\t\t\tsize = streamQuota\n\t\t\t}\n\n\t\t\ttq, _, err := t.sendQuotaPool.get(size, s.waiters)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif tq < size {\n\t\t\t\tsize = tq\n\t\t\t}\n\t\t\tltq, _, err := t.localSendQuota.get(size, s.waiters)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tstreamQuota -= size\n\t\t\tp := r[:size]\n\t\t\tvar endStream bool\n\n\t\t\tif opts.Last {\n\t\t\t\tif len(r)-size == 0 { // No more data in r after this iteration.\n\t\t\t\t\tif idx == 0 { // We're writing data header.\n\t\t\t\t\t\tif len(data) == 0 { // There's no data to follow.\n\t\t\t\t\t\t\tendStream = true\n\t\t\t\t\t\t}\n\t\t\t\t\t} else { // We're writing data.\n\t\t\t\t\t\tendStream = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuccess := func() {\n\t\t\t\tltq := ltq\n\t\t\t\tt.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { t.localSendQuota.add(ltq) }})\n\t\t\t\tr = r[size:]\n\t\t\t}\n\t\t\tfailure := func() { // The stream quota version must have changed.\n\n\t\t\t\ts.sendQuotaPool.lockedAdd(streamQuota + size)\n\t\t\t}\n\t\t\tif !s.sendQuotaPool.compareAndExecute(streamQuotaVer, success, failure) {\n\n\t\t\t\tt.sendQuotaPool.add(size)\n\t\t\t\tt.localSendQuota.add(ltq)\n\t\t\t\tstreamQuota = 0\n\t\t\t}\n\t\t}\n\t}\n\tif streamQuota > 0 { // Add the left over quota back to stream.\n\t\ts.sendQuotaPool.add(streamQuota)\n\t}\n\tif !opts.Last {\n\t\treturn nil\n\t}\n\ts.mu.Lock()\n\tif s.state != streamDone {\n\t\ts.state = streamWriteDone\n\t}\n\ts.mu.Unlock()\n\treturn nil\n}", "func TestReceivePerformance(t *testing.T) {\n\tt.Skip(\"Skipped by default\")\n\n\tconst defaultNumGoRoutines = 100\n\tdefaultReceiveProfile := func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 0 }\n\tdefaultProcessProfile := func(bool) time.Duration { return 0 }\n\n\ttests := []struct {\n\t\tdescription string\n\t\t// See the defaults above.\n\t\tnumGoRoutines int\n\t\treceiveProfile func(bool, int) (int, time.Duration)\n\t\tprocessProfile func(bool) time.Duration\n\t}{\n\t\t{\n\t\t\tdescription: \"baseline\",\n\t\t},\n\t\t{\n\t\t\tdescription: \"1 goroutine\",\n\t\t\tnumGoRoutines: 1,\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 100ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 100 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 1s\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 1 * time.Second },\n\t\t},\n\t\t{\n\t\t\tdescription: \"process 100ms\",\n\t\t\tprocessProfile: func(bool) time.Duration { return 100 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"process 1s\",\n\t\t\tprocessProfile: func(bool) time.Duration { return 1 * time.Second },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 1s process 70ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, 1 * time.Second\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return 70 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 250ms+stddev 150ms, process 10ms + stddev 5ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, time.Duration(rand.NormFloat64()*150+250) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty message arrival\",\n\t\t\treceiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {\n\t\t\t\t// When in the middle third of the running time, return 0 messages.\n\t\t\t\tn := maxMessages\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\tn = 0\n\t\t\t\t}\n\t\t\t\treturn n, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty receive time\",\n\t\t\treceiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {\n\t\t\t\t// When in the middle third of the running time, 10x the RPC time.\n\t\t\t\td := time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\td *= 10\n\t\t\t\t}\n\t\t\t\treturn maxMessages, d\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty process time\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(inMiddleThird bool) time.Duration {\n\t\t\t\td := time.Duration(rand.NormFloat64()*5+10) * time.Millisecond\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\td *= 100\n\t\t\t\t}\n\t\t\t\treturn d\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"intermittent\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\tn := rand.Int() % 2\n\t\t\t\treturn n, 250 * time.Millisecond\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.numGoRoutines == 0 {\n\t\t\ttest.numGoRoutines = defaultNumGoRoutines\n\t\t}\n\t\tif test.receiveProfile == nil {\n\t\t\ttest.receiveProfile = defaultReceiveProfile\n\t\t}\n\t\tif test.processProfile == nil {\n\t\t\ttest.processProfile = defaultProcessProfile\n\t\t}\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\trunBenchmark(t, test.description, test.numGoRoutines, test.receiveProfile, test.processProfile)\n\t\t})\n\t}\n}", "func (*server) LongGreet(stream greetpb.GreetService_LongGreetServer) error {\n\t//This server takes a stream\n\tfmt.Printf(\"LongGreet server function was invoked with streaming \\n\")\n\tresult := \"Hello \"\n\tfor {\n\t\treq, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tfmt.Println(\"We have finished reading the client streaming\")\n\t\t\treturn stream.SendAndClose(&greetpb.LongGreetResponse{\n\t\t\t\tResult: result,\n\t\t\t})\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error reading client requeset ::: %v\", err)\n\t\t}\n\n\t\tfirstName := req.GetGreeting().GetFirstName()\n\t\tresult += firstName + \"! \"\n\n\t}\n\n}", "func setupBatchTCPTest(logf logger.Logf, traf *TrafficGen) {\n\tsl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tlog.Fatalf(\"listen: %v\", err)\n\t}\n\n\tvar slCloseOnce sync.Once\n\tslClose := func() {\n\t\tslCloseOnce.Do(func() {\n\t\t\tsl.Close()\n\t\t})\n\t}\n\n\ts1, err := net.Dial(\"tcp\", sl.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"dial: %v\", err)\n\t}\n\n\ts2, err := sl.Accept()\n\tif err != nil {\n\t\tlog.Fatalf(\"accept: %v\", err)\n\t}\n\n\ts1.(*net.TCPConn).SetWriteBuffer(1024 * 1024)\n\ts2.(*net.TCPConn).SetReadBuffer(1024 * 1024)\n\n\tch := make(chan int)\n\n\tgo func() {\n\t\t// transmitter\n\t\tdefer slClose()\n\t\tdefer s1.Close()\n\n\t\tbs1 := bufio.NewWriterSize(s1, 1024*1024)\n\n\t\tb := make([]byte, 1600)\n\t\ti := 0\n\t\tfor {\n\t\t\ti += 1\n\t\t\tn := traf.Generate(b, 16)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i == 1 {\n\t\t\t\tch <- n\n\t\t\t}\n\t\t\tbs1.Write(b[16 : n+16])\n\n\t\t\t// TODO: this is a pretty half-baked batching\n\t\t\t// function, which we'd never want to employ in\n\t\t\t// a real-life program.\n\t\t\t//\n\t\t\t// In real life, we'd probably want to flush\n\t\t\t// immediately when there are no more packets to\n\t\t\t// generate, and queue up only if we fall behind.\n\t\t\t//\n\t\t\t// In our case however, we just want to see the\n\t\t\t// technical benefits of batching 10 syscalls\n\t\t\t// into 1, so a fixed ratio makes more sense.\n\t\t\tif (i % 10) == 0 {\n\t\t\t\tbs1.Flush()\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// receiver\n\t\tdefer slClose()\n\t\tdefer s2.Close()\n\n\t\tbs2 := bufio.NewReaderSize(s2, 1024*1024)\n\n\t\t// Find out the packet size (we happen to know they're\n\t\t// all the same size)\n\t\tpacketSize := <-ch\n\n\t\tb := make([]byte, packetSize)\n\t\tfor traf.Running() {\n\t\t\t// TODO: can't use ReadFrom() here, which is\n\t\t\t// unfair compared to UDP. (ReadFrom for UDP\n\t\t\t// apparently allocates memory per packet, which\n\t\t\t// this test does not.)\n\t\t\tn, err := io.ReadFull(bs2, b)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"s2.Read: %v\", err)\n\t\t\t}\n\t\t\ttraf.GotPacket(b[:n], 0)\n\t\t}\n\t}()\n}", "func (c *Client) readStreamed(ctx context.Context, name string, offset, limit int64, w io.Writer) (n int64, e error) {\n\tclosure := func() error {\n\t\tstream, err := c.Read(ctx, &bspb.ReadRequest{\n\t\t\tResourceName: name,\n\t\t\tReadOffset: offset + n,\n\t\t\tReadLimit: limit,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tvar resp *bspb.ReadResponse\n\t\t\terr := c.CallWithTimeout(ctx, \"Read\", func(_ context.Context) error {\n\t\t\t\tr, err := stream.Recv()\n\t\t\t\tresp = r\n\t\t\t\treturn err\n\t\t\t})\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.V(3).Infof(\"Read: resource:%s offset:%d len(data):%d\", name, offset+n, len(resp.Data))\n\t\t\tnm, err := w.Write(resp.Data)\n\t\t\tif err != nil {\n\t\t\t\t// Wrapping the error to ensure it may never get retried.\n\t\t\t\treturn fmt.Errorf(\"failed to write to output stream: %v\", err)\n\t\t\t}\n\t\t\tsz := len(resp.Data)\n\t\t\tif nm != sz {\n\t\t\t\treturn fmt.Errorf(\"received %d bytes but could only write %d\", sz, nm)\n\t\t\t}\n\t\t\tn += int64(sz)\n\t\t\tif limit > 0 {\n\t\t\t\tlimit -= int64(sz)\n\t\t\t\tif limit <= 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\te = c.Retrier.Do(ctx, closure)\n\treturn n, e\n}", "func BenchmarkParallelProcess(b *testing.B) {\n\trand.Seed(18)\n\tp := protocols{}\n\tp.tcp = make(map[protos.Protocol]protos.TcpProtocolPlugin)\n\tp.tcp[1] = &TestProtocol{Ports: []int{ServerPort}}\n\ttcp, _ := NewTcp(p)\n\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tpkt := &protos.Packet{\n\t\t\t\tTs: time.Now(),\n\t\t\t\tTuple: common.NewIpPortTuple(4,\n\t\t\t\t\tnet.ParseIP(ServerIp), ServerPort,\n\t\t\t\t\tnet.ParseIP(ClientIp), uint16(rand.Intn(65535))),\n\t\t\t\tPayload: []byte{1, 2, 3, 4},\n\t\t\t}\n\t\t\ttcp.Process(&layers.TCP{}, pkt)\n\t\t}\n\t})\n}", "func TestSmoke(t *testing.T) {\n\ta := assert.New(t)\n\tconst backendCount = 4\n\tconst payloadSize = 4096\n\tconst requestCount = 64\n\tconst requestWorkers = 8\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tbackends := make([]*CharGenServer, backendCount)\n\ttier := config.Tier{\n\t\tDialFailureTimeout: 10 * time.Second,\n\t}\n\tfor i := range backends {\n\t\tvar err error\n\t\tbackends[i], err = startChargen(ctx, payloadSize)\n\t\tif !a.NoError(err) {\n\t\t\treturn\n\t\t}\n\t\ttier.Targets = append(tier.Targets, config.Target{\n\t\t\tHosts: []string{backends[i].Addr.IP.String()},\n\t\t\tPort: backends[i].Addr.Port,\n\t\t\tProto: config.TCP,\n\t\t})\n\t}\n\n\tcfg := &config.Config{\n\t\tFrontends: []config.Frontend{\n\t\t\t{\n\t\t\t\tRebalanceDuration: time.Millisecond,\n\t\t\t\tBackendPool: config.BackendPool{\n\t\t\t\t\t// Disable extra pings so our request counts are correct.\n\t\t\t\t\tLatencyBucket: -1,\n\t\t\t\t\tTiers: []config.Tier{tier},\n\t\t\t\t},\n\t\t\t\tBindAddress: \":13013\",\n\t\t\t\tIdleDuration: time.Minute,\n\t\t\t},\n\t\t},\n\t}\n\tif !a.NoError(cfg.Validate()) {\n\t\treturn\n\t}\n\n\tfe := frontend.Frontend{}\n\tif !a.NoError(fe.Ensure(ctx, cfg)) {\n\t\treturn\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(requestWorkers)\n\tvar remainingRequests = int32(requestCount)\n\tfor i := 0; i < requestWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt32(&remainingRequests, -1) < 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\t\t\t\tif !a.NoError(err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcount, err := io.Copy(ioutil.Discard, conn)\n\t\t\t\t_ = conn.Close()\n\t\t\t\ta.NoError(err)\n\t\t\t\ta.Equal(payloadSize, int(count))\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\tfe.Wait()\n\n\t// Ensure that the total number of requests was made.\n\tcount := uint64(0)\n\tfor _, cg := range backends {\n\t\tcount += cg.ConnectionCount()\n\t}\n\ta.Equal(requestCount, int(count))\n\n\tdata, err := yaml.Marshal(&fe)\n\ta.NoError(err)\n\tlog.Print(string(data))\n\n\t// Test tearing down a frontend.\n\tcfg.Frontends = []config.Frontend{}\n\ta.NoError(fe.Ensure(ctx, cfg))\n\t_, err = net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\ta.Errorf(err, \"connection refused\")\n}", "func Benchmark_Ctx_SendString_B(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tbody := \"Hello, world!\"\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.SendString(body)\n\t}\n\tutils.AssertEqual(b, []byte(\"Hello, world!\"), c.Fasthttp.Response.Body())\n}", "func streamMultiNonReuseConn(opts []grpc.DialOption) {\n\tfor i := 0; i < 10; i++ {\n\t\tfunc() {\n\t\t\tconn := conn(opts)\n\t\t\tdefer closerClose(conn)\n\t\t\tclient := pb.NewRouteGuideClient(conn)\n\t\t\t// Looking for a valid feature\n\t\t\tprintFeatures(client, &pb.Rectangle{\n\t\t\t\tLo: &pb.Point{Latitude: 400000000, Longitude: -750000000},\n\t\t\t\tHi: &pb.Point{Latitude: 420000000, Longitude: -730000000},\n\t\t\t})\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}()\n\t}\n}", "func pipe(in io.Reader, out io.Writer, timeout int) (err error) {\n\tbuffer := make([]byte, 1024)\n\tfor {\n\t\tif conn, ok := in.(net.Conn); ok {\n\t\t\tconn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))\n\t\t}\n\n\t\tinCount, err1 := in.Read(buffer)\n\t\tif err1 != nil && !err1.(net.Error).Timeout() {\n\t\t\terr = err1\n\t\t\treturn\n\t\t}\n\n\t\tn := 0\n\t\tfor n < inCount {\n\t\t\tif conn, ok := out.(net.Conn); ok {\n\t\t\t\tconn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))\n\t\t\t}\n\n\t\t\toutCount, err2 := out.Write(buffer[n:inCount])\n\t\t\tif err2 != nil && !err2.(net.Error).Timeout() {\n\t\t\t\terr = err2\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tn += outCount\n\t\t}\n\n\t\tif err1 != nil || inCount == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func TestWriteSmallMultiLine(t *testing.T) {\n\tfor _, i := range []CompressType{CompressGzip, CompressZlib, CompressNone} {\n\t\tmsgData := \"awesomesauce\\nbananas\"\n\n\t\tmsg, err := sendAndRecv(msgData, i)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"sendAndRecv: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif msg.Short != \"awesomesauce\" {\n\t\t\tt.Errorf(\"msg.Short: expected %s, got %s\", msgData, msg.Full)\n\t\t\treturn\n\t\t}\n\n\t\tif msg.Full != msgData {\n\t\t\tt.Errorf(\"msg.Full: expected %s, got %s\", msgData, msg.Full)\n\t\t\treturn\n\t\t}\n\t}\n}", "func readLoop(r server.Request, s client.Stream) error {\n\t// request to backend server\n\treq := s.Request()\n\n\tfor {\n\t\t// get data from client\n\t\t// no need to decode it\n\t\tbody, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// get the header from client\n\t\thdr := r.Header()\n\t\tmsg := &codec.Message{\n\t\t\tType: codec.Request,\n\t\t\tHeader: hdr,\n\t\t\tBody: body,\n\t\t}\n\n\t\t// write the raw request\n\t\terr = req.Codec().Write(msg, nil)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func pipe(dst io.Writer, src io.Reader, dstconn, srcconn net.Conn) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Println(\"Recovered in\", r, \":\", string(debug.Stack()))\n\t\t}\n\t}()\n\n\t// only close dst when done\n\tdefer dstconn.Close()\n\n\tbuf := make([]byte, 2*4096)\n\tfor {\n\t\tsrcconn.SetReadDeadline(time.Now().Add(_ConnReadTimeout))\n\t\tnr, er := src.Read(buf)\n\t\tif nr > 0 {\n\t\t\tnw, ew := dst.Write(buf[0:nr])\n\t\t\tif ew != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif nr != nw {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif neterr, ok := er.(net.Error); ok && neterr.Timeout() {\n\t\t\tcontinue\n\t\t}\n\t\tif er == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif er != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func TestListener(t *testing.T) {\n\tlistener := &fakeListener{}\n\tdoh, _ := NewTransport(testURL, ips, nil, nil, listener)\n\ttransport := doh.(*transport)\n\trt := makeTestRoundTripper()\n\ttransport.client.Transport = rt\n\n\tgo func() {\n\t\treq := <-rt.req\n\t\ttrace := httptrace.ContextClientTrace(req.Context())\n\t\ttrace.GotConn(httptrace.GotConnInfo{\n\t\t\tConn: &fakeConn{\n\t\t\t\tremoteAddr: &net.TCPAddr{\n\t\t\t\t\tIP: net.ParseIP(\"192.0.2.2\"),\n\t\t\t\t\tPort: 443,\n\t\t\t\t}}})\n\n\t\tr, w := io.Pipe()\n\t\trt.resp <- &http.Response{\n\t\t\tStatusCode: 200,\n\t\t\tBody: r,\n\t\t\tRequest: &http.Request{URL: parsedURL},\n\t\t}\n\t\tw.Write([]byte{0, 0, 8, 9, 10})\n\t\tw.Close()\n\t}()\n\n\tdoh.Query(simpleQueryBytes)\n\ts := listener.summary\n\tif s.Latency < 0 {\n\t\tt.Errorf(\"Negative latency: %f\", s.Latency)\n\t}\n\tif !bytes.Equal(s.Query, simpleQueryBytes) {\n\t\tt.Errorf(\"Wrong query: %v\", s.Query)\n\t}\n\tif !bytes.Equal(s.Response, []byte{0xbe, 0xef, 8, 9, 10}) {\n\t\tt.Errorf(\"Wrong response: %v\", s.Response)\n\t}\n\tif s.Server != \"192.0.2.2\" {\n\t\tt.Errorf(\"Wrong server IP string: %s\", s.Server)\n\t}\n\tif s.Status != Complete {\n\t\tt.Errorf(\"Wrong status: %d\", s.Status)\n\t}\n}", "func StreamsResponsesFromTheServerUsingWebsockets() {\n\thelloworldService := helloworld.NewHelloworldService(os.Getenv(\"MICRO_API_TOKEN\"))\n\trsp, err := helloworldService.Stream(&helloworld.StreamRequest{\n\t\tMessages: 10,\n\t\tName: \"John\",\n\t})\n\tfmt.Println(rsp, err)\n}", "func superNetperfStream(s *helpers.SSHMeta, client string, server string, num int) *helpers.CmdRes {\n\treturn superNetperfStreamIPv4(s, client, server, num)\n}", "func TestPubsubBulkPublishHttpPerformance(t *testing.T) {\n\tpublishTypes := []string{\"normal\", \"bulk\"}\n\tbulkSizes := []int{10, 100}\n\tmessageSizesKb := []int{1}\n\n\ttestcases := []testCase{}\n\tfor _, bulkSize := range bulkSizes {\n\t\tfor _, messageSizeKb := range messageSizesKb {\n\t\t\tfor _, broker := range brokers {\n\t\t\t\tfor _, publishType := range publishTypes {\n\t\t\t\t\ttestcases = append(testcases, testCase{\n\t\t\t\t\t\tbroker: broker.Name,\n\t\t\t\t\t\tpublishType: publishType,\n\t\t\t\t\t\ttopic: topicName,\n\t\t\t\t\t\tbulkSize: bulkSize,\n\t\t\t\t\t\tmessageSizeKb: messageSizeKb,\n\t\t\t\t\t\tdurationMs: 30 * 1000,\n\t\t\t\t\t\tnumVus: 50,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, tc := range testcases {\n\t\ttestName := fmt.Sprintf(\"%s_b%d_s%dKB_%s\", tc.broker, tc.bulkSize, tc.messageSizeKb, tc.publishType)\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\trunTest(t, tc)\n\t\t})\n\t}\n}", "func GetDataSlowly(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tchars := []string{\" \", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"}\n\ts := \"\"\n\tparams := mux.Vars(r)\n\tnum := params[\"num\"]\n\tctr, err := strconv.Atoi(num)\n\tif err != nil {\n\t\tctr = 10\n\t}\n\tif ctr > 1000 {\n\t\tctr = 1000\n\t}\n\n\ts2 := rand.NewSource(time.Now().UnixNano())\n\tr2 := rand.New(s2)\n\n\tfor i := 0; i < 1024*ctr; i++ {\n\t\t//s += \"c\"\n\t\ts += chars[r2.Intn(37)]\n\t}\n\tjson.NewEncoder(w).Encode(s)\n}", "func HTTPAPIServerStreamHLSM3U8(c *gin.Context) {\n\trequestLogger := log.WithFields(logrus.Fields{\n\t\t\"module\": \"http_hls\",\n\t\t\"stream\": c.Param(\"uuid\"),\n\t\t\"channel\": c.Param(\"channel\"),\n\t\t\"func\": \"HTTPAPIServerStreamHLSM3U8\",\n\t})\n\n\tif !Storage.StreamChannelExist(c.Param(\"uuid\"), c.Param(\"channel\")) {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotFound.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamChannelExist\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\n\tif !RemoteAuthorization(\"HLS\", c.Param(\"uuid\"), c.Param(\"channel\"), c.Param(\"token\"), c.ClientIP()) {\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"RemoteAuthorization\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\n\tc.Header(\"Content-Type\", \"application/x-mpegURL\")\n\tStorage.StreamChannelRun(c.Param(\"uuid\"), c.Param(\"channel\"))\n\t//If stream mode on_demand need wait ready segment's\n\tfor i := 0; i < 40; i++ {\n\t\tindex, seq, err := Storage.StreamHLSm3u8(c.Param(\"uuid\"), c.Param(\"channel\"))\n\t\tif err != nil {\n\t\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\"call\": \"StreamHLSm3u8\",\n\t\t\t}).Errorln(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif seq >= 6 {\n\t\t\t_, err := c.Writer.Write([]byte(index))\n\t\t\tif err != nil {\n\t\t\t\tc.IndentedJSON(400, Message{Status: 0, Payload: err.Error()})\n\t\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\t\"call\": \"Write\",\n\t\t\t\t}).Errorln(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func TestFileServer(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"\", \"cachetest\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !keepTempDir {\n\t\tdefer os.RemoveAll(dir)\n\t} else {\n\t\tprintln(dir)\n\t}\n\n\tfs := http.FileServer(http.Dir(\"testdata\"))\n\tsrvActual := httptest.NewServer(Handler(dir, fs))\n\tsrvExpected := httptest.NewServer(fs)\n\tdefer srvActual.Close()\n\tdefer srvExpected.Close()\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tresp, err := http.Head(srvActual.URL + \"/file.txt\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t\trespExpected, err := http.Head(srvExpected.URL + \"/file.txt\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\trespExpected.Body.Close()\n\t\t\tif !headersEqual(resp.Header, respExpected.Header) {\n\t\t\t\tt.Log(resp.Request.Method, resp.StatusCode, resp.Header)\n\t\t\t\tt.Log(respExpected.Request.Method, respExpected.StatusCode, respExpected.Header)\n\t\t\t\tt.Fatal(\"headers not equal\")\n\t\t\t}\n\t\t\tresp, err = http.Get(srvActual.URL + \"/file.txt\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbuf := bytes.NewBuffer(make([]byte, 0, 256))\n\t\t\t_, err = io.Copy(buf, resp.Body)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\trespExpected, err = http.Get(srvExpected.URL + \"/file.txt\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tbufExpected := bytes.NewBuffer(make([]byte, 0, 256))\n\t\t\tdefer respExpected.Body.Close()\n\t\t\t_, err = io.Copy(bufExpected, respExpected.Body)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif !headersEqual(resp.Header, respExpected.Header) {\n\t\t\t\tt.Log(resp.Request.Method, resp.StatusCode, resp.Header)\n\t\t\t\tt.Log(respExpected.Request.Method, respExpected.StatusCode, respExpected.Header)\n\t\t\t\tt.Fatal(\"headers not equal\")\n\t\t\t}\n\t\t\tif !bytes.Equal(buf.Bytes(), bufExpected.Bytes()) {\n\t\t\t\tt.Fatal(\"bodies not equal\")\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n}", "func TestLineBufferSequential(t *testing.T) {\n\tsrc := &sourceTailer{lines: make(chan string)}\n\tbuffered := BufferedTailerWithMetrics(src)\n\tfor i := 0; i < 10000; i++ {\n\t\tsrc.lines <- fmt.Sprintf(\"This is line number %v.\", i)\n\t}\n\tfor i := 0; i < 10000; i++ {\n\t\tline := <-buffered.Lines()\n\t\tif line != fmt.Sprintf(\"This is line number %v.\", i) {\n\t\t\tt.Errorf(\"Expected 'This is line number %v', but got '%v'.\", i, line)\n\t\t}\n\t}\n\tbuffered.Close()\n\t_, stillOpen := <-buffered.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Buffered tailer was not closed.\")\n\t}\n\t_, stillOpen = <-src.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Source tailer was not closed.\")\n\t}\n}", "func StreamingMain() {\n\tstdout := bytes.NewBufferString(StreamingMainStdout)\n\tstderr := bytes.NewBufferString(StreamingMainStderr)\n\n\tfor stdout.Len() > 0 || stderr.Len() > 0 {\n\t\tos.Stdout.Write(stdout.Next(5))\n\t\tos.Stderr.Write(stderr.Next(5))\n\t}\n}", "func TestClient(t *testing.T) {\n\tt.Parallel()\n\tvar (\n\t\ts = &server{Upgraded: make(chan struct{})}\n\t\tc = NewClient().WithLogger(t.Log)\n\t)\n\n\terr := c.Connect(s, \"ws://example.org/ws\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed connecting to s: %s\", err)\n\t}\n\n\t<-s.Upgraded\n\n\tfor i := 0; i < count; i++ {\n\t\tmsg := fmt.Sprintf(\"hello, world! %d\", i)\n\n\t\terr := c.WriteMessage(websocket.TextMessage, []byte(msg))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tmT, m, err := s.ReadMessage()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif want, got := msg, string(m); want != got {\n\t\t\tt.Errorf(\"server got %s, want %s\", got, want)\n\t\t}\n\t\tif want, got := websocket.TextMessage, mT; want != got {\n\t\t\tt.Errorf(\"message type = %s , want %s\", got, want)\n\t\t}\n\n\t\ts.WriteMessage(websocket.TextMessage, []byte(msg))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tmT, m, err = c.ReadMessage()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif want, got := msg, string(m); want != got {\n\t\t\tt.Errorf(\"client got %s, want %s\", got, want)\n\t\t}\n\t\tif want, got := websocket.TextMessage, mT; want != got {\n\t\t\tt.Errorf(\"message type = %s , want %s\", got, want)\n\t\t}\n\t}\n\n\terr = c.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = s.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (e *Helloworlde) Stream(ctx context.Context, req *helloworlde.StreamingRequest, stream helloworlde.Helloworlde_StreamStream) error {\n\tlog.Infof(\"Received Helloworlde.Stream request with count: %d\", req.Count)\n\n\tfor i := 0; i < int(req.Count); i++ {\n\t\tlog.Infof(\"Responding: %d\", i)\n\t\tif err := stream.Send(&helloworlde.StreamingResponse{\n\t\t\tCount: int64(i),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestSecureBuffers(t *testing.T) {\n\ttests := []struct {\n\t\tsourceData []byte\n\t}{\n\t\t{[]byte(\"this is a test\")},\n\t\t{make([]byte, maxChunkSize-1)},\n\t\t{make([]byte, maxChunkSize+1)},\n\t\t{make([]byte, maxChunkSize*10)},\n\t\t{make([]byte, maxChunkSize)},\n\t\t{func() []byte {\n\t\t\tres := make([]byte, 300e6) // 300 mb\n\t\t\t_, err := io.ReadFull(rand.Reader, res)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\treturn res\n\t\t}()},\n\t}\n\tfor _, test := range tests {\n\t\tt.Log(\"testing with\", len(test.sourceData), \"B of data\")\n\t\tresult := new(bytes.Buffer)\n\t\tskb := make([]byte, 32)\n\t\t_, err := rand.Read(skb)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tvar sk [32]byte\n\t\tcopy(sk[:], skb)\n\t\tencWriter := NewWriter(sk, result)\n\t\tif len(encWriter.buf) > maxChunkSize*3 { // there should never be more than 3 chunks buffered in memory\n\t\t\tt.Fatal(\"encWriter is leaking chunks\")\n\t\t}\n\t\tn, err := encWriter.Write(test.sourceData)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif n != len(test.sourceData) {\n\t\t\tt.Fatal(\"output was not the correct length got\", n, \"wanted\", len(test.sourceData))\n\t\t}\n\t\tif !sufficientEntropy(result.Bytes()) {\n\t\t\tt.Fatal(\"resulting output was not uniformly random\")\n\t\t}\n\t\tif nonceReuse(result.Bytes()) {\n\t\t\tt.Fatal(\"resulting ciphertext has re-used nonces!\")\n\t\t}\n\t\tdecReader := NewReader(sk, result)\n\t\tdecryptedData := make([]byte, len(test.sourceData))\n\t\t_, err = decReader.Read(decryptedData)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif len(decReader.buf) > maxChunkSize*3 { // there should never be more than 3 chunks buffered in memory\n\t\t\tt.Fatal(\"decReader is leaking chunks\")\n\t\t}\n\t\tif !bytes.Equal(decryptedData, test.sourceData) {\n\t\t\tt.Fatal(\"data decrypt mismatch got\", decryptedData, \"wanted\", test.sourceData)\n\t\t}\n\t}\n}", "func TestApiSpeed (t *testing.T) {\n\tgo setUpApi() \t//run the service asynchronously\n\n\tclient := http.Client{\n\t\tTimeout: time.Second * 2,\n\t} //Initialize the client\n\n\n\tfor i := 10990; i < 11010 ; i++{\n\t\tstart:= time.Now()\n\t\tcallApiWithCount(i,client)\n\t\telapsed := time.Since(start)\n\t\tt.Logf(\"%v took %s\\n\", i, elapsed)\n\t}\n\n}", "func (server) LongGreet(stream greetpb.GreetService_LongGreetServer) error {\n\tresult := \"\"\n\tfor {\n\t\treq, err := stream.Recv()\n\n\t\tif err == io.EOF {\n\t\t\t// we received end of stream from client\n\t\t\treturn stream.SendAndClose(&greetpb.LongGreetResponse{\n\t\t\t\tResult: result,\n\t\t\t})\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error while reading the client stream %v\", err)\n\t\t}\n\n\t\tname := req.Name\n\t\tresult += \"Hello \" + name + \"!\"\n\t}\n\n\treturn nil\n}", "func runEchoClientTPC(b *testing.B, payloadSize int) {\n\tb.ReportAllocs()\n\tinternal.CallEcho(b, tpcCtx, serverAddr, b.N, payloadSize, false, benchmark.AddStats(b, 16))\n}", "func (t testConn) NewStream(ctx context.Context) (network.Stream, error) { return nil, nil }", "func sendBenchmarkedRequest(client *RequestClient, fields []string, size int, c chan time.Duration) {\n\tstart := time.Now()\n\tclient.SendRequest(fields, size)\n\tc <- time.Since(start)\n}", "func SubtestStress1Conn100Stream100Msg10MB(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestStress1Conn100Stream100Msg10MB(t, tr)\n}", "func StreamServerInterceptor(label string) grpc.StreamServerInterceptor {\n\treturn func(\n\t\tsrv interface{},\n\t\tstream grpc.ServerStream,\n\t\tinfo *grpc.StreamServerInfo,\n\t\thandler grpc.StreamHandler,\n\t) error {\n\t\tstarted := time.Now()\n\t\tctx := stream.Context()\n\t\tmd, _ := metadata.FromIncomingContext(ctx)\n\t\tmetadataCopy := md.Copy()\n\n\t\ttracer := otel.Tracer(label)\n\t\tprop := otel.GetTextMapPropagator()\n\t\tctx = prop.Extract(ctx, &metadataSupplier{\n\t\t\tmetadata: &metadataCopy,\n\t\t})\n\n\t\tctx, span := tracer.Start(ctx, info.FullMethod)\n\t\tctx = logz.StartCollectingSeverity(ctx)\n\n\t\twrapped := &serverStream{\n\t\t\tServerStream: stream,\n\t\t\tctx: ctx,\n\t\t}\n\t\tvar err error\n\t\tdefer func() {\n\t\t\tua, ip := extractUAAndIP(md)\n\t\t\treqSize := int(wrapped.requestSize)\n\t\t\tresSize := int(wrapped.responseSize)\n\t\t\tcode := httpStatusFromCode(status.Code(err))\n\n\t\t\tlogz.AccessLog(ctx, \"gRPC Server Streaming\", info.FullMethod,\n\t\t\t\tua, ip, \"HTTP/2\",\n\t\t\t\tcode, reqSize, resSize, time.Since(started))\n\t\t\tspan.End()\n\t\t}()\n\n\t\terr = handler(srv, wrapped)\n\t\treturn err\n\t}\n}", "func TestLatencyTestReal(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping test in short mode.\")\n\t}\n\tserverID := \"16976\"\n\n\tconfig := configuration{\n\t\tServerID: serverID,\n\t\tTimeout: 5,\n\t\t//MaxSeconds: 4.0,\n\t}\n\n\tserver := GetServerByID(serverID)\n\tserver.Configuration = &config\n\n\tlocalAddr := net.TCPAddr{}\n\tsource, _ := net.ResolveTCPAddr(\"tcp\", localAddr.String())\n\n\tspdTest := speedtest{\n\t\tSource: source,\n\t}\n\n\tserver.Speedtest = &spdTest\n\tspdTest.Server = &server\n\n\tLatencyTest(&server)\n\tallResults := server.Results\n\n\tresults := allResults.Latency.Seconds()\n\n\tif results <= 0 {\n\t\tt.Fatalf(\"Error: Expected a positive Latency result, but got: %f, err: %s\", results, allResults.Error)\n\t}\n\tfmt.Printf(\"\\nLatency test results for server %s ... %f\\n\", serverID, results)\n}", "func TestStubCollector(t *testing.T) {\n\tts1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"Total Accesses: 16147\")\n\t\tfmt.Fprintln(w, \"Total kBytes: 12988\")\n\t\tfmt.Fprintln(w, \"CPULoad: .000408393\")\n\t\tfmt.Fprintln(w, \"Uptime: 3229728\")\n\t\tfmt.Fprintln(w, \"ReqPerSec: .00499949\")\n\t\tfmt.Fprintln(w, \"BytesPerSec: 4.1179\")\n\t\tfmt.Fprintln(w, \"BytesPerReq: 823.665\")\n\t\tfmt.Fprintln(w, \"BusyWorkers: 1\")\n\t\tfmt.Fprintln(w, \"IdleWorkers: 8\")\n\t\tfmt.Fprintln(w, \"ConnsTotal: 4940\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncWriting: 527\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncKeepAlive: 1321\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncClosing: 2785\")\n\t\tfmt.Fprintln(w, \"ServerUptimeSeconds: 43\")\n\t\tfmt.Fprintln(w, \"Load1: 0.01\")\n\t\tfmt.Fprintln(w, \"Load5: 0.10\")\n\t\tfmt.Fprintln(w, \"Load15: 0.06\")\n\t\tfmt.Fprintln(w, \"CPUUser: 0\")\n\t\tfmt.Fprintln(w, \"CPUSystem: .01\")\n\t\tfmt.Fprintln(w, \"CPUChildrenUser: 0\")\n\t\tfmt.Fprintln(w, \"CPUChildrenSystem: 0\")\n\t\tfmt.Fprintln(w, \"Scoreboard: _W____........___...............................................................................................................................................................................................................................................\")\n\t}))\n\tdefer ts1.Close()\n\n\tab1 := ApacheBeat{}\n\tu1, _ := url.Parse(ts1.URL)\n\ts1, _ := ab1.GetServerStatus(*u1)\n\n\tassert.Equal(t, s1[\"totalAccesses\"].(int), 16147)\n\tassert.Equal(t, s1[\"totalKBytes\"].(int), 12988)\n\tassert.Equal(t, s1[\"reqPerSec\"].(float64), 0.00499949)\n\tassert.Equal(t, s1[\"bytesPerSec\"].(float64), 4.1179)\n\tassert.Equal(t, s1[\"bytesPerReq\"].(float64), 823.665)\n\tassert.Equal(t, s1[\"busyWorkers\"].(int), 1)\n\tassert.Equal(t, s1[\"idleWorkers\"].(int), 8)\n\n\tup1 := s1[\"uptime\"].(common.MapStr)\n\tassert.Equal(t, up1[\"uptime\"].(int), 3229728)\n\tassert.Equal(t, up1[\"serverUptimeSeconds\"].(int), 43)\n\n\tc1 := s1[\"connections\"].(common.MapStr)\n\tassert.Equal(t, c1[\"connsTotal\"].(int), 4940)\n\tassert.Equal(t, c1[\"connsAsyncWriting\"].(int), 527)\n\tassert.Equal(t, c1[\"connsAsyncKeepAlive\"].(int), 1321)\n\tassert.Equal(t, c1[\"connsAsyncClosing\"].(int), 2785)\n\t//assert.Equal(t, s1[\"host_url\"], \"localhost\")\n\n\tl1 := s1[\"load\"].(common.MapStr)\n\tassert.Equal(t, l1[\"load1\"].(float64), 0.01)\n\tassert.Equal(t, l1[\"load5\"].(float64), 0.10)\n\tassert.Equal(t, l1[\"load15\"].(float64), 0.06)\n\n\tcpu1 := s1[\"cpu\"].(common.MapStr)\n\tassert.Equal(t, cpu1[\"cpuLoad\"].(float64), 0.000408393)\n\tassert.Equal(t, cpu1[\"cpuUser\"].(float64), float64(0))\n\tassert.Equal(t, cpu1[\"cpuSystem\"].(float64), 0.01)\n\tassert.Equal(t, cpu1[\"cpuChildrenUser\"].(float64), float64(0))\n\tassert.Equal(t, cpu1[\"cpuChildrenSystem\"].(float64), float64(0))\n\n\tscb1 := s1[\"scoreboard\"].(common.MapStr)\n\tassert.Equal(t, scb1[\"startingUp\"].(int), 0)\n\tassert.Equal(t, scb1[\"readingRequest\"].(int), 0)\n\tassert.Equal(t, scb1[\"sendingReply\"].(int), 1)\n\tassert.Equal(t, scb1[\"keepalive\"].(int), 0)\n\tassert.Equal(t, scb1[\"dnsLookup\"].(int), 0)\n\tassert.Equal(t, scb1[\"closingConnection\"].(int), 0)\n\tassert.Equal(t, scb1[\"logging\"].(int), 0)\n\tassert.Equal(t, scb1[\"gracefullyFinishing\"].(int), 0)\n\tassert.Equal(t, scb1[\"idleCleanup\"].(int), 0)\n\tassert.Equal(t, scb1[\"openSlot\"].(int), 247)\n\tassert.Equal(t, scb1[\"waitingForConnection\"].(int), 8)\n\tassert.Equal(t, scb1[\"total\"].(int), 256)\n\n\t// BusyWorkers: 1\n\t// IdleWorkers: 4\n\t// Scoreboard: W____...........................................................................................................................................................................................................................................................\n\n\tts2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"BusyWorkers: 3\")\n\t\tfmt.Fprintln(w, \"IdleWorkers: 15\")\n\t\tfmt.Fprintln(w, \"Scoreboard: W____...........................................................................................................................................................................................................................................................\")\n\t}))\n\tdefer ts2.Close()\n\n\tab2 := ApacheBeat{}\n\tu2, _ := url.Parse(ts2.URL)\n\ts2, _ := ab2.GetServerStatus(*u2)\n\n\tassert.Equal(t, s2[\"totalAccesses\"].(int), 0)\n\tassert.Equal(t, s2[\"totalKBytes\"].(int), 0)\n\tassert.Equal(t, s2[\"reqPerSec\"].(float64), float64(0))\n\tassert.Equal(t, s2[\"bytesPerSec\"].(float64), float64(0))\n\tassert.Equal(t, s2[\"bytesPerReq\"].(float64), float64(0))\n\tassert.Equal(t, s2[\"busyWorkers\"].(int), 3)\n\tassert.Equal(t, s2[\"idleWorkers\"].(int), 15)\n\n\tup2 := s2[\"uptime\"].(common.MapStr)\n\tassert.Equal(t, up2[\"uptime\"].(int), 0)\n\tassert.Equal(t, up2[\"serverUptimeSeconds\"].(int), 0)\n\n\tc2 := s2[\"connections\"].(common.MapStr)\n\tassert.Equal(t, c2[\"connsTotal\"].(int), 0)\n\tassert.Equal(t, c2[\"connsAsyncWriting\"].(int), 0)\n\tassert.Equal(t, c2[\"connsAsyncKeepAlive\"].(int), 0)\n\tassert.Equal(t, c2[\"connsAsyncClosing\"].(int), 0)\n\t//assert.Equal(t, s2[\"host_url\"], \"localhost\")\n\n\tl2 := s2[\"load\"].(common.MapStr)\n\tassert.Equal(t, l2[\"load1\"].(float64), float64(0))\n\tassert.Equal(t, l2[\"load5\"].(float64), float64(0))\n\tassert.Equal(t, l2[\"load15\"].(float64), float64(0))\n\n\tcpu2 := s2[\"cpu\"].(common.MapStr)\n\tassert.Equal(t, cpu2[\"cpuLoad\"].(float64), float64(0))\n\tassert.Equal(t, cpu2[\"cpuUser\"].(float64), float64(0))\n\tassert.Equal(t, cpu2[\"cpuSystem\"].(float64), float64(0))\n\tassert.Equal(t, cpu2[\"cpuChildrenUser\"].(float64), float64(0))\n\tassert.Equal(t, cpu2[\"cpuChildrenSystem\"].(float64), float64(0))\n\n\tscb2 := s2[\"scoreboard\"].(common.MapStr)\n\tassert.Equal(t, scb2[\"startingUp\"].(int), 0)\n\tassert.Equal(t, scb2[\"readingRequest\"].(int), 0)\n\tassert.Equal(t, scb2[\"sendingReply\"].(int), 1)\n\tassert.Equal(t, scb2[\"keepalive\"].(int), 0)\n\tassert.Equal(t, scb2[\"dnsLookup\"].(int), 0)\n\tassert.Equal(t, scb2[\"closingConnection\"].(int), 0)\n\tassert.Equal(t, scb2[\"logging\"].(int), 0)\n\tassert.Equal(t, scb2[\"gracefullyFinishing\"].(int), 0)\n\tassert.Equal(t, scb2[\"idleCleanup\"].(int), 0)\n\tassert.Equal(t, scb2[\"openSlot\"].(int), 251)\n\tassert.Equal(t, scb2[\"waitingForConnection\"].(int), 4)\n\tassert.Equal(t, scb2[\"total\"].(int), 256)\n\n\t// Total Accesses: 491803362\n\t// Total kBytes: 21453176370\n\t// CPULoad: .84122\n\t// Uptime: 3761632\n\t// ReqPerSec: 130.742\n\t// BytesPerSec: 5840030\n\t// BytesPerReq: 44668.4\n\t// BusyWorkers: 1298\n\t// IdleWorkers: 652\n\t// ConnsTotal: 3264\n\t// ConnsAsyncWriting: 82\n\t// ConnsAsyncKeepAlive: 1574\n\t// ConnsAsyncClosing: 309\n\t// ServerUptimeSeconds: 5632\n\t// Load1: 1.01\n\t// Load5: 1.50\n\t// Load15: 2.06\n\t// CPUUser: 0.5\n\t// CPUSystem: .01\n\t// CPUChildrenUser: .1\n\t// CPUChildrenSystem: 1.99\n\t// Scoreboard: RRR_R__RR_RLRR_RRRRRRRRRR_RRR_RRRRR__R___RRR_R_RRWRR_R______RWRR___RR_RR_RRRR_WR_R__W_RR__RRRR_____RR___RRRWRR__RRR_R_RRR_RW_RR_RRR_WRRRR__R__RRRR_RRRW_RRRRR_RRRRRR_RRRR_RRRWRWRRRRRR_R_R____R___RRR_W__RRRRRR_RR_W__R_RRRRRRR_RR_RRR____W_RRRR_RRRW_RRRRRR_RR_RR___R_RRRRRRRR_RR__RRRR__RRRRR_RWR__RRWRRRR__RR_RRWWR_R_RWRR__R_RR_RRRRRWR___RW_RR__RR_R_RWRRR_RRRRRRW___R_RRRR_RRR__RRRRWR___R_R__RRR__RRRW_RRRR__RRWR_RRR__L_R_R__R_R_R_R__WRRRRRRRR__RWRRRW_RRWRRRWWL__RR_R__R_RRR____RRRRRR_RWRRRR_R_RRR_R__R_RR_R_RRRRR_RRRW_RR_RRRRRRRRR_RRRRR_RRRRR_RRRRRRRRWR_RRRRRR_R_RR_RR__R__R_RR_R_R_R_R__R_W__RRR_WRR_R_R__WRRR_RRRRR__RRRRRW_WRRR___RRRRRR_R_RRRRRRR_RR__R_RR_RR_RRRRR__W_R_WR__RRRRRR__RR_RR_R_R_RWRWRRRR_____WRRRRRRRRR_R_RRR_RRRRRRRRR_RR____RRRRWRRR_RR_R_WRRR___R_RRRR_RRRR_RR_W___RW_RRR_RRWRRRWWRRR_RRRRR_R_R_RR_RWR_R_R__RR_RR_RRWR_R_WRRWRWRRRR_RRWRR_RWRR_R_RRRR____R___RRR_W_RR__RR_R_RRRRRRRRRWRRRRRWR_RW__R__WR_RRW_R_RWRRWRR_R_R_RR__W_R___RR_RRR_RRWRRRRRR__RRRRRW_RRRR_WRRRRRRR__RRRWRWR_RR_RR___RRRW___RW__R__RRRRRRRWR_RR_RRRRR_RRRRRWRRRRR_RRR_RWR_RRRR__RR_RRR__RRRWWR_RRWRR__R_R_RWRRR___RRRRRRRR_RR_RR_WRW_RR_RRRRR_RRRRR_R_RRRWWRRRR_WRRRRRRRRRRR_RR_WRRRRW_RR_WRWRWRRRRW_WR__W_RR__RRR_W_RR_R___R_R____RR_WRRR_R_R_R_WRWRRRR_WR_RR_RRWR__RRRRRRRR_RRR__R_R___RRRRRRR__R_R_R__W__RRRRR_RRRRRRR_R_R_RW_W____RR__R_RRW_R_RRRRRWRRR_R__R_RRRRRRR__RRRRWRRRRR_RRRWRRRWW_RW_R_R_RR_____RRRW_RRRRRWRWRR_R__R_R_R__RRRRRRRRR_RRRRRRRRRR_RRRRRR_R_R__WRR_RR_RR__WRRR_RR_RRRR_R_RWWR___R_R_RRRR_R_RRRRWRRR_RRRRR_RRRRRRR_R___RR_____RRR__RRW__R__RR_____R_RR_____RR_W___R_R_____RRRR__R_RR_R__RR______R_RRR_RRRRWRW_R__RR__W__RRRR_WR_R__RRR__RR_RRRRR__R_W_________RR__WR_____R__W_RR_RR_RW_RRRRWRRRR___RWRR_WRRRRRR__R_RRR__R__RR__WWRR__RRRRR__RRR_RRR_RR_RR_RRRRR_RRRRRR_RRR_WRW_RRRW_RRRR__R_RWRRRRR_RR__RRRWRRR____RRWRR____RRRRRRW_......................................................................................................................................................R____R_RRRR_R__RR__R_RWR_RR__R__R_RRRR___RRRR_R_RRW__R__RRR_RRRR_R____RR_RRRRR_RR_RR___RRRR_RR_RR__R_RR___R_R_R_RR___RR_R__R____RR_RR__R__R__RRR__WRRW..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\n\n\tts3 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"Total Accesses: 491803362\")\n\t\tfmt.Fprintln(w, \"Total kBytes: 21453176370\")\n\t\tfmt.Fprintln(w, \"CPULoad: .84122\")\n\t\tfmt.Fprintln(w, \"Uptime: 3761632\")\n\t\tfmt.Fprintln(w, \"ReqPerSec: 130.742\")\n\t\tfmt.Fprintln(w, \"BytesPerSec: 5840030\")\n\t\tfmt.Fprintln(w, \"BytesPerReq: 44668.4\")\n\t\tfmt.Fprintln(w, \"BusyWorkers: 1298\")\n\t\tfmt.Fprintln(w, \"IdleWorkers: 652\")\n\t\tfmt.Fprintln(w, \"ConnsTotal: 3264\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncWriting: 82\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncKeepAlive: 1574\")\n\t\tfmt.Fprintln(w, \"ConnsAsyncClosing: 309\")\n\t\tfmt.Fprintln(w, \"ServerUptimeSeconds: 5632\")\n\t\tfmt.Fprintln(w, \"Load1: 1.01\")\n\t\tfmt.Fprintln(w, \"Load5: 1.50\")\n\t\tfmt.Fprintln(w, \"Load15: 2.06\")\n\t\tfmt.Fprintln(w, \"CPUUser: 0.5\")\n\t\tfmt.Fprintln(w, \"CPUSystem: .01\")\n\t\tfmt.Fprintln(w, \"CPUChildrenUser: .1\")\n\t\tfmt.Fprintln(w, \"CPUChildrenSystem: 1.99\")\n\t\tfmt.Fprintln(w, \"Scoreboard: RRR_R__RR_RLRR_RRRRRRRRRR_RRR_RRRRR__R___RRR_R_RRWRR_R______RWRR___RR_RR_RRRR_WR_R__W_RR__RRRR_____RR___RRRWRR__RRR_R_RRR_RW_RR_RRR_WRRRR__R__RRRR_RRRW_RRRRR_RRRRRR_RRRR_RRRWRWRRRRRR_R_R____R___RRR_W__RRRRRR_RR_W__R_RRRRRRR_RR_RRR____W_RRRR_RRRW_RRRRRR_RR_RR___R_RRRRRRRR_RR__RRRR__RRRRR_RWR__RRWRRRR__RR_RRWWR_R_RWRR__R_RR_RRRRRWR___RW_RR__RR_R_RWRRR_RRRRRRW___R_RRRR_RRR__RRRRWR___R_R__RRR__RRRW_RRRR__RRWR_RRR__L_R_R__R_R_R_R__WRRRRRRRR__RWRRRW_RRWRRRWWL__RR_R__R_RRR____RRRRRR_RWRRRR_R_RRR_R__R_RR_R_RRRRR_RRRW_RR_RRRRRRRRR_RRRRR_RRRRR_RRRRRRRRWR_RRRRRR_R_RR_RR__R__R_RR_R_R_R_R__R_W__RRR_WRR_R_R__WRRR_RRRRR__RRRRRW_WRRR___RRRRRR_R_RRRRRRR_RR__R_RR_RR_RRRRR__W_R_WR__RRRRRR__RR_RR_R_R_RWRWRRRR_____WRRRRRRRRR_R_RRR_RRRRRRRRR_RR____RRRRWRRR_RR_R_WRRR___R_RRRR_RRRR_RR_W___RW_RRR_RRWRRRWWRRR_RRRRR_R_R_RR_RWR_R_R__RR_RR_RRWR_R_WRRWRWRRRR_RRWRR_RWRR_R_RRRR____R___RRR_W_RR__RR_R_RRRRRRRRRWRRRRRWR_RW__R__WR_RRW_R_RWRRWRR_R_R_RR__W_R___RR_RRR_RRWRRRRRR__RRRRRW_RRRR_WRRRRRRR__RRRWRWR_RR_RR___RRRW___RW__R__RRRRRRRWR_RR_RRRRR_RRRRRWRRRRR_RRR_RWR_RRRR__RR_RRR__RRRWWR_RRWRR__R_R_RWRRR___RRRRRRRR_RR_RR_WRW_RR_RRRRR_RRRRR_R_RRRWWRRRR_WRRRRRRRRRRR_RR_WRRRRW_RR_WRWRWRRRRW_WR__W_RR__RRR_W_RR_R___R_R____RR_WRRR_R_R_R_WRWRRRR_WR_RR_RRWR__RRRRRRRR_RRR__R_R___RRRRRRR__R_R_R__W__RRRRR_RRRRRRR_R_R_RW_W____RR__R_RRW_R_RRRRRWRRR_R__R_RRRRRRR__RRRRWRRRRR_RRRWRRRWW_RW_R_R_RR_____RRRW_RRRRRWRWRR_R__R_R_R__RRRRRRRRR_RRRRRRRRRR_RRRRRR_R_R__WRR_RR_RR__WRRR_RR_RRRR_R_RWWR___R_R_RRRR_R_RRRRWRRR_RRRRR_RRRRRRR_R___RR_____RRR__RRW__R__RR_____R_RR_____RR_W___R_R_____RRRR__R_RR_R__RR______R_RRR_RRRRWRW_R__RR__W__RRRR_WR_R__RRR__RR_RRRRR__R_W_________RR__WR_____R__W_RR_RR_RW_RRRRWRRRR___RWRR_WRRRRRR__R_RRR__R__RR__WWRR__RRRRR__RRR_RRR_RR_RR_RRRRR_RRRRRR_RRR_WRW_RRRW_RRRR__R_RWRRRRR_RR__RRRWRRR____RRWRR____RRRRRRW_......................................................................................................................................................R____R_RRRR_R__RR__R_RWR_RR__R__R_RRRR___RRRR_R_RRW__R__RRR_RRRR_R____RR_RRRRR_RR_RR___RRRR_RR_RR__R_RR___R_R_R_RR___RR_R__R____RR_RR__R__R__RRR__WRRW..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\")\n\t}))\n\tdefer ts3.Close()\n\n\tab3 := ApacheBeat{}\n\tu3, _ := url.Parse(ts3.URL)\n\ts3, _ := ab3.GetServerStatus(*u3)\n\n\tassert.Equal(t, s3[\"totalAccesses\"].(int), 491803362)\n\tassert.Equal(t, s3[\"totalKBytes\"].(int), 21453176370)\n\tassert.Equal(t, s3[\"reqPerSec\"].(float64), 130.742)\n\tassert.Equal(t, s3[\"bytesPerSec\"].(float64), float64(5840030))\n\tassert.Equal(t, s3[\"bytesPerReq\"].(float64), 44668.4)\n\tassert.Equal(t, s3[\"busyWorkers\"].(int), 1298)\n\tassert.Equal(t, s3[\"idleWorkers\"].(int), 652)\n\n\tup3 := s3[\"uptime\"].(common.MapStr)\n\tassert.Equal(t, up3[\"uptime\"].(int), 3761632)\n\tassert.Equal(t, up3[\"serverUptimeSeconds\"].(int), 5632)\n\n\tc3 := s3[\"connections\"].(common.MapStr)\n\tassert.Equal(t, c3[\"connsTotal\"].(int), 3264)\n\tassert.Equal(t, c3[\"connsAsyncWriting\"].(int), 82)\n\tassert.Equal(t, c3[\"connsAsyncKeepAlive\"].(int), 1574)\n\tassert.Equal(t, c3[\"connsAsyncClosing\"].(int), 309)\n\t//assert.Equal(t, s3[\"host_url\"], \"localhost\")\n\n\tl3 := s3[\"load\"].(common.MapStr)\n\tassert.Equal(t, l3[\"load1\"].(float64), 1.01)\n\tassert.Equal(t, l3[\"load5\"].(float64), 1.50)\n\tassert.Equal(t, l3[\"load15\"].(float64), 2.06)\n\n\tcpu3 := s3[\"cpu\"].(common.MapStr)\n\tassert.Equal(t, cpu3[\"cpuLoad\"].(float64), 0.84122)\n\tassert.Equal(t, cpu3[\"cpuUser\"].(float64), 0.5)\n\tassert.Equal(t, cpu3[\"cpuSystem\"].(float64), 0.01)\n\tassert.Equal(t, cpu3[\"cpuChildrenUser\"].(float64), 0.1)\n\tassert.Equal(t, cpu3[\"cpuChildrenSystem\"].(float64), 1.99)\n\n\tscb3 := s3[\"scoreboard\"].(common.MapStr)\n\tassert.Equal(t, scb3[\"startingUp\"].(int), 0)\n\tassert.Equal(t, scb3[\"readingRequest\"].(int), 1150)\n\tassert.Equal(t, scb3[\"sendingReply\"].(int), 145)\n\tassert.Equal(t, scb3[\"keepalive\"].(int), 0)\n\tassert.Equal(t, scb3[\"dnsLookup\"].(int), 0)\n\tassert.Equal(t, scb3[\"closingConnection\"].(int), 0)\n\tassert.Equal(t, scb3[\"logging\"].(int), 3)\n\tassert.Equal(t, scb3[\"gracefullyFinishing\"].(int), 0)\n\tassert.Equal(t, scb3[\"idleCleanup\"].(int), 0)\n\tassert.Equal(t, scb3[\"openSlot\"].(int), 1800)\n\tassert.Equal(t, scb3[\"waitingForConnection\"].(int), 652)\n\tassert.Equal(t, scb3[\"total\"].(int), 3750)\n}", "func init() {\n\tserverDown = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write([]byte(`hello`))\n\t\t\t},\n\t\t),\n\t)\n\tdefer func() { serverDown.Close() }()\n\n\tserverBadBody = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write([]byte(`<!# SOME BAD--XML_/__.*__\\\\fhji(*&^%^%<Boo<HA/>/>$%^&Y*(J)OPKL:/>`))\n\t\t\t},\n\t\t),\n\t)\n\n\t// init test servers...\n\tserverPNRDetails = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(samplePNRRes)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverPNRDetails.Close() }()\n\n\tserverBizLogic = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(samplePNRResWarnBizLogic)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverBizLogic.Close() }()\n\n\tserverEndTBizLogic = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(sampleEndTBizLogic)\n\t\t\t},\n\t\t),\n\t)\n\n\tserverEndT = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(sampleEndTRS)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverEndT.Close() }()\n}", "func ControlStream(conn net.Conn) *Control {\n\tconst pongChSize = 10\n\n\tctrl := &Control{\n\t\tconn: conn,\n\t\tpongCh: make(chan time.Time, pongChSize),\n\t\tdoneCh: make(chan struct{}),\n\t}\n\tgo ctrl.serve()\n\n\treturn ctrl\n}", "func (self *nntpConnection) runConnection(daemon NNTPDaemon, inbound, stream, reader bool, preferMode string, conn *textproto.Conn) {\n\n var err error\n var line string\n var success bool\n\n for err == nil {\n if self.mode == \"\" {\n if inbound {\n // no mode and inbound\n line, err = conn.ReadLine()\n if len(line) == 0 {\n conn.Close()\n return\n } else if line == \"QUIT\" {\n conn.PrintfLine(\"205 bai\")\n conn.Close()\n return\n }\n parts := strings.Split(line, \" \")\n cmd := parts[0]\n if cmd == \"CAPABILITIES\" {\n // write capabilities\n conn.PrintfLine(\"101 i support to the following:\")\n dw := conn.DotWriter()\n caps := []string{\"VERSION 2\", \"READER\", \"STREAMING\", \"IMPLEMENTATION srndv2\"}\n for _, cap := range caps {\n io.WriteString(dw, cap)\n io.WriteString(dw, \"\\n\")\n }\n dw.Close()\n log.Println(self.name, \"sent Capabilities\")\n } else if cmd == \"MODE\" {\n if len(parts) == 2 {\n if parts[1] == \"READER\" {\n // set reader mode\n self.mode = \"READER\"\n // we'll allow posting for reader\n conn.PrintfLine(\"201 Not Posting Permitted Yo\")\n } else if parts[1] == \"STREAM\" {\n // set streaming mode\n conn.PrintfLine(\"203 Stream it brah\")\n self.mode = \"STREAM\"\n log.Println(self.name, \"streaming enabled\")\n go self.startStreaming(daemon, reader, conn)\n }\n }\n } else {\n // handle a it as a command, we don't have a mode set\n parts := strings.Split(line, \" \")\n var code64 int64\n code64, err = strconv.ParseInt(parts[0], 10, 32)\n if err == nil {\n err = self.handleLine(daemon, int(code64), line[4:], conn)\n } else {\n err = self.handleLine(daemon, 0, line, conn)\n }\n }\n } else { // no mode and outbound\n if preferMode == \"stream\" {\n // try outbound streaming\n if stream {\n success, err = self.modeSwitch(\"STREAM\", conn)\n self.mode = \"STREAM\"\n if success {\n // start outbound streaming in background\n go self.startStreaming(daemon, reader, conn)\n }\n }\n } else if reader {\n // try reader mode\n success, err = self.modeSwitch(\"READER\", conn)\n if success {\n self.mode = \"READER\"\n self.startReader(daemon, conn)\n }\n }\n if success {\n log.Println(self.name, \"mode set to\", self.mode)\n } else {\n // bullshit\n // we can't do anything so we quit\n log.Println(self.name, \"can't stream or read, wtf?\")\n conn.PrintfLine(\"QUIT\")\n conn.Close()\n return\n }\n }\n } else {\n // we have our mode set\n line, err = conn.ReadLine()\n if err == nil {\n parts := strings.Split(line, \" \")\n var code64 int64\n code64, err = strconv.ParseInt(parts[0], 10, 32)\n if err == nil {\n err = self.handleLine(daemon, int(code64), line[4:], conn)\n } else {\n err = self.handleLine(daemon, 0, line, conn)\n }\n }\n }\n }\n log.Println(self.name, \"got error\", err)\n if ! inbound {\n // send quit on outbound\n conn.PrintfLine(\"QUIT\")\n }\n conn.Close()\n}", "func handleClient(conn net.Conn) {\n var buf [512]byte\n\n for {\n nBytes, readErr := conn.Read(buf[0:])\n\n if readErr != nil {\n continue\n }\n\n http.ParseHttpRequest(string(buf[0:]))\n\n // Echo request back to client.\n _, writeErr := conn.Write(buf[0:nBytes])\n\n if writeErr != nil {\n return\n }\n }\n}", "func BenchmarkTCPFindCipherFail(b *testing.B) {\n\tb.StopTimer()\n\tb.ResetTimer()\n\n\tlistener, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 0})\n\tif err != nil {\n\t\tb.Fatalf(\"ListenTCP failed: %v\", err)\n\t}\n\n\tcipherList, err := MakeTestCiphers(ss.MakeTestSecrets(100))\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\ttestPayload := ss.MakeTestPayload(50)\n\tfor n := 0; n < b.N; n++ {\n\t\tgo func() {\n\t\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"Failed to dial %v: %v\", listener.Addr(), err)\n\t\t\t}\n\t\t\tconn.Write(testPayload)\n\t\t\tconn.Close()\n\t\t}()\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"AcceptTCP failed: %v\", err)\n\t\t}\n\t\tclientIP := clientConn.RemoteAddr().(*net.TCPAddr).IP\n\t\tb.StartTimer()\n\t\tfindAccessKey(clientConn, clientIP, cipherList)\n\t\tb.StopTimer()\n\t}\n}" ]
[ "0.708875", "0.5872227", "0.5817243", "0.58082604", "0.5704013", "0.56407464", "0.5638732", "0.55772704", "0.5568068", "0.5539785", "0.55394876", "0.5530436", "0.54894876", "0.54229844", "0.53735656", "0.53704923", "0.5354784", "0.5350201", "0.53439015", "0.5339074", "0.5302677", "0.5292338", "0.52918124", "0.52738583", "0.5266618", "0.5255678", "0.52436435", "0.52405226", "0.5221135", "0.521752", "0.52160984", "0.5215027", "0.5204563", "0.5189792", "0.51862645", "0.51738966", "0.51670104", "0.5163847", "0.5156487", "0.514686", "0.5136587", "0.51315296", "0.51254916", "0.5107928", "0.5089015", "0.50769305", "0.50761783", "0.50728315", "0.5071055", "0.50669014", "0.5063611", "0.50626796", "0.5059287", "0.5035428", "0.5028416", "0.5021489", "0.501389", "0.50137305", "0.50025284", "0.50000435", "0.49988022", "0.49787027", "0.4974993", "0.4968449", "0.49607977", "0.49331734", "0.49267003", "0.49125063", "0.49048385", "0.4901569", "0.4895414", "0.4892403", "0.4892197", "0.48885092", "0.48799947", "0.48733747", "0.48639438", "0.481935", "0.481905", "0.48118812", "0.48089042", "0.48057425", "0.48043728", "0.48038137", "0.47990057", "0.4793878", "0.4792461", "0.4792099", "0.47871625", "0.4784234", "0.47829255", "0.47818696", "0.4781074", "0.47742495", "0.47737998", "0.47697604", "0.47684297", "0.47513556", "0.47445297", "0.47397545" ]
0.7596622
0
BenchmarkPlainHandshake measures endtoend plaintext handshake performance for fasthttp client and server. It reestablishes new connection per each http request.
func BenchmarkPlainHandshake(b *testing.B) { benchmark(b, handshakeHandler, false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ServerHandshake(c net.Conn, hashes []hash.HashPair, cryptoOptions *crypto.Options) (conn net.Conn, result HandshakeResult, init []byte, err error) {\n\tconn = c\n\terr = conn.SetDeadline(time.Now().Add(90 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := make([]byte, 20+8+20+20)\n\tvar n int\n\tn, err = io.ReadAtLeast(conn, buf, len(header))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuf = buf[:n]\n\n\tok := checkHeader(buf)\n\tif ok && cryptoOptions.ForceCryptoHandshake {\n\t\terr = errors.New(\"plaintext handshake forbidden\")\n\t\treturn\n\t}\n\n\tvar skey hash.Hash\n\tif !ok && cryptoOptions.AllowCryptoHandshake {\n\t\tskeys := make([][]byte, len(hashes))\n\t\tfor i := range hashes {\n\t\t\tskeys[i] = hashes[i].First\n\t\t}\n\t\tvar ia []byte\n\t\tconn, skey, ia, err =\n\t\t\tcrypto.ServerHandshake(conn, buf, skeys, cryptoOptions)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbuf = ia\n\t\tbuf, err = readMore(conn, buf, 20, 20+8+20+20)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tok = checkHeader(buf)\n\t}\n\n\tif !ok {\n\t\terr = ErrBadHandshake\n\t\treturn\n\t}\n\n\tbuf = buf[20:]\n\tbuf, err = readMore(conn, buf, 8+20, 8+20+20)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif buf[7]&0x01 != 0 {\n\t\tresult.Dht = true\n\t}\n\tif buf[7]&0x04 != 0 {\n\t\tresult.Fast = true\n\t}\n\tif buf[5]&0x10 != 0 {\n\t\tresult.Extended = true\n\t}\n\tbuf = buf[8:]\n\n\thsh := hash.Hash(make([]byte, 20))\n\tcopy(hsh, buf)\n\tbuf = buf[20:]\n\n\tif skey != nil && !skey.Equal(hsh) {\n\t\terr = errors.New(\"crypto hash mismatch\")\n\t\treturn\n\t}\n\n\tfound := false\n\tvar h hash.HashPair\n\tfor _, h = range hashes {\n\t\tif hsh.Equal(h.First) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\terr = ErrUnknownTorrent\n\t\treturn\n\t}\n\n\tresult.Hash = hsh\n\n\thndshk := handshake(result.Hash, h.Second)\n\t_, err = conn.Write(hndshk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuf, err = readMore(conn, buf, 20, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult.Id = make([]byte, 20)\n\tcopy(result.Id, buf)\n\tbuf = buf[20:]\n\n\tif len(buf) > 0 {\n\t\tinit = make([]byte, len(buf))\n\t\tcopy(init, buf)\n\t}\n\n\treturn\n}", "func handshake(conn net.Conn, validUri string) (res http.Response, retErr error) {\n var b64ConnKey string\n\n // Properly set the status code text on exit\n defer func() {\n res.Status = http.StatusText(res.StatusCode)\n }()\n\n // Set initial response, just in case...\n res.StatusCode = http.StatusForbidden\n res.Proto = \"HTTP/1.0\"\n res.ProtoMajor = 1\n res.ProtoMinor = 0\n\n req, err := http.ReadRequest(bufio.NewReader(conn))\n if err != nil {\n retErr = errors.Wrap(err, \"Failed to receive client handshake\")\n return\n }\n\n res.Proto = req.Proto\n res.ProtoMajor = req.ProtoMajor\n res.ProtoMinor = req.ProtoMinor\n\n // 4.2.1 Reading the Client's Opening Handshake\n\n // 1. Check that it's a HTTP/1.1 or higher GET\n // (ignore \"Request-URI\" but check its presence)\n if !strings.HasPrefix(req.Proto, \"HTTP/\") {\n retErr = errors.New(fmt.Sprintf(\"Non HTTP request: '%s'\", req.Proto))\n return\n } else if req.ProtoMajor == 1 && req.ProtoMinor < 1 ||\n req.ProtoMajor < 1 {\n\n retErr = errors.New(\"Non HTTP/1.1 or higher\")\n return\n } else if req.Method != \"GET\" {\n retErr = errors.New(\"Non GET request\")\n return\n } else if req.RequestURI == \"\" {\n retErr = errors.New(\"Missing RequestURI in request\")\n return\n } else if req.RequestURI != validUri {\n retErr = errors.New(\"Invalid RequestURI\")\n return\n }\n\n // 2. Check for a |Host| header with server's authority\n if host := req.Header.Get(\"Host\"); len(host) == 0 {\n retErr = errors.New(\"Missing |Host| header field\")\n if Strict {\n return\n } else {\n fmt.Printf(\" Ignoring: %s\\n\", retErr.Error())\n retErr = nil\n }\n }\n\n // 3. Check for an |Upgrade| header == \"websocket\"\n if want, got := \"websocket\", req.Header.Get(\"Upgrade\"); want != got {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Upgrade| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 4. Check for a |Connection| header == \"Upgrade\"\n if want, got := \"Upgrade\", req.Header.Get(\"Connection\"); !strings.Contains(got, want) {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Connection| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 5. Check for a |Sec-WebSocket-Key| with the base-64 key\n if b64ConnKey = req.Header.Get(\"Sec-WebSocket-Key\"); len(b64ConnKey) == 0{\n retErr = errors.New(\"Missing |Sec-WebSocket-Key| header field\")\n return\n }\n\n // 6..10 are optional (and, therefore, ignored)\n\n // 4.2.2 Sending the Server's Opening Handshake\n\n res.Header = make (http.Header)\n\n // 1. Connection isn't HTTPS, so ignore it\n // 2. Stuff that the server can do... ignore (as it isn't a MUST)\n // 3. \"The server MAY...\": NOPE\n // 4. Maybe later\n\n // 5. Set fields required to accept the connection\n\n // 5.1 Set status as Switching Protocols\n res.StatusCode = http.StatusSwitchingProtocols\n\n // 5.2 Set |Upgrade| = \"websocket\"\n res.Header.Set(\"Upgrade\", \"websocket\")\n\n // 5.3 Set |Connection| = \"Upgrade\"\n res.Header.Set(\"Connection\", \"Upgrade\")\n\n // 5.4 Set |Sec-WebSocket-Accept| with the base_64(SHA_1(key+UIGD))\n serverKey := calculateServerResponseKey(b64ConnKey)\n res.Header.Set(\"Sec-WebSocket-Accept\", serverKey)\n\n // 5.5 Later\n // 5.6 Later\n\n return\n}", "func benchmarkConnectionEstablishment(b *testing.B, ctx *context.T, server string) {\n\tvar buf [1]byte\n\tfor i := 0; i < b.N; i++ {\n\t\t// The client and server are running with the same principal\n\t\t// here (since they are both keyed off the same 'ctx').\n\t\tcctx, cancel := context.WithCancel(ctx)\n\t\tcctx, _, err := v23.WithNewClient(cctx)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"Iteration %d/%d: %v\", i, b.N, err)\n\t\t}\n\t\t// Execute an RPC to ensure that the connection is established\n\t\t// by both ends.\n\t\tif _, err := bm.BenchmarkClient(server).Echo(cctx, buf[:]); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tcancel()\n\t}\n}", "func TestConnectOK(t *testing.T) {\n\tconnectReq := \"CONNECT %s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n\"\n\n\ttestHTTP := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t_, err = conn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestTLS := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t// HTTPS-Tunneled HTTPS\n\t\ttunnConn := tls.Client(conn, &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t})\n\t\ttunnConn.Handshake()\n\n\t\t_, err = tunnConn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(tunnConn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestRoundTrip(t, httpProxyAddr, false, httpOriginServer, testHTTP)\n\ttestRoundTrip(t, tlsProxyAddr, true, httpOriginServer, testHTTP)\n\n\ttestRoundTrip(t, httpProxyAddr, false, tlsOriginServer, testTLS)\n\ttestRoundTrip(t, tlsProxyAddr, true, tlsOriginServer, testTLS)\n}", "func TestPlainHTTPServer(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{\n\t\t// The default context uses embedded certs.\n\t\tInsecure: true,\n\t})\n\tdefer s.Stopper().Stop()\n\tts := s.(*TestServer)\n\n\thttpClient, err := s.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thttpURL := \"http://\" + ts.Ctx.HTTPAddr + healthPath\n\tif resp, err := httpClient.Get(httpURL); err != nil {\n\t\tt.Fatalf(\"error requesting health at %s: %s\", httpURL, err)\n\t} else {\n\t\tdefer resp.Body.Close()\n\t\tvar data serverpb.HealthResponse\n\t\tif err := jsonpb.Unmarshal(resp.Body, &data); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\thttpsURL := \"https://\" + ts.Ctx.HTTPAddr + healthPath\n\tif _, err := httpClient.Get(httpsURL); err == nil {\n\t\tt.Fatalf(\"unexpected success fetching %s\", httpsURL)\n\t}\n}", "func BenchmarkTLSStreaming(b *testing.B) {\n\tbenchmark(b, streamingHandler, true)\n}", "func (tc *testConn) handshake() {\n\ttc.t.Helper()\n\tif *testVV {\n\t\t*testVV = false\n\t\tdefer func() {\n\t\t\t*testVV = true\n\t\t\ttc.t.Logf(\"performed connection handshake\")\n\t\t}()\n\t}\n\tdefer func(saved map[byte]bool) {\n\t\ttc.ignoreFrames = saved\n\t}(tc.ignoreFrames)\n\ttc.ignoreFrames = nil\n\tt := tc.t\n\tdgrams := handshakeDatagrams(tc)\n\ti := 0\n\tfor {\n\t\tif i == len(dgrams)-1 {\n\t\t\tif tc.conn.side == clientSide {\n\t\t\t\twant := tc.now.Add(maxAckDelay - timerGranularity)\n\t\t\t\tif !tc.timer.Equal(want) {\n\t\t\t\t\tt.Fatalf(\"want timer = %v (max_ack_delay), got %v\", want, tc.timer)\n\t\t\t\t}\n\t\t\t\tif got := tc.readDatagram(); got != nil {\n\t\t\t\t\tt.Fatalf(\"client unexpectedly sent: %v\", got)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttc.advance(maxAckDelay)\n\t\t}\n\n\t\t// Check that we're sending exactly the data we expect.\n\t\t// Any variation from the norm here should be intentional.\n\t\tgot := tc.readDatagram()\n\t\tvar want *testDatagram\n\t\tif !(tc.conn.side == serverSide && i == 0) && i < len(dgrams) {\n\t\t\twant = dgrams[i]\n\t\t\tfillCryptoFrames(want, tc.cryptoDataOut)\n\t\t\ti++\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Fatalf(\"dgram %v:\\ngot %v\\n\\nwant %v\", i, got, want)\n\t\t}\n\t\tif i >= len(dgrams) {\n\t\t\tbreak\n\t\t}\n\n\t\tfillCryptoFrames(dgrams[i], tc.cryptoDataIn)\n\t\ttc.write(dgrams[i])\n\t\ti++\n\t}\n}", "func ClientHandshake(c net.Conn, cryptoHandshake bool, infoHash hash.Hash, myid hash.Hash, cryptoOptions *crypto.Options) (conn net.Conn, result HandshakeResult, init []byte, err error) {\n\tconn = c\n\n\terr = conn.SetDeadline(time.Now().Add(30 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\n\thshk := handshake(infoHash, myid)\n\n\tvar buf []byte\n\tif cryptoHandshake {\n\t\tconn, buf, err = crypto.ClientHandshake(\n\t\t\tconn, infoHash, hshk, cryptoOptions)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t_, err = conn.Write(hshk)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tbuf, err = readMore(conn, buf, 20+8+20+20, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !bytes.Equal(buf[:20], header) {\n\t\terr = ErrBadHandshake\n\t\treturn\n\t}\n\n\tbuf = buf[20:]\n\n\tif buf[7]&0x01 != 0 {\n\t\tresult.Dht = true\n\t}\n\tif buf[7]&0x04 != 0 {\n\t\tresult.Fast = true\n\t}\n\tif buf[5]&0x10 != 0 {\n\t\tresult.Extended = true\n\t}\n\n\tbuf = buf[8:]\n\n\tif !bytes.Equal(buf[:20], infoHash) {\n\t\terr = errors.New(\"unexpected infoHash\")\n\t\treturn\n\t}\n\tresult.Hash = make([]byte, 20)\n\tcopy(result.Hash, buf)\n\n\tbuf = buf[20:]\n\n\tresult.Id = make([]byte, 20)\n\tcopy(result.Id, buf)\n\n\tbuf = buf[20:]\n\n\tif len(buf) > 0 {\n\t\tinit = make([]byte, len(buf))\n\t\tcopy(init, buf)\n\t}\n\n\treturn\n}", "func Benchmark_Ctx_Protocol(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar res string\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tres = c.Protocol()\n\t}\n\tutils.AssertEqual(b, \"http\", res)\n}", "func (c *Conn) writeInitHandshake() error {\n\n data := make([]byte, 4, 128)\n\n // 1 byte 协议版本号\n\n data = append(data, 10)\n\n // n bytes 服务版本号[00]\n\n data = append(data, constant.ServerVersion...)\n data = append(data, 0)\n\n // 4 bytes 线程id\n data = append(data, byte(c.connectionId), byte(c.connectionId>>8), byte(c.connectionId>>16), byte(c.connectionId>>24) )\n\n // 8 bytes 随机数\n\n data = append(data, c.salt[0:8]...)\n\n // 1 bytes 填充值 0x00\n data = append(data, 0)\n\n\n // 2 bytes 服务器权能标志\n data = append(data, byte(DEFAULT_CAPABILITY), byte(DEFAULT_CAPABILITY>>8))\n\n // 1 bytes 字符编码\n data = append(data, uint8(DEFAULT_COLLATION_ID))\n\n // 2 bytes 服务器状态\n data = append(data, byte(c.status), byte(c.status>>8))\n\n // 2 bytes 服务器权能标志(高16位)\n data = append(data, byte(DEFAULT_CAPABILITY>>16), byte(DEFAULT_COLLATION_ID>>24))\n\n // 1 bytes 挑战长度\n data = append(data, 0x15)\n\n // 10 bytes 填充数据\n data = append(data, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\n // n bytes 挑战随机数\n data = append(data, c.salt[8:]...)\n\n // 1 byte 结尾0x00\n data = append(data,0)\n\n return c.pkg.WritePacket(data)\n\n}", "func BenchmarkTLSHandshakeRSAWithClientSessionCache(b *testing.B) {\n\tbc := &benchConfig{\n\t\tIsTLS: true,\n\t\tDisableClientSessionCache: false,\n\t}\n\tbenchmarkExt(b, handshakeHandler, bc)\n}", "func tcpTLSDo(ctx context.Context, config *tcpTLSConfig) {\n\tconst timeout = 15 * time.Second\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\tdefer config.Wg.Done()\n\tout := &tcpResultPair{\n\t\tAddress: config.Address,\n\t\tEndpoint: config.Endpoint,\n\t\tTCP: model.THTCPConnectResult{},\n\t\tTLS: nil, // means: not measured\n\t}\n\tdefer func() {\n\t\tconfig.Out <- out\n\t}()\n\tol := measurexlite.NewOperationLogger(\n\t\tconfig.Logger,\n\t\t\"TCPConnect %s EnableTLS=%v SNI=%s\",\n\t\tconfig.Endpoint,\n\t\tconfig.EnableTLS,\n\t\tconfig.URLHostname,\n\t)\n\tdialer := config.NewDialer(config.Logger)\n\tdefer dialer.CloseIdleConnections()\n\tconn, err := dialer.DialContext(ctx, \"tcp\", config.Endpoint)\n\tout.TCP.Failure = tcpMapFailure(newfailure(err))\n\tout.TCP.Status = err == nil\n\tdefer measurexlite.MaybeClose(conn)\n\tif err != nil || !config.EnableTLS {\n\t\tol.Stop(err)\n\t\treturn\n\t}\n\t// See https://github.com/ooni/probe/issues/2413 to understand\n\t// why we're using a cached cert pool.\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{\"h2\", \"http/1.1\"},\n\t\tRootCAs: certpool,\n\t\tServerName: config.URLHostname,\n\t}\n\tthx := config.NewTSLHandshaker(config.Logger)\n\ttlsConn, _, err := thx.Handshake(ctx, conn, tlsConfig)\n\tol.Stop(err)\n\tout.TLS = &ctrlTLSResult{\n\t\tServerName: config.URLHostname,\n\t\tStatus: err == nil,\n\t\tFailure: newfailure(err),\n\t}\n\tmeasurexlite.MaybeClose(tlsConn)\n}", "func BenchmarkDialTCP(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tDialTCP(TEST_HOST, TEST_USER, TEST_PASSWD, TEST_DBNAME)\n\t}\n}", "func ConnHandshake(c *tls.Conn,) error", "func BenchmarkNewFetchHTTP_Parallel(b *testing.B) {\n\t// This parent benchmark function runs only once as soon as there is another\n\t// sub-benchmark.\n\n\t// Full integration benchmark test which starts a HTTP file server and uses\n\t// TCP to query it on the localhost.\n\tconst backendURL = \"http://127.0.0.1:8283/cart_example.html\"\n\tconst lenCartExampleHTML = 21601\n\n\t// grpc_server_main also reads the file from the disk so stay conistent when\n\t// running benchmarks.\n\tcmd := esitesting.StartProcess(\"go\", \"run\", \"http_server_main.go\")\n\tgo cmd.Wait() // waits forever until killed\n\tdefer cmd.Process.Kill() // kills the go process but not the main startet server\n\tdefer esitesting.KillZombieProcess(\"http_server_main\")\n\n\t// Wait until http server has been started\n\tfor i := 300; ; i = i + 100 {\n\t\td := time.Duration(i) * time.Millisecond\n\t\ttime.Sleep(d)\n\t\t_, err := http.Get(backendURL)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"BenchmarkNewFetchHTTP_Parallel: %s => Sleept %s\\n\", err, d)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tb.Run(\"Insecure\", func(b *testing.B) {\n\n\t\tfh := backend.NewFetchHTTP(backend.DefaultHTTPTransport)\n\t\trfa := &esitag.ResourceArgs{\n\t\t\tExternalReq: getExternalReqWithExtendedHeaders(),\n\t\t\tURL: backendURL,\n\t\t\tTag: esitag.Config{\n\t\t\t\tTimeout: time.Second,\n\t\t\t\tMaxBodySize: 22001,\n\t\t\t},\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tb.ReportAllocs()\n\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\tvar content []byte\n\t\t\tvar hdr http.Header\n\t\t\tvar err error\n\n\t\t\tfor pb.Next() {\n\t\t\t\thdr, content, err = fh.DoRequest(rfa)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"%+v\", err)\n\t\t\t\t}\n\t\t\t\tif hdr != nil {\n\t\t\t\t\tb.Fatal(\"Header should be nil\")\n\t\t\t\t}\n\t\t\t\tif len(content) != lenCartExampleHTML {\n\t\t\t\t\tb.Fatalf(\"Want %d\\nHave %d\", lenCartExampleHTML, len(content))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "func TestHTTPSServer(t *testing.T) {\n\n\tcaCert := path.Join(assetsDir, \"rootCA.crt\")\n\tserverCert := path.Join(assetsDir, \"server.crt\")\n\tserverKey := path.Join(assetsDir, \"server.key\")\n\tclientCert := path.Join(assetsDir, \"client.crt\")\n\tclientKey := path.Join(assetsDir, \"client.key\")\n\tuntrustedClientCert := path.Join(assetsDir, \"other_client.crt\")\n\tuntrustedClientKey := path.Join(assetsDir, \"other_client.key\")\n\n\tauthServer := AuthServer{\n\t\tAddr: \":3457\",\n\t\tSpiffeID: \"spiffe://example.com/service\",\n\t\tCertFile: serverCert,\n\t\tKeyFile: serverKey,\n\t\tCaCert: caCert,\n\t\tCertValidator: validator.SvidValidator{},\n\t}\n\n\t// Run the HTTPS server\n\tgo func() {\n\t\tauthServer.Start()\n\t}()\n\n\t// Create a client with a trusted SpiffeID\n\tclient := createClient(clientCert, clientKey, caCert)\n\n\t// Perform a the authentication request\n\tres, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Response code was %v; want 200\", res.StatusCode)\n\t}\n\n\t// Create a client with an untrusted SpiffeID\n\tclient = createClient(untrustedClientCert, untrustedClientKey, caCert)\n\n\t// Perform a the authentication request\n\tres2, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res2.Body.Close()\n\n\tif res2.StatusCode != 401 {\n\t\tt.Errorf(\"Response code was %v; want 401\", res.StatusCode)\n\t}\n\n\t// Send signal to shutdown the server\n\tshutdown <- 1\n}", "func TestNewClient(t *testing.T) {\n\taPK, aSK := cipher.GenerateKeyPair()\n\tbPK, bSK := cipher.GenerateKeyPair()\n\tsPK, sSK := cipher.GenerateKeyPair()\n\tsAddr := \"127.0.0.1:8081\"\n\n\tconst tpCount = 10\n\tconst msgCount = 100\n\n\tdc := disc.NewMock()\n\n\tl, err := net.Listen(\"tcp\", sAddr)\n\trequire.NoError(t, err)\n\n\tlog.Println(l.Addr().String())\n\n\ts, err := NewServer(sPK, sSK, \"\", l, dc)\n\trequire.NoError(t, err)\n\n\tgo s.Serve() //nolint:errcheck\n\n\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\trequire.NoError(t, a.InitiateServerConnections(context.Background(), 1))\n\n\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\trequire.NoError(t, b.InitiateServerConnections(context.Background(), 1))\n\n\twg := new(sync.WaitGroup)\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < tpCount; i++ {\n\t\t\taDone := make(chan struct{})\n\t\t\tvar aTp *Transport\n\t\t\tgo func() {\n\t\t\t\tvar err error\n\t\t\t\taTp, err = a.Accept(context.Background())\n\t\t\t\tcatch(err)\n\t\t\t\tclose(aDone)\n\t\t\t}()\n\n\t\t\tbTp, err := b.Dial(context.Background(), aPK)\n\t\t\tcatch(err)\n\n\t\t\t<-aDone\n\t\t\tcatch(err)\n\n\t\t\tfor j := 0; j < msgCount; j++ {\n\t\t\t\tpay := []byte(fmt.Sprintf(\"This is message %d!\", j))\n\t\t\t\t_, err := aTp.Write(pay)\n\t\t\t\tcatch(err)\n\t\t\t\t_, err = bTp.Read(pay)\n\t\t\t\tcatch(err)\n\t\t\t}\n\n\t\t\t// Close TPs\n\t\t\tcatch(aTp.Close())\n\t\t\tcatch(bTp.Close())\n\t\t}\n\t}()\n\n\tfor i := 0; i < tpCount; i++ {\n\t\tbDone := make(chan struct{})\n\t\tvar bErr error\n\t\tvar bTp *Transport\n\t\tgo func() {\n\t\t\tbTp, bErr = b.Accept(context.Background())\n\t\t\tclose(bDone)\n\t\t}()\n\n\t\taTp, err := a.Dial(context.Background(), bPK)\n\t\trequire.NoError(t, err)\n\n\t\t<-bDone\n\t\trequire.NoError(t, bErr)\n\n\t\tfor j := 0; j < msgCount; j++ {\n\t\t\tpay := []byte(fmt.Sprintf(\"This is message %d!\", j))\n\n\t\t\tn, err := aTp.Write(pay)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, len(pay), n)\n\n\t\t\tgot := make([]byte, len(pay))\n\t\t\tn, err = bTp.Read(got)\n\t\t\trequire.Equal(t, len(pay), n)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, pay, got)\n\t\t}\n\n\t\t// Close TPs\n\t\trequire.NoError(t, aTp.Close())\n\t\trequire.NoError(t, bTp.Close())\n\t}\n\twg.Wait()\n\n\t// Close server.\n\tassert.NoError(t, s.Close())\n}", "func HTTP2ALPNTLSWrap(conn *net.TCPConn, cfg *tls.Config, tFunc TLSWrapperFunc) (*tls.Conn, error) {\n\tprotoCfg := cfg.Clone()\n\t// TODO: append here\n\tprotoCfg.NextProtos = []string{http2.NextProtoTLS}\n\tprotoCfg.MinVersion = tls.VersionTLS12\n\n\tvar tlsConn *tls.Conn\n\tfor {\n\t\tif err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConn = tFunc(conn, protoCfg)\n\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\t\tif netErr.Timeout() || netErr.Temporary() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := conn.SetDeadline(time.Time{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\t}\n\n\t// Check if we're creating a client conn before checking verification\n\tif isTLSClient(tFunc) {\n\t\tif !protoCfg.InsecureSkipVerify {\n\t\t\tif err := tlsConn.VerifyHostname(protoCfg.ServerName); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tstate := tlsConn.ConnectionState()\n\tif p := state.NegotiatedProtocol; p != http2.NextProtoTLS {\n\t\treturn nil, fmt.Errorf(\"http2: unexpected ALPN protocol %q; want %q\", p, http2.NextProtoTLS)\n\t}\n\n\tif !state.NegotiatedProtocolIsMutual {\n\t\treturn nil, fmt.Errorf(\"http2: could not negotiate protocol mutually\")\n\t}\n\n\treturn tlsConn, nil\n}", "func TestBigData(t *testing.T) {\n\tclient, server := pair(t)\n\n\tserverReads := sinkReads(server)\n\tclientReads := sinkReads(client)\n\n\tconst sz = 15 * 1024 // 15KiB\n\tclientStr := strings.Repeat(\"abcde\", sz/5)\n\tserverStr := strings.Repeat(\"fghij\", sz/5*2)\n\n\tif _, err := io.WriteString(client, clientStr); err != nil {\n\t\tt.Fatalf(\"writing client>server: %v\", err)\n\t}\n\tif _, err := io.WriteString(server, serverStr); err != nil {\n\t\tt.Fatalf(\"writing server>client: %v\", err)\n\t}\n\n\tif serverGot := serverReads.String(sz); serverGot != clientStr {\n\t\tt.Error(\"server didn't receive what client sent\")\n\t}\n\tif clientGot := clientReads.String(2 * sz); clientGot != serverStr {\n\t\tt.Error(\"client didn't receive what server sent\")\n\t}\n\n\tgetNonce := func(n [chp.NonceSize]byte) uint64 {\n\t\tif binary.BigEndian.Uint32(n[:4]) != 0 {\n\t\t\tpanic(\"unexpected nonce\")\n\t\t}\n\t\treturn binary.BigEndian.Uint64(n[4:])\n\t}\n\n\t// Reach into the Conns and verify the cipher nonces advanced as\n\t// expected.\n\tif getNonce(client.tx.nonce) != getNonce(server.rx.nonce) {\n\t\tt.Error(\"desynchronized client tx nonce\")\n\t}\n\tif getNonce(server.tx.nonce) != getNonce(client.rx.nonce) {\n\t\tt.Error(\"desynchronized server tx nonce\")\n\t}\n\tif n := getNonce(client.tx.nonce); n != 4 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 4\", n)\n\t}\n\tif n := getNonce(server.tx.nonce); n != 8 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 8\", n)\n\t}\n}", "func main() {\n\n\tst := time.Now()\n\n\tll.Printf(\"%stag:%s connsess:%s starts\\n\",\n\t\texampid, tag, sngecomm.Lcs)\n\n\t// TLS Configuration.\n\ttc = new(tls.Config)\n\ttc.InsecureSkipVerify = true // Do *not* check the server's certificate\n\n\t// Usually one will use the default cipher suites that go provides.\n\t// However, if a custom cipher squite list is needed/required this\n\t// is how it is accomplished.\n\tif sngecomm.UseCustomCiphers() { // Set custom cipher suite list\n\t\ttc.CipherSuites = append(tc.CipherSuites, sngecomm.CustomCiphers()...)\n\t}\n\n\t// Standard example TLS connect sequence\n\tn, conn, e := sngecomm.CommonTLSConnect(exampid, tag, ll, tc)\n\tif e != nil {\n\t\tll.Fatalf(\"%stag:%s connsess:%s main_on_connect error:%v\",\n\t\t\texampid, tag, sngecomm.Lcs,\n\t\t\te.Error()) // Handle this ......\n\t}\n\n\tnc := n.(*tls.Conn)\n\tsngecomm.DumpTLSConfig(exampid, tc, nc)\n\n\t// *NOTE* application specific functionaltiy starts here!\n\t// For you to add.\n\t// *NOTE* application specific functionaltiy ends here!\n\n\t// Standard example disconnect sequence\n\te = sngecomm.CommonDisconnect(n, conn, exampid, tag, ll)\n\tif e != nil {\n\t\tll.Fatalf(\"%s %s\\n\", exampid, e.Error()) // Handle this ......\n\t}\n\n\tll.Printf(\"%stag:%s connsess:%s main_elapsed:%v\\n\",\n\t\texampid, tag, conn.Session(),\n\t\ttime.Now().Sub(st))\n\n}", "func BenchmarkTCPFindCipherFail(b *testing.B) {\n\tb.StopTimer()\n\tb.ResetTimer()\n\n\tlistener, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 0})\n\tif err != nil {\n\t\tb.Fatalf(\"ListenTCP failed: %v\", err)\n\t}\n\n\tcipherList, err := MakeTestCiphers(ss.MakeTestSecrets(100))\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\ttestPayload := ss.MakeTestPayload(50)\n\tfor n := 0; n < b.N; n++ {\n\t\tgo func() {\n\t\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"Failed to dial %v: %v\", listener.Addr(), err)\n\t\t\t}\n\t\t\tconn.Write(testPayload)\n\t\t\tconn.Close()\n\t\t}()\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"AcceptTCP failed: %v\", err)\n\t\t}\n\t\tclientIP := clientConn.RemoteAddr().(*net.TCPAddr).IP\n\t\tb.StartTimer()\n\t\tfindAccessKey(clientConn, clientIP, cipherList)\n\t\tb.StopTimer()\n\t}\n}", "func sendHandshake(conn *net.TCPConn, infoHash, peerID []byte) error {\n\tdata := make([]byte, 68)\n\tcopy(data[:28], handshakePrefix)\n\tcopy(data[28:48], infoHash)\n\tcopy(data[48:], peerID)\n\n\tconn.SetWriteDeadline(time.Now().Add(time.Second * 10))\n\t_, err := conn.Write(data)\n\treturn err\n}", "func TestServerTLS(t *testing.T) {\n\tca1 := newSelfSignedCA(t)\n\tca2 := newSelfSignedCA(t)\n\n\t// trusted certificates with proxy roles.\n\tclient1 := setupClient(t, ca1, ca1, types.RoleProxy)\n\t_, serverDef1 := setupServer(t, \"s1\", ca1, ca1, types.RoleProxy)\n\terr := client1.updateConnections([]types.Server{serverDef1})\n\trequire.NoError(t, err)\n\tstream, _, err := client1.dial([]string{\"s1\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n\n\t// trusted certificates with incorrect server role.\n\tclient2 := setupClient(t, ca1, ca1, types.RoleNode)\n\t_, serverDef2 := setupServer(t, \"s2\", ca1, ca1, types.RoleProxy)\n\terr = client2.updateConnections([]types.Server{serverDef2})\n\trequire.NoError(t, err) // connection succeeds but is in transient failure state\n\t_, _, err = client2.dial([]string{\"s2\"}, &proto.DialRequest{})\n\trequire.Error(t, err)\n\n\t// certificates with correct role from different CAs\n\tclient3 := setupClient(t, ca1, ca2, types.RoleProxy)\n\t_, serverDef3 := setupServer(t, \"s3\", ca2, ca1, types.RoleProxy)\n\terr = client3.updateConnections([]types.Server{serverDef3})\n\trequire.NoError(t, err)\n\tstream, _, err = client3.dial([]string{\"s3\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n}", "func Benchmark_Ctx_Send(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar str = \"Hello, World!\"\n\tvar byt = []byte(\"Hello, World!\")\n\tvar nmb = 123\n\tvar bol = true\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.Send(str)\n\t\tc.Send(byt)\n\t\tc.Send(nmb)\n\t\tc.Send(bol)\n\t}\n\tutils.AssertEqual(b, \"true\", string(c.Fasthttp.Response.Body()))\n}", "func TestSmoke(t *testing.T) {\n\ta := assert.New(t)\n\tconst backendCount = 4\n\tconst payloadSize = 4096\n\tconst requestCount = 64\n\tconst requestWorkers = 8\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tbackends := make([]*CharGenServer, backendCount)\n\ttier := config.Tier{\n\t\tDialFailureTimeout: 10 * time.Second,\n\t}\n\tfor i := range backends {\n\t\tvar err error\n\t\tbackends[i], err = startChargen(ctx, payloadSize)\n\t\tif !a.NoError(err) {\n\t\t\treturn\n\t\t}\n\t\ttier.Targets = append(tier.Targets, config.Target{\n\t\t\tHosts: []string{backends[i].Addr.IP.String()},\n\t\t\tPort: backends[i].Addr.Port,\n\t\t\tProto: config.TCP,\n\t\t})\n\t}\n\n\tcfg := &config.Config{\n\t\tFrontends: []config.Frontend{\n\t\t\t{\n\t\t\t\tRebalanceDuration: time.Millisecond,\n\t\t\t\tBackendPool: config.BackendPool{\n\t\t\t\t\t// Disable extra pings so our request counts are correct.\n\t\t\t\t\tLatencyBucket: -1,\n\t\t\t\t\tTiers: []config.Tier{tier},\n\t\t\t\t},\n\t\t\t\tBindAddress: \":13013\",\n\t\t\t\tIdleDuration: time.Minute,\n\t\t\t},\n\t\t},\n\t}\n\tif !a.NoError(cfg.Validate()) {\n\t\treturn\n\t}\n\n\tfe := frontend.Frontend{}\n\tif !a.NoError(fe.Ensure(ctx, cfg)) {\n\t\treturn\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(requestWorkers)\n\tvar remainingRequests = int32(requestCount)\n\tfor i := 0; i < requestWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt32(&remainingRequests, -1) < 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\t\t\t\tif !a.NoError(err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcount, err := io.Copy(ioutil.Discard, conn)\n\t\t\t\t_ = conn.Close()\n\t\t\t\ta.NoError(err)\n\t\t\t\ta.Equal(payloadSize, int(count))\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\tfe.Wait()\n\n\t// Ensure that the total number of requests was made.\n\tcount := uint64(0)\n\tfor _, cg := range backends {\n\t\tcount += cg.ConnectionCount()\n\t}\n\ta.Equal(requestCount, int(count))\n\n\tdata, err := yaml.Marshal(&fe)\n\ta.NoError(err)\n\tlog.Print(string(data))\n\n\t// Test tearing down a frontend.\n\tcfg.Frontends = []config.Frontend{}\n\ta.NoError(fe.Ensure(ctx, cfg))\n\t_, err = net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\ta.Errorf(err, \"connection refused\")\n}", "func NewClient(netConn net.Conn, host, path string, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {\n\tchallengeKey, err := generateChallengeKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tacceptKey := computeAcceptKey(challengeKey)\n\n\tc = newConn(netConn, false, readBufSize, writeBufSize)\n\tp := c.writeBuf[:0]\n\tp = append(p, \"GET \"...)\n\tp = append(p, path...)\n\tp = append(p, \" HTTP/1.1\\r\\nHost: \"...)\n\tp = append(p, host...)\n\t// \"Upgrade\" is capitalized for servers that do not use case insensitive\n\t// comparisons on header tokens.\n\tp = append(p, \"\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Version: 13\\r\\nSec-WebSocket-Key: \"...)\n\tp = append(p, challengeKey...)\n\tp = append(p, \"\\r\\n\"...)\n\tfor k, vs := range requestHeader {\n\t\tfor _, v := range vs {\n\t\t\tp = append(p, k...)\n\t\t\tp = append(p, \": \"...)\n\t\t\tp = append(p, v...)\n\t\t\tp = append(p, \"\\r\\n\"...)\n\t\t}\n\t}\n\tp = append(p, \"\\r\\n\"...)\n\n\tif _, err := netConn.Write(p); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := &url.URL{Scheme: \"ws\", Host: host, Path: path}\n\tresp, err := http.ReadResponse(c.br, &http.Request{Method: \"GET\", URL: u})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif resp.StatusCode != 101 ||\n\t\t!strings.EqualFold(resp.Header.Get(\"Upgrade\"), \"websocket\") ||\n\t\t!strings.EqualFold(resp.Header.Get(\"Connection\"), \"upgrade\") ||\n\t\tresp.Header.Get(\"Sec-Websocket-Accept\") != acceptKey {\n\t\treturn nil, resp, ErrBadHandshake\n\t}\n\tc.subprotocol = resp.Header.Get(\"Sec-Websocket-Protocol\")\n\treturn c, resp, nil\n}", "func BenchmarkTCPConnWithoutPool(b *testing.B) {\n\tb.ReportAllocs()\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr = write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\n\t\t\t\terr = write(conn, \"close\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error closing: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func TestClient(t *testing.T) {\n\tt.Parallel()\n\tvar (\n\t\ts = &server{Upgraded: make(chan struct{})}\n\t\tc = NewClient().WithLogger(t.Log)\n\t)\n\n\terr := c.Connect(s, \"ws://example.org/ws\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed connecting to s: %s\", err)\n\t}\n\n\t<-s.Upgraded\n\n\tfor i := 0; i < count; i++ {\n\t\tmsg := fmt.Sprintf(\"hello, world! %d\", i)\n\n\t\terr := c.WriteMessage(websocket.TextMessage, []byte(msg))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tmT, m, err := s.ReadMessage()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif want, got := msg, string(m); want != got {\n\t\t\tt.Errorf(\"server got %s, want %s\", got, want)\n\t\t}\n\t\tif want, got := websocket.TextMessage, mT; want != got {\n\t\t\tt.Errorf(\"message type = %s , want %s\", got, want)\n\t\t}\n\n\t\ts.WriteMessage(websocket.TextMessage, []byte(msg))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tmT, m, err = c.ReadMessage()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif want, got := msg, string(m); want != got {\n\t\t\tt.Errorf(\"client got %s, want %s\", got, want)\n\t\t}\n\t\tif want, got := websocket.TextMessage, mT; want != got {\n\t\t\tt.Errorf(\"message type = %s , want %s\", got, want)\n\t\t}\n\t}\n\n\terr = c.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = s.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (g *altsTC) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)\n\tctx = log.ContextWithPrefix(ctx, \"alts-handshake\")\n\tdefer cancel()\n\n\topts := handshaker.DefaultServerHandshakerOptions()\n\tshs, err := handshaker.NewServerHandshaker(ctx, rawConn, opts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsecureConn, authInfo, err := shs.ServerHandshake(ctx, g.secClient, g.secInfo)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn secureConn, authInfo, nil\n}", "func Server(conn net.Conn, config *Config) *Conn {\n\ttls := new(Conn);\n\ttls.Conn = conn;\n\n\twriteChan := make(chan []byte);\n\treadChan := make(chan []byte);\n\trequestChan := make(chan interface{});\n\n\ttls.writeChan = writeChan;\n\ttls.readChan = readChan;\n\ttls.requestChan = requestChan;\n\n\thandshakeWriterChan := make(chan interface{});\n\tprocessorHandshakeChan := make(chan interface{});\n\thandshakeProcessorChan := make(chan interface{});\n\treaderProcessorChan := make(chan *record);\n\n\tgo new(recordWriter).loop(conn, writeChan, handshakeWriterChan);\n\tgo recordReader(readerProcessorChan, conn);\n\tgo new(recordProcessor).loop(readChan, requestChan, handshakeProcessorChan, readerProcessorChan, processorHandshakeChan);\n\tgo new(serverHandshake).loop(handshakeWriterChan, handshakeProcessorChan, processorHandshakeChan, config);\n\n\treturn tls;\n}", "func handshake(conn net.Conn, modulus *big.Int, m string) {\n // When we dial a peer, send an encrypted (signed) message\n intmessage := crypto.ConvertMessageToInt(m)\n message := (crypto.Encrypt(intmessage, modulus)).String()\n fmt.Fprintf(conn, \"Handshake:\" + message + \"\\n\")\n}", "func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {\n\tconfig := ResetConfig(\"proxy_test_\")\n\n\twalBody, err := WALWithNBlocks(NUM_BLOCKS)\n\trequire.NoError(t, err)\n\twalFile := tempWALWithData(walBody)\n\tconfig.Consensus.SetWalFile(walFile)\n\n\tprivVal := privval.LoadFilePV(config.PrivValidatorFile())\n\n\twal, err := NewWAL(walFile)\n\trequire.NoError(t, err)\n\twal.SetLogger(log.TestingLogger())\n\terr = wal.Start()\n\trequire.NoError(t, err)\n\tdefer wal.Stop()\n\n\tchain, commits, err := makeBlockchainFromWAL(wal)\n\trequire.NoError(t, err)\n\n\tstateDB, state, store := stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)\n\tstore.chain = chain\n\tstore.commits = commits\n\n\t// run the chain through state.ApplyBlock to build up the tendermint state\n\tstate = buildTMStateFromChain(config, stateDB, state, chain, mode)\n\tlatestAppHash := state.AppHash\n\n\t// make a new client creator\n\tkvstoreApp := kvstore.NewPersistentKVStoreApplication(path.Join(config.DBDir(), \"2\"))\n\tclientCreator2 := proxy.NewLocalClientCreator(kvstoreApp)\n\tif nBlocks > 0 {\n\t\t// run nBlocks against a new client to build up the app state.\n\t\t// use a throwaway tendermint state\n\t\tproxyApp := proxy.NewAppConns(clientCreator2)\n\t\tstateDB, state, _ := stateAndStore(config, privVal.GetPubKey(), kvstore.ProtocolVersion)\n\t\tbuildAppStateFromChain(proxyApp, stateDB, state, chain, nBlocks, mode)\n\t}\n\n\t// now start the app using the handshake - it should sync\n\tgenDoc, _ := sm.MakeGenesisDocFromFile(config.GenesisFile())\n\thandshaker := NewHandshaker(stateDB, state, store, genDoc)\n\tproxyApp := proxy.NewAppConns(clientCreator2)\n\tif err := proxyApp.Start(); err != nil {\n\t\tt.Fatalf(\"Error starting proxy app connections: %v\", err)\n\t}\n\tdefer proxyApp.Stop()\n\tif err := handshaker.Handshake(proxyApp); err != nil {\n\t\tt.Fatalf(\"Error on abci handshake: %v\", err)\n\t}\n\n\t// get the latest app hash from the app\n\tres, err := proxyApp.Query().InfoSync(abci.RequestInfo{Version: \"\"})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// the app hash should be synced up\n\tif !bytes.Equal(latestAppHash, res.LastBlockAppHash) {\n\t\tt.Fatalf(\"Expected app hashes to match after handshake/replay. got %X, expected %X\", res.LastBlockAppHash, latestAppHash)\n\t}\n\n\texpectedBlocksToSync := NUM_BLOCKS - nBlocks\n\tif nBlocks == NUM_BLOCKS && mode > 0 {\n\t\texpectedBlocksToSync++\n\t} else if nBlocks > 0 && mode == 1 {\n\t\texpectedBlocksToSync++\n\t}\n\n\tif handshaker.NBlocks() != expectedBlocksToSync {\n\t\tt.Fatalf(\"Expected handshake to sync %d blocks, got %d\", expectedBlocksToSync, handshaker.NBlocks())\n\t}\n}", "func handshakeConnect(u *url.URL, c net.Conn) error {\r\n\th := u.Host\r\n\tif hasPort(h) {\r\n\t\th = h[:strings.LastIndex(h, \":\")]\r\n\t}\r\n\tcfg := &tls.Config{ServerName: h}\r\n\ttlsConn := tls.Client(c, cfg)\r\n\treturn tlsConn.Handshake()\r\n}", "func BenchmarkClientEncoding(b *testing.B) {\n\tvar req pb.GetWithQueryRequest\n\treq.A = 12\n\treq.B = 45360\n\tfor i := 0; i < b.N; i++ {\n\t\thttpreq, _ := http.NewRequest(\"GET\", \"http://localhost/getwithquery\", strings.NewReader(string(\"\")))\n\t\thttpclient.EncodeHTTPGetWithQueryZeroRequest(context.Background(), httpreq, &req)\n\t}\n}", "func main() {\n\ttrn := terrain.New()\n\n\tctx := message.NewClientContext()\n\tctx.Terrain = trn\n\tctx.Clock = clock.NewService()\n\n\thdlr := handler.New(ctx)\n\n\ttlsConfig, err := crypto.GetClientTlsConfig()\n\tif err != nil {\n\t\tlog.Println(\"WARN: could not load TLS config\")\n\t}\n\n\tvar c net.Conn\n\tif tlsConfig != nil {\n\t\tc, err = tls.Dial(\"tcp\", \"127.0.0.1:9999\", tlsConfig)\n\t} else {\n\t\tc, err = net.Dial(\"tcp\", \"127.0.0.1:9999\")\n\t}\n\n\tif err != nil {\n\t\tpanic(\"Dial: \" + err.Error())\n\t}\n\n\treader := bufio.NewReader(c)\n\tclientIO := &message.IO{\n\t\tReader: reader,\n\t\tWriter: c,\n\t}\n\n\tgo hdlr.Listen(clientIO)\n\n\t/*err = builder.SendPing(clientIO.Writer)\n\tif err != nil {\n\t\tpanic(\"SendPing: \" + err.Error())\n\t}*/\n\n\terr = builder.SendLogin(clientIO.Writer, \"root\", \"root\")\n\tif err != nil {\n\t\tpanic(\"SendLogin: \" + err.Error())\n\t}\n\n\tfor {\n\t}\n\n\t/*err = builder.SendChatSend(clientIO.Writer, \"Hello World!\")\n\tif err != nil {\n\t\tpanic(\"SendChatSend: \" + err.Error())\n\t}*/\n\n\t/*err = c.Close()\n\tif err != nil {\n\t\tpanic(\"Close: \" + err.Error())\n\t}*/\n}", "func main() {\n\tkvURL, kvCert := mustArgs()\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create credentials\", zap.Error(err))\n\t}\n\n\tkvs, err := keyvault.NewShim(kvURL, cred)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create keyvault client\", zap.Error(err))\n\t}\n\n\ttlsCert, err := kvs.GetLatestTLSCertificate(context.TODO(), kvCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get tls cert from keyvault\", zap.Error(err))\n\t}\n\n\tclientTLSConfig, err := createClientTLSConfig(tlsCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create client tls config\", zap.Error(err))\n\t}\n\n\tserver := http.Server{\n\t\tAddr: serverAddr,\n\t\tHandler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t_, _ = writer.Write([]byte(\"hello\"))\n\t\t}),\n\t\tTLSConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{tlsCert},\n\t\t\tClientCAs: clientTLSConfig.RootCAs,\n\t\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\t},\n\t}\n\n\tgo func() {\n\t\tif err := server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tlogger.Fatal(\"could not serve tls\", zap.Error(err))\n\t\t}\n\t}()\n\n\t// wait for a short time to allow server to start\n\ttime.Sleep(time.Second)\n\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: clientTLSConfig,\n\t\t},\n\t}\n\n\taddr := fmt.Sprintf(\"https://%s\", serverAddr)\n\tresp, err := client.Get(addr)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get response\", zap.String(\"host\", addr), zap.Error(err))\n\t}\n\n\tprintTLSConnState(resp.TLS)\n\n\tbs, _ := io.ReadAll(resp.Body)\n\tlogger.Info(\"response from tls server\", zap.String(\"body bytes\", string(bs)))\n}", "func Benchmark_Ctx_SendBytes(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar byt = []byte(\"Hello, World!\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.SendBytes(byt)\n\t}\n\tutils.AssertEqual(b, \"Hello, World!\", string(c.Fasthttp.Response.Body()))\n}", "func fastBenchmarkHTTP(ctx *fasthttp.RequestCtx) {\n\t_, err := ctx.Write([]byte(\"Retry !\"))\n\tcommonutils.Check(err, \"fastBenchmarkHTTP\")\n}", "func httpsIncus(ctx context.Context, requestURL string, args *ConnectionArgs) (InstanceServer, error) {\n\t// Use empty args if not specified\n\tif args == nil {\n\t\targs = &ConnectionArgs{}\n\t}\n\n\thttpBaseURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctxConnected, ctxConnectedCancel := context.WithCancel(context.Background())\n\n\t// Initialize the client struct\n\tserver := ProtocolIncus{\n\t\tctx: ctx,\n\t\thttpCertificate: args.TLSServerCert,\n\t\thttpBaseURL: *httpBaseURL,\n\t\thttpProtocol: \"https\",\n\t\thttpUserAgent: args.UserAgent,\n\t\tctxConnected: ctxConnected,\n\t\tctxConnectedCancel: ctxConnectedCancel,\n\t\teventConns: make(map[string]*websocket.Conn),\n\t\teventListeners: make(map[string][]*EventListener),\n\t}\n\n\tif shared.StringInSlice(args.AuthType, []string{\"oidc\"}) {\n\t\tserver.RequireAuthenticated(true)\n\t}\n\n\t// Setup the HTTP client\n\thttpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy, args.TransportWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args.CookieJar != nil {\n\t\thttpClient.Jar = args.CookieJar\n\t}\n\n\tserver.http = httpClient\n\tif args.AuthType == \"oidc\" {\n\t\tserver.setupOIDCClient(args.OIDCTokens)\n\t}\n\n\t// Test the connection and seed the server information\n\tif !args.SkipGetServer {\n\t\t_, _, err := server.GetServer()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &server, nil\n}", "func Test_Ctx_SendBytes(t *testing.T) {\n\tt.Parallel()\n\tapp := New()\n\tctx := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(ctx)\n\tctx.SendBytes([]byte(\"Hello, World!\"))\n\tutils.AssertEqual(t, \"Hello, World!\", string(ctx.Fasthttp.Response.Body()))\n}", "func BenchmarkTCPFindCipherRepeat(b *testing.B) {\n\tb.StopTimer()\n\tb.ResetTimer()\n\n\tconst numCiphers = 100 // Must be <256\n\tcipherList, err := MakeTestCiphers(ss.MakeTestSecrets(numCiphers))\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\tcipherEntries := [numCiphers]*CipherEntry{}\n\tsnapshot := cipherList.SnapshotForClientIP(nil)\n\tfor cipherNumber, element := range snapshot {\n\t\tcipherEntries[cipherNumber] = element.Value.(*CipherEntry)\n\t}\n\tfor n := 0; n < b.N; n++ {\n\t\tcipherNumber := byte(n % numCiphers)\n\t\treader, writer := io.Pipe()\n\t\tclientIP := net.IPv4(192, 0, 2, cipherNumber)\n\t\taddr := &net.TCPAddr{IP: clientIP, Port: 54321}\n\t\tc := conn{clientAddr: addr, reader: reader, writer: writer}\n\t\tcipher := cipherEntries[cipherNumber].Cipher\n\t\tgo ss.NewShadowsocksWriter(writer, cipher).Write(ss.MakeTestPayload(50))\n\t\tb.StartTimer()\n\t\t_, _, _, _, err := findAccessKey(&c, clientIP, cipherList)\n\t\tb.StopTimer()\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t\tc.Close()\n\t}\n}", "func (s *ServerSuite) TestServerHTTPSAutoCert(c *C) {\n\tvar req *http.Request\n\te := testutils.NewHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\treq = r\n\t\tw.Write([]byte(\"hi https\"))\n\t})\n\tdefer e.Close()\n\n\t// Start an ACME Stub server locally that serves certificates for \"example.org\"\n\tman := &autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t}\n\turl, finish := startACMEServerStub(c, man, \"example.org\", \"\")\n\tdefer finish()\n\n\t// Create a Host definition for example.org, with an AutoCert setting that points to local stub URL\n\t// (obtained from the stub start above)\n\tb := MakeBatch(Batch{\n\t\tHost: \"example.org\",\n\t\tAddr: \"localhost:41000\",\n\t\tRoute: `Path(\"/\")`,\n\t\tURL: e.URL,\n\t\tProtocol: engine.HTTPS,\n\t\tAutoCert: &engine.AutoCertSettings{\n\t\t\tDirectoryURL: url,\n\t\t},\n\t})\n\n\tc.Assert(s.mux.UpsertHost(b.H), IsNil)\n\tc.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)\n\tc.Assert(s.mux.UpsertFrontend(b.F), IsNil)\n\tc.Assert(s.mux.UpsertListener(b.L), IsNil)\n\n\tc.Assert(s.mux.Start(), IsNil)\n\n\t// Attempt to connect to the Host over HTTPS which will validate that it was able to generate a cert\n\t// over ACME against our local stub. This is an SNI-based host-name.\n\tc.Assert(GETResponse(c, b.FrontendURL(\"/\"), testutils.Host(\"example.org\")), Equals, \"hi https\")\n\t// Make sure that we see right proto\n\tc.Assert(req.Header.Get(\"X-Forwarded-Proto\"), Equals, \"https\")\n}", "func TestServer_Serve(t *testing.T) {\n\tsPK, sSK := cipher.GenerateKeyPair()\n\tdc := disc.NewMock()\n\n\tl, err := nettest.NewLocalListener(\"tcp\")\n\trequire.NoError(t, err)\n\n\ts, err := NewServer(sPK, sSK, \"\", l, dc)\n\trequire.NoError(t, err)\n\n\tgo s.Serve() //nolint:errcheck\n\n\t// connect two clients, establish transport, check if there are\n\t// two ServerConn's and that both conn's `nextConn` is filled correctly\n\tt.Run(\"test transport establishment\", func(t *testing.T) {\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\t\tbPK, bSK := cipher.GenerateKeyPair()\n\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr := a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\t\terr = b.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\tbTransport, err := b.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\taTransport, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\t// must be 2 ServerConn's\n\t\trequire.Equal(t, 2, s.connCount())\n\n\t\t// must have ServerConn for A\n\t\taServerConn, ok := s.getConn(aPK)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, aPK, aServerConn.PK())\n\n\t\t// must have ServerConn for B\n\t\tbServerConn, ok := s.getConn(bPK)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, bPK, bServerConn.PK())\n\n\t\t// must have a ClientConn\n\t\taClientConn, ok := a.getConn(sPK)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, sPK, aClientConn.RemotePK())\n\n\t\t// must have a ClientConn\n\t\tbClientConn, ok := b.getConn(sPK)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, sPK, bClientConn.RemotePK())\n\n\t\t// check whether nextConn's contents are as must be\n\t\tbClientConn.mx.RLock()\n\t\tnextInitID := bClientConn.nextInitID\n\t\tbClientConn.mx.RUnlock()\n\t\tbNextConn, ok := bServerConn.getNext(nextInitID - 2)\n\t\trequire.Equal(t, true, ok)\n\t\taServerConn.mx.RLock()\n\t\tnextRespID := aServerConn.nextRespID\n\t\taServerConn.mx.RUnlock()\n\t\trequire.Equal(t, bNextConn.id, nextRespID-2)\n\n\t\t// check whether nextConn's contents are as must be\n\t\taServerConn.mx.RLock()\n\t\tnextRespID = aServerConn.nextRespID\n\t\taServerConn.mx.RUnlock()\n\t\taNextConn, ok := aServerConn.getNext(nextRespID - 2)\n\t\trequire.Equal(t, true, ok)\n\t\tbClientConn.mx.RLock()\n\t\tnextInitID = bClientConn.nextInitID\n\t\tbClientConn.mx.RUnlock()\n\t\trequire.Equal(t, aNextConn.id, nextInitID-2)\n\n\t\terr = aTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = bTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = a.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = b.Close()\n\t\trequire.NoError(t, err)\n\n\t\trequire.NoError(t, testWithTimeout(5*time.Second, func() error {\n\t\t\tif s.connCount() != 0 {\n\t\t\t\treturn errors.New(\"s.conns is not empty\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}))\n\n\t\trequire.NoError(t, testWithTimeout(5*time.Second, func() error {\n\t\t\tif a.connCount() != 0 {\n\t\t\t\treturn errors.New(\"a.conns is not empty\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}))\n\n\t\trequire.NoError(t, testWithTimeout(5*time.Second, func() error {\n\t\t\tif b.connCount() != 0 {\n\t\t\t\treturn errors.New(\"b.conns is not empty\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}))\n\t})\n\n\tt.Run(\"test transport establishment concurrently\", func(t *testing.T) {\n\t\t// this way we can control the tests' difficulty\n\t\tinitiatorsCount := 50\n\t\tremotesCount := 50\n\n\t\trand := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\t// store the number of transports each remote should handle\n\t\tremotesTpCount := make(map[int]int)\n\t\t// mapping initiators to remotes. one initiator performs a single connection,\n\t\t// while remotes may handle from 0 to `initiatorsCount` connections\n\t\tpickedRemotes := make([]int, 0, initiatorsCount)\n\t\tfor i := 0; i < initiatorsCount; i++ {\n\t\t\t// pick random remote, which the initiator will connect to\n\t\t\tremote := rand.Intn(remotesCount)\n\t\t\t// increment the number of connections picked remote will handle\n\t\t\tremotesTpCount[remote] = remotesTpCount[remote] + 1\n\t\t\t// map initiator to picked remote\n\t\t\tpickedRemotes = append(pickedRemotes, remote)\n\t\t}\n\n\t\tinitiators := make([]*Client, 0, initiatorsCount)\n\t\tremotes := make([]*Client, 0, remotesCount)\n\n\t\t// create initiators\n\t\tfor i := 0; i < initiatorsCount; i++ {\n\t\t\tpk, sk := cipher.GenerateKeyPair()\n\n\t\t\tc := NewClient(pk, sk, dc, SetLogger(logging.MustGetLogger(fmt.Sprintf(\"initiator_%d\", i))))\n\t\t\terr := c.InitiateServerConnections(context.Background(), 1)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tinitiators = append(initiators, c)\n\t\t}\n\n\t\t// create remotes\n\t\tfor i := 0; i < remotesCount; i++ {\n\t\t\tpk, sk := cipher.GenerateKeyPair()\n\n\t\t\tc := NewClient(pk, sk, dc, SetLogger(logging.MustGetLogger(fmt.Sprintf(\"remote_%d\", i))))\n\t\t\tif _, ok := remotesTpCount[i]; ok {\n\t\t\t\terr := c.InitiateServerConnections(context.Background(), 1)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tremotes = append(remotes, c)\n\t\t}\n\n\t\ttotalRemoteTpsCount := 0\n\t\tfor _, connectionsCount := range remotesTpCount {\n\t\t\ttotalRemoteTpsCount += connectionsCount\n\t\t}\n\n\t\t// channel to listen for `Accept` errors. Any single error must\n\t\t// fail the test\n\t\tacceptErrs := make(chan error, totalRemoteTpsCount)\n\t\tvar remotesTpsMX sync.Mutex\n\t\tremotesTps := make(map[int][]*Transport, len(remotesTpCount))\n\t\tvar remotesWG sync.WaitGroup\n\t\tremotesWG.Add(totalRemoteTpsCount)\n\t\tfor i := range remotes {\n\t\t\t// only run `Accept` in case the remote was picked before\n\t\t\tif _, ok := remotesTpCount[i]; ok {\n\t\t\t\tfor connect := 0; connect < remotesTpCount[i]; connect++ {\n\t\t\t\t\t// run remote\n\t\t\t\t\tgo func(remoteInd int) {\n\t\t\t\t\t\tvar (\n\t\t\t\t\t\t\ttransport *Transport\n\t\t\t\t\t\t\terr error\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\ttransport, err = remotes[remoteInd].Accept(context.Background())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tacceptErrs <- err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// store transport\n\t\t\t\t\t\tremotesTpsMX.Lock()\n\t\t\t\t\t\tremotesTps[remoteInd] = append(remotesTps[remoteInd], transport)\n\t\t\t\t\t\tremotesTpsMX.Unlock()\n\n\t\t\t\t\t\tremotesWG.Done()\n\t\t\t\t\t}(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// channel to listen for `Dial` errors. Any single error must\n\t\t// fail the test\n\t\tdialErrs := make(chan error, initiatorsCount)\n\t\tvar initiatorsTpsMx sync.Mutex\n\t\tinitiatorsTps := make([]*Transport, 0, initiatorsCount)\n\t\tvar initiatorsWG sync.WaitGroup\n\t\tinitiatorsWG.Add(initiatorsCount)\n\t\tfor i := range initiators {\n\t\t\t// run initiator\n\t\t\tgo func(initiatorInd int) {\n\t\t\t\tvar (\n\t\t\t\t\ttransport *Transport\n\t\t\t\t\terr error\n\t\t\t\t)\n\n\t\t\t\tremote := remotes[pickedRemotes[initiatorInd]]\n\t\t\t\ttransport, err = initiators[initiatorInd].Dial(context.Background(), remote.pk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdialErrs <- err\n\t\t\t\t}\n\n\t\t\t\t// store transport\n\t\t\t\tinitiatorsTpsMx.Lock()\n\t\t\t\tinitiatorsTps = append(initiatorsTps, transport)\n\t\t\t\tinitiatorsTpsMx.Unlock()\n\n\t\t\t\tinitiatorsWG.Done()\n\t\t\t}(i)\n\t\t}\n\n\t\t// wait for initiators\n\t\tinitiatorsWG.Wait()\n\t\tclose(dialErrs)\n\t\terr = <-dialErrs\n\t\t// single error should fail test\n\t\trequire.NoError(t, err)\n\n\t\t// wait for remotes\n\t\tremotesWG.Wait()\n\t\tclose(acceptErrs)\n\t\terr = <-acceptErrs\n\t\t// single error should fail test\n\t\trequire.NoError(t, err)\n\n\t\t// check ServerConn's count\n\t\trequire.Equal(t, len(remotesTpCount)+initiatorsCount, s.connCount())\n\n\t\tfor i, initiator := range initiators {\n\t\t\t// get and check initiator's ServerConn\n\t\t\tinitiatorServConn, ok := s.getConn(initiator.pk)\n\t\t\trequire.Equal(t, true, ok)\n\t\t\trequire.Equal(t, initiator.pk, initiatorServConn.PK())\n\n\t\t\t// get and check initiator's ClientConn\n\t\t\tinitiatorClientConn, ok := initiator.getConn(sPK)\n\t\t\trequire.Equal(t, true, ok)\n\t\t\trequire.Equal(t, sPK, initiatorClientConn.RemotePK())\n\n\t\t\tremote := remotes[pickedRemotes[i]]\n\n\t\t\t// get and check remote's ServerConn\n\t\t\tremoteServConn, ok := s.getConn(remote.pk)\n\t\t\trequire.Equal(t, true, ok)\n\t\t\trequire.Equal(t, remote.pk, remoteServConn.PK())\n\n\t\t\t// get and check remote's ClientConn\n\t\t\tremoteClientConn, ok := remote.getConn(sPK)\n\t\t\trequire.Equal(t, true, ok)\n\t\t\trequire.Equal(t, sPK, remoteClientConn.RemotePK())\n\n\t\t\t// get initiator's nextConn\n\t\t\tinitiatorClientConn.mx.RLock()\n\t\t\tnextInitID := initiatorClientConn.nextInitID\n\t\t\tinitiatorClientConn.mx.RUnlock()\n\t\t\tinitiatorNextConn, ok := initiatorServConn.getNext(nextInitID - 2)\n\t\t\trequire.Equal(t, true, ok)\n\t\t\trequire.NotNil(t, initiatorNextConn)\n\t\t}\n\n\t\t// close transports for remotes\n\t\tfor _, tps := range remotesTps {\n\t\t\tfor _, tp := range tps {\n\t\t\t\terr := tp.Close()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t}\n\n\t\t// close transports for initiators\n\t\tfor _, tp := range initiatorsTps {\n\t\t\terr := tp.Close()\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\t// close remotes\n\t\tfor _, remote := range remotes {\n\t\t\terr := remote.Close()\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\t// close initiators\n\t\tfor _, initiator := range initiators {\n\t\t\terr := initiator.Close()\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\trequire.NoError(t, testWithTimeout(10*time.Second, func() error {\n\t\t\tif s.connCount() != 0 {\n\t\t\t\treturn errors.New(\"s.conns is not empty\")\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}))\n\n\t\tfor i, remote := range remotes {\n\t\t\trequire.NoError(t, testWithTimeout(10*time.Second, func() error {\n\t\t\t\tif remote.connCount() != 0 {\n\t\t\t\t\treturn fmt.Errorf(\"remotes[%v].conns is not empty\", i)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\tfor i, initiator := range initiators {\n\t\t\trequire.NoError(t, testWithTimeout(10*time.Second, func() error {\n\t\t\t\tif initiator.connCount() != 0 {\n\t\t\t\t\treturn fmt.Errorf(\"initiators[%v].conns is not empty\", i)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\t})\n\n\tt.Run(\"failed_accepts_should_not_result_in_hang\", func(t *testing.T) {\n\t\t// generate keys for both clients\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\t\tbPK, bSK := cipher.GenerateKeyPair()\n\n\t\t// create remote\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr = a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create initiator\n\t\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\t\terr = b.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\tbTransport, err := b.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\taTransport, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\treadWriteStop := make(chan struct{})\n\t\treadWriteDone := make(chan struct{})\n\n\t\tvar readErr, writeErr error\n\t\tgo func() {\n\t\t\t// read/write to/from transport until the stop signal arrives\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-readWriteStop:\n\t\t\t\t\tclose(readWriteDone)\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\tmsg := []byte(\"Hello there!\")\n\t\t\t\t\tif _, writeErr = bTransport.Write(msg); writeErr != nil {\n\t\t\t\t\t\tclose(readWriteDone)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif _, readErr = aTransport.Read(msg); readErr != nil {\n\t\t\t\t\t\tclose(readWriteDone)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// continue creating transports until the error occurs\n\t\tfor {\n\t\t\tctx := context.Background()\n\t\t\tif _, err = a.Dial(ctx, bPK); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// must be error\n\t\trequire.Error(t, err)\n\n\t\t// the same as above, transport is created by another drdrhdrh\n\t\tfor {\n\t\t\tctx := context.Background()\n\t\t\tif _, err = b.Dial(ctx, aPK); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// must be error\n\t\trequire.Error(t, err)\n\n\t\t// wait more time to ensure that the initially created transport works\n\t\ttime.Sleep(2 * time.Second)\n\n\t\terr = aTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = bTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\t// stop reading/writing goroutines\n\t\tclose(readWriteStop)\n\t\t<-readWriteDone\n\n\t\t// check that the initial transport had been working properly all the time\n\t\t// if any error, it must be `io.EOF` for reader\n\t\tif readErr != io.EOF {\n\t\t\trequire.NoError(t, readErr)\n\t\t}\n\t\t// if any error, it must be `io.ErrClosedPipe` for writer\n\t\tif writeErr != io.ErrClosedPipe {\n\t\t\trequire.NoError(t, writeErr)\n\t\t}\n\n\t\terr = a.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = b.Close()\n\t\trequire.NoError(t, err)\n\t})\n\n\tt.Run(\"test sent/received message consistency\", func(t *testing.T) {\n\t\t// generate keys for both clients\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\t\tbPK, bSK := cipher.GenerateKeyPair()\n\n\t\t// create remote\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr = a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create initiator\n\t\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\t\terr = b.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create transports\n\t\tbTransport, err := b.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\taTransport, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\tmsgCount := 100\n\t\tfor i := 0; i < msgCount; i++ {\n\t\t\tmsg := \"Hello there!\"\n\n\t\t\t// write message of 12 bytes\n\t\t\t_, err := bTransport.Write([]byte(msg))\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// create a receiving buffer of 5 bytes\n\t\t\trecBuff := make([]byte, 5)\n\n\t\t\t// read 5 bytes, 7 left\n\t\t\tn, err := aTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, n, len(recBuff))\n\n\t\t\treceived := string(recBuff[:n])\n\n\t\t\t// read 5 more, 2 left\n\t\t\tn, err = aTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, n, len(recBuff))\n\n\t\t\treceived += string(recBuff[:n])\n\n\t\t\t// read 2 bytes left\n\t\t\tn, err = aTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, n, len(msg)-len(recBuff)*2)\n\n\t\t\treceived += string(recBuff[:n])\n\n\t\t\t// received string must be equal to the sent one\n\t\t\trequire.Equal(t, received, msg)\n\t\t}\n\n\t\terr = bTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = aTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = a.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = b.Close()\n\t\trequire.NoError(t, err)\n\t})\n\n\tt.Run(\"capped_transport_buffer_should_not_result_in_hang\", func(t *testing.T) {\n\t\t// generate keys for both clients\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\t\tbPK, bSK := cipher.GenerateKeyPair()\n\n\t\t// create remote\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr = a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create initiator\n\t\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\t\terr = b.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create transports\n\t\taWrTransport, err := a.Dial(context.Background(), bPK)\n\t\trequire.NoError(t, err)\n\n\t\t_, err = b.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\tmsg := []byte(\"Hello there!\")\n\t\t// exact iterations to fill the receiving buffer and hang `Write`\n\t\titerationsToDo := tpBufCap/len(msg) + 1\n\n\t\t// fill the buffer, but no block yet\n\t\tfor i := 0; i < iterationsToDo-1; i++ {\n\t\t\t_, err = aWrTransport.Write(msg)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\t// block on `Write`\n\t\tvar blockedWriteErr error\n\t\tblockedWriteDone := make(chan struct{})\n\t\tgo func() {\n\t\t\t_, blockedWriteErr = aWrTransport.Write(msg)\n\t\t\tclose(blockedWriteDone)\n\t\t}()\n\n\t\t// wait till it's definitely blocked\n\t\ttime.Sleep(1 * time.Second)\n\n\t\t// create new transport from `B` to `A`\n\t\tbWrTransport, err := b.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\taRdTransport, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\t// try to write/read message via the new transports\n\t\tfor i := 0; i < 100; i++ {\n\t\t\t_, err := bWrTransport.Write(msg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trecBuff := make([]byte, len(msg))\n\t\t\t_, err = aRdTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equal(t, recBuff, msg)\n\t\t}\n\n\t\terr = aWrTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\t<-blockedWriteDone\n\t\trequire.Error(t, blockedWriteErr)\n\n\t\terr = bWrTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = aRdTransport.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = a.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = b.Close()\n\t\trequire.NoError(t, err)\n\t})\n\n\tt.Run(\"self_dial_should_work\", func(t *testing.T) {\n\t\t// generate keys for the drdrhdrh\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\n\t\t// create drdrhdrh\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr = a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// self-dial\n\t\tselfWrTp, err := a.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\t// self-accept\n\t\tselfRdTp, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\t// try to write/read message to/from self\n\t\tmsgCount := 100\n\t\tfor i := 0; i < msgCount; i++ {\n\t\t\tmsg := []byte(\"Hello there!\")\n\n\t\t\t_, err := selfWrTp.Write(msg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trecBuf := make([]byte, 5)\n\n\t\t\t_, err = selfRdTp.Read(recBuf)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = selfRdTp.Read(recBuf)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = selfRdTp.Read(recBuf)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\terr = selfRdTp.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = selfWrTp.Close()\n\t\trequire.NoError(t, err)\n\n\t\terr = a.Close()\n\t\trequire.NoError(t, err)\n\t})\n\n\tt.Run(\"server_disconnect_should_close_transports\", func(t *testing.T) {\n\t\t// generate keys for server\n\t\tsPK, sSK := cipher.GenerateKeyPair()\n\n\t\tdc := disc.NewMock()\n\n\t\tl, err := nettest.NewLocalListener(\"tcp\")\n\t\trequire.NoError(t, err)\n\n\t\t// create a server separately from other tests, since this one should be closed\n\t\ts, err := NewServer(sPK, sSK, \"\", l, dc)\n\t\trequire.NoError(t, err)\n\n\t\tvar sStartErr error\n\t\tsDone := make(chan struct{})\n\t\tgo func() {\n\t\t\tif err := s.Serve(); err != nil {\n\t\t\t\tsStartErr = err\n\t\t\t}\n\n\t\t\tsDone <- struct{}{}\n\t\t}()\n\n\t\t// generate keys for both clients\n\t\taPK, aSK := cipher.GenerateKeyPair()\n\t\tbPK, bSK := cipher.GenerateKeyPair()\n\n\t\t// create remote\n\t\ta := NewClient(aPK, aSK, dc, SetLogger(logging.MustGetLogger(\"A\")))\n\t\terr = a.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\t// create initiator\n\t\tb := NewClient(bPK, bSK, dc, SetLogger(logging.MustGetLogger(\"B\")))\n\t\terr = b.InitiateServerConnections(context.Background(), 1)\n\t\trequire.NoError(t, err)\n\n\t\tbTransport, err := b.Dial(context.Background(), aPK)\n\t\trequire.NoError(t, err)\n\n\t\taTransport, err := a.Accept(context.Background())\n\t\trequire.NoError(t, err)\n\n\t\tmsgCount := 100\n\t\tfor i := 0; i < msgCount; i++ {\n\t\t\tmsg := []byte(\"Hello there!\")\n\n\t\t\t_, err := bTransport.Write(msg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trecBuff := make([]byte, 5)\n\n\t\t\t_, err = aTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = aTransport.Read(recBuff)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = aTransport.Read(msg)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\terr = s.Close()\n\t\trequire.NoError(t, err)\n\n\t\t<-sDone\n\t\t// TODO: remove log, uncomment when bug is fixed\n\t\tlog.Printf(\"SERVE ERR: %v\", sStartErr)\n\t\t//require.NoError(t, sStartErr)\n\n\t\t/*time.Sleep(10 * time.Second)\n\n\t\ttp, ok := bTransport.(*Transport)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, true, tp.IsClosed())\n\n\t\ttp, ok = aTransport.(*Transport)\n\t\trequire.Equal(t, true, ok)\n\t\trequire.Equal(t, true, tp.IsClosed())*/\n\t})\n\n\tt.Run(\"Reconnect to server should succeed\", func(t *testing.T) {\n\t\tt.Run(\"Same address\", func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\ttestReconnect(t, false)\n\t\t})\n\n\t\tt.Run(\"Random address\", func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\ttestReconnect(t, true)\n\t\t})\n\t})\n}", "func getServer(mux *http.ServeMux) (server *http.Server) {\n\tvar certdir string\n\tif config.CertDir != \"\" {\n\t\tcertdir = config.CertDir\n\t} else {\n\t\tcertdir = config.BaseDir\n\t}\n\n\tm := autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tCache: autocert.DirCache(certdir),\n\t\tHostPolicy: autocert.HostWhitelist(config.DomainNames...),\n\t\tEmail: config.Email,\n\t}\n\ttlsConf := &tls.Config{\n\t\tRand: rand.Reader,\n\t\tTime: time.Now,\n\t\tNextProtos: []string{acme.ALPNProto, \"http/1.1\"}, // add http2.NextProtoTLS?\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tGetCertificate: m.GetCertificate,\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t},\n\t}\n\tserver = &http.Server{\n\t\tAddr: config.TLSAddressPort,\n\t\tHandler: mux,\n\t\tTLSConfig: tlsConf,\n\t\t// https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go\n\t\tTLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),\n\t}\n\t// Handle ACME \"http-01\" challenge responses on external port 80.\n\tgo http.ListenAndServe(config.AddressPort, m.HTTPHandler(nil))\n\treturn\n}", "func TestServerShortLivedConn(t *testing.T) {\n\tserver := newTestServer()\n\tdefer server.Stop()\n\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(\"can't listen:\", err)\n\t}\n\tdefer listener.Close()\n\tgo server.ServeListener(listener)\n\n\tvar (\n\t\trequest = `{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"rpc_modules\"}` + \"\\n\"\n\t\twantResp = `{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"nftest\":\"1.0\",\"rpc\":\"1.0\",\"test\":\"1.0\"}}` + \"\\n\"\n\t\tdeadline = time.Now().Add(10 * time.Second)\n\t)\n\tfor i := 0; i < 20; i++ {\n\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(\"can't dial:\", err)\n\t\t}\n\t\tdefer conn.Close()\n\t\tconn.SetDeadline(deadline)\n\t\t// Write the request, then half-close the connection so the server stops reading.\n\t\tconn.Write([]byte(request))\n\t\tconn.(*net.TCPConn).CloseWrite()\n\t\t// Now try to get the response.\n\t\tbuf := make([]byte, 2000)\n\t\tn, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"read error:\", err)\n\t\t}\n\t\tif !bytes.Equal(buf[:n], []byte(wantResp)) {\n\t\t\tt.Fatalf(\"wrong response: %s\", buf[:n])\n\t\t}\n\t}\n}", "func TestDynamicGrpcBackendTLS(t *testing.T) {\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tclientProtocol string\n\t\tmethodOrUrl string\n\t\tmtlsCertFile string\n\t\tuseWrongBackendCert bool\n\t\theader http.Header\n\t\twantResp string\n\t\twantError string\n\t}{\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"http\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantResp: `{\"id\":\"200\",\"theme\":\"Classic\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http2 client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend with mTLS succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ServerCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"HTTP2 client calling gRPCs remote backend through mTLS failed with incorrect client root cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ProxyCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\targs := utils.CommonArgs()\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\ts := env.NewTestEnv(platform.TestDynamicGrpcBackendTLS, platform.GrpcBookstoreRemote)\n\t\t\tdefer s.TearDown(t)\n\t\t\ts.UseWrongBackendCertForDR(tc.useWrongBackendCert)\n\t\t\tif tc.mtlsCertFile != \"\" {\n\t\t\t\ts.SetBackendMTLSCert(tc.mtlsCertFile)\n\t\t\t\targs = append(args, fmt.Sprintf(\"--ssl_backend_client_cert_path=%v\", platform.GetFilePath(platform.TestDataFolder)))\n\t\t\t}\n\n\t\t\tif err := s.Setup(args); err != nil {\n\t\t\t\tt.Fatalf(\"fail to setup test env, %v\", err)\n\t\t\t}\n\t\t\taddr := fmt.Sprintf(\"%v:%v\", platform.GetLoopbackAddress(), s.Ports().ListenerPort)\n\t\t\tresp, err := bsclient.MakeCall(tc.clientProtocol, addr, \"GET\", tc.methodOrUrl, \"\", tc.header)\n\t\t\tif tc.wantError != \"\" && (err == nil || !strings.Contains(err.Error(), tc.wantError)) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %v\", tc.desc, tc.wantError, err)\n\t\t\t}\n\n\t\t\tif tc.wantError == \"\" && err != nil {\n\t\t\t\tt.Errorf(\"Test (%s): got unexpected error: %s\", tc.desc, resp)\n\t\t\t}\n\n\t\t\tif !strings.Contains(resp, tc.wantResp) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %s\", tc.desc, tc.wantResp, resp)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestPerConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tserver1, server2 := startAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// setting bandwidth limit per connection\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 2\n\tserver1.conn.SetReadCPS(reqSpeed1)\n\treqSpeed2 := reqSpeedC / 3\n\tserver2.conn.SetReadCPS(reqSpeed2)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func TestPlaintextDialTLS(t *testing.T) {\n\turi, err := ParseURI(integrationURLFromEnv())\n\tif err != nil {\n\t\tt.Fatalf(\"parse URI error: %s\", err)\n\t}\n\n\t// We can only test when we have a plaintext listener\n\tif uri.Scheme != \"amqp\" {\n\t\tt.Skip(\"requires server listening for plaintext connections\")\n\t}\n\n\tconn, err := DialTLS(uri.String(), &tls.Config{MinVersion: tls.VersionTLS12})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected dial error, got %v\", err)\n\t}\n\tconn.Close()\n}", "func BenchmarkTCPConnWithPool(b *testing.B) {\n\tb.ReportAllocs()\n\tpool := &sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t}\n\t\t\treturn conn\n\t\t},\n\t}\n\tpool.Put(pool.New())\n\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn := pool.Get().(*net.TCPConn)\n\t\t\t\tpool.Put(conn)\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr := write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func mockPostgresSSL(listener net.Listener, errChan chan error, nameChan chan string) {\n\tvar sniHost string\n\n\tconn, err := listener.Accept()\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\terr = conn.SetDeadline(time.Now().Add(time.Second))\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\t// Receive StartupMessage with SSL Request\n\tstartupMessage := make([]byte, 8)\n\tif _, err := io.ReadFull(conn, startupMessage); err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\t// StartupMessage: first four bytes -- total len = 8, last four bytes SslRequestNumber\n\tif !bytes.Equal(startupMessage, []byte{0, 0, 0, 0x8, 0x4, 0xd2, 0x16, 0x2f}) {\n\t\terrChan <- fmt.Errorf(\"unexpected startup message: %#v\", startupMessage)\n\t\treturn\n\t}\n\n\t// Respond with SSLOk\n\t_, err = conn.Write([]byte(\"S\"))\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\t// Set up TLS context to catch clientHello. It will always error out during handshake\n\t// as no certificate is set.\n\tsrv := tls.Server(conn, &tls.Config{\n\t\tGetConfigForClient: func(argHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t\tsniHost = argHello.ServerName\n\t\t\treturn nil, nil\n\t\t},\n\t})\n\tdefer srv.Close()\n\n\t// Do the TLS handshake ignoring errors\n\t_ = srv.Handshake()\n\n\tnameChan <- sniHost\n}", "func TestAllConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tstartAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// changing limits in runtime (applies to all existing connections)\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 3\n\treqSpeed2 := reqSpeedC / 3\n\tl.(*netlisten.Listener).ReadLimiter().SetPerChildCPS(reqSpeed1)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func TestSSLEnforcement(t *testing.T) {\n\ts := StartTestServer(t)\n\tdefer s.Stop()\n\ttestCases := []struct {\n\t\tmethod, key string\n\t\tcertsStatus int // Status code for https with client certs.\n\t\tnoCertsStatus int // Status code for https without client certs.\n\t}{\n\t\t// /ui/: basic file server: no auth.\n\t\t{\"GET\", \"/index.html\", http.StatusOK, http.StatusOK},\n\n\t\t// /_admin/: server.adminServer: no auth.\n\t\t{\"GET\", healthPath, http.StatusOK, http.StatusOK},\n\n\t\t// /debug/: server.adminServer: no auth.\n\t\t{\"GET\", debugEndpoint + \"vars\", http.StatusOK, http.StatusOK},\n\n\t\t// /_status/: server.statusServer: no auth.\n\t\t{\"GET\", statusKeyPrefix, http.StatusOK, http.StatusOK},\n\n\t\t// /kv/db/: kv.DBServer. These are proto reqs, but we can at least get past auth.\n\t\t{\"GET\", kv.DBPrefix + \"Get\", http.StatusBadRequest, http.StatusUnauthorized},\n\n\t\t// /ts/: ts.Server.\n\t\t{\"GET\", ts.URLPrefix, http.StatusNotFound, http.StatusUnauthorized},\n\t}\n\n\t// HTTPS with client certs.\n\tcertsContext := testutils.NewTestBaseContext()\n\tclient, err := certsContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", certsContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"[%d]: error issuing request: %s\", tcNum, err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != tc.certsStatus {\n\t\t\tt.Errorf(\"[%d]: expected status code %d, got %d\", tcNum, tc.certsStatus, resp.StatusCode)\n\t\t}\n\t}\n\n\t// HTTPS without client certs.\n\tnoCertsContext := testutils.NewTestBaseContext()\n\tnoCertsContext.Certs = \"\"\n\tclient, err = noCertsContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", noCertsContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"[%d]: error issuing request: %s\", tcNum, err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != tc.noCertsStatus {\n\t\t\tt.Errorf(\"[%d]: expected status code %d, got %d\", tcNum, tc.noCertsStatus, resp.StatusCode)\n\t\t}\n\t}\n\n\t// Plain http.\n\tinsecureContext := testutils.NewTestBaseContext()\n\tinsecureContext.Insecure = true\n\tclient, err = insecureContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", insecureContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\t// We're talking http to a https server. We don't even make it to a response.\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tt.Errorf(\"[%d]: unexpected success\", tcNum)\n\t\t}\n\t}\n}", "func handleConn(logger serverLogger, conn net.Conn) error {\n\tdefer conn.Close()\n\n\tif tlsConn, ok := conn.(*tls.Conn); ok {\n\t\tif !tlsConn.ConnectionState().HandshakeComplete {\n\t\t\tlogger.logf(\"completing TLS handshake ...\")\n\t\t\terr := tlsConn.Handshake()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tstate := tlsConn.ConnectionState()\n\t\tlogger.logf(\" DidResume: %t\", state.DidResume)\n\t\tlogger.logf(\" CipherSuite: 0x%04x (%s)\", state.CipherSuite, cipherSuiteNames[state.CipherSuite])\n\t\tlogger.logf(\" Version: 0x%04x (%s)\", state.Version, versionNames[state.Version])\n\t\tif len(state.PeerCertificates) > 0 {\n\t\t\tlogger.logf(\" Peer certificates: %d\", len(state.PeerCertificates))\n\t\t\tlogger.logf(\" Peer 1 Issuer: %s\", state.PeerCertificates[0].Issuer.ToRDNSequence())\n\t\t\tlogger.logf(\" Peer 1 Subject: %s\", state.PeerCertificates[0].Subject.ToRDNSequence())\n\t\t\tlogger.logf(\" Peer 1 Serial Number: %s\", hex.EncodeToString(state.PeerCertificates[0].SerialNumber.Bytes()))\n\t\t\tlogger.logf(\" Peer 1 Subject Key ID: %s\", hex.EncodeToString(state.PeerCertificates[0].SubjectKeyId))\n\t\t\tlogger.logf(\" Peer 1 Authority ID: %s\", hex.EncodeToString(state.PeerCertificates[0].AuthorityKeyId))\n\t\t\t// matches the output shown in browsers and openssl -text\n\t\t\tpubKey, err := marshalPublicKey(state.PeerCertificates[0].PublicKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlogger.logf(\" Peer 1 Public Key: %s\", hex.EncodeToString(pubKey))\n\t\t}\n\t}\n\n\tscanner := bufio.NewScanner(conn)\n\tfor scanner.Scan() {\n\t\tlogger.logf(\"read %#v; echoing ...\", scanner.Text())\n\n\t\tlineWithNewLine := append(scanner.Bytes(), '\\n')\n\t\t_, err := conn.Write(lineWithNewLine)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif scanner.Err() != nil {\n\t\treturn scanner.Err()\n\t}\n\n\treturn conn.Close()\n}", "func (m *Mitm) startup() error {\n\tconnstr := fmt.Sprintf(\"%s %s <-> %s %s\", m.Client.RemoteAddr(), m.Client.LocalAddr(), m.Conn.LocalAddr(), m.Conn.RemoteAddr())\n\tDebug(\"--------- BEGIN STARTUP for\", connstr)\n\tbc := [100]byte{}\n\tclient := m.Client\n\tn, _ := client.Read(bc[:])\n\trb := readBuf(bc[:n])\n\trbi := rb.int32()\n\trbi = rb.int32()\n\tif rbi == 80877103 {\n\t\tclient := m.Client\n if *cert != \"\" && *key != \"\" {\n \n _, err := client.Write([]byte{'S'})\n if err != nil {\n Debug(\"ERROR sending we support ssl\")\n }\n Debug(\"Did the client respond to the S?\")\n m.Client, err = doTLS(client, *cert, *key)\n if err != nil {\n Debug(\"ERROR in doTLS\", err)\n }\n readN(m.Client, 100)\n\n } else {\n\t\t Debug(\"The client wants ssl, but we're going to say we don't support it\", rbi)\n _, _ = client.Write([]byte{'N'})\n readN(client, 1024)\n }\n\n\t}\n\t/* The right order is this, but it isn't required\n\t sendAuthPlain(client)\n\t readN(client, 100)\n\t*/\n\tsendAuthOk(m.Client)\n m.sendClientParams()\n\t//sendParameter(client, \"client_encoding\", \"UTF8\")\n\t//sendParameter(client, \"server_version\", *server_version)\n\tsendReady(client)\n\tDebug(\"--------- END STARTUP for\", connstr)\n\tlog.Println(\"client startup complete\")\n return nil\n}", "func TestConnectRepeatHandshake(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\ts1, overlay1, cleanup1 := newService(t, libp2p.Options{NetworkID: 1})\n\tdefer cleanup1()\n\n\ts2, overlay2, cleanup2 := newService(t, libp2p.Options{NetworkID: 1})\n\tdefer cleanup2()\n\n\taddr := serviceUnderlayAddress(t, s1)\n\n\t_, err := s2.Connect(ctx, addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\texpectPeers(t, s2, overlay1)\n\texpectPeersEventually(t, s1, overlay2)\n\n\tinfo, err := libp2ppeer.AddrInfoFromP2pAddr(addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tstream, err := s2.NewStreamForPeerID(info.ID, handshake.ProtocolName, handshake.ProtocolVersion, handshake.StreamName)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := s2.HandshakeService().Handshake(libp2p.NewStream(stream)); err == nil {\n\t\tt.Fatalf(\"expected stream error\")\n\t}\n\n\texpectPeersEventually(t, s2)\n\texpectPeersEventually(t, s1)\n}", "func TestNATSServer_Cluster_TLS(t *testing.T) {\n\tconst CONN_COUNT = 3\n\tconfigs := createNATSServerConfigsWithTLS(CONN_COUNT)\n\tservers := createNATSServers(t, configs)\n\tstartServers(servers)\n\tdefer shutdownServers(servers)\n\tlogNATServerInfo(servers, \"Servers have been started\")\n\tif err := waitforClusterMeshToForm(servers); err != nil {\n\t\tt.Fatalf(\"Full mesh did not form : %v\", err)\n\t}\n\n\tfor i, server := range servers {\n\t\tif server.Cluster() != configs[i].Cluster {\n\t\t\tt.Errorf(\"Cluster name does not match : %s != %s\", server.Cluster(), configs[i].Cluster)\n\t\t}\n\t}\n\n\t// connect to each server\n\t// create a subscription on each server\n\t// create a queue subscription on each server\n\tconst TOPIC = \"TestNewNATSServer\"\n\tconst QUEUE = \"TestNewNATSServer\"\n\tvar subscriptions []messaging.Subscription\n\tvar qsubscriptions []messaging.QueueSubscription\n\tvar conns []*opnats.ManagedConn\n\tfor _, config := range configs {\n\t\tconn, err := nats.Connect(fmt.Sprintf(\"tls://localhost:%d\", config.ServerPort), nats.Secure(clientTLSConfig()))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to connect : %v\", err)\n\t\t}\n\n\t\tmanagedConn := opnats.NewManagedConn(config.Cluster, fmt.Sprintf(\"%s:%d\", config.Cluster, config.ServerPort), conn, nil)\n\t\tconns = append(conns, managedConn)\n\t\tsub, err := managedConn.TopicSubscribe(TOPIC, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tsubscriptions = append(subscriptions, sub)\n\n\t\tqsub, err := managedConn.TopicQueueSubscribe(TOPIC, QUEUE, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create queue subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tqsubscriptions = append(qsubscriptions, qsub)\n\n\t\tlogNATServerInfo(servers, fmt.Sprintf(\"created subscription on %d\", config.ServerPort))\n\t}\n\tlogNATServerInfo(servers, \"Connected to each server and created a subsription on each server\")\n\tif err := checkClientConnectionCounts(servers, 1); err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\twaitForClusterToBecomeAwareOfAllSubscriptions(servers, len(qsubscriptions)+len(qsubscriptions))\n\n\t// publish a message on each connection\n\ti := 0\n\tfor _, conn := range conns {\n\t\ti++\n\t\tconn.Publish(TOPIC, []byte(fmt.Sprintf(\"MSG #%d\", i)))\n\t}\n\tlog.Logger.Info().Msg(\"Published messages\")\n\n\tvar (\n\t\tSUBSCRIBER_EXPECTED_MSG_COUNT = (CONN_COUNT * len(subscriptions))\n\t\tQSUBSCRIBER_EXPECTED_MSG_COUNT = len(conns)\n\t)\n\tsubscriberMsgCount := receiveMessagesOnSubscriptions(subscriptions, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\tqsubscriberMsgCount := receiveMessagesOnQueueSubscriptions(qsubscriptions, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\tif subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", subscriberMsgCount, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n\tif qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", qsubscriberMsgCount, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n}", "func init() {\n\tserverDown = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write([]byte(`hello`))\n\t\t\t},\n\t\t),\n\t)\n\tdefer func() { serverDown.Close() }()\n\n\tserverBadBody = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write([]byte(`<!# SOME BAD--XML_/__.*__\\\\fhji(*&^%^%<Boo<HA/>/>$%^&Y*(J)OPKL:/>`))\n\t\t\t},\n\t\t),\n\t)\n\n\t// init test servers...\n\tserverPNRDetails = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(samplePNRRes)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverPNRDetails.Close() }()\n\n\tserverBizLogic = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(samplePNRResWarnBizLogic)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverBizLogic.Close() }()\n\n\tserverEndTBizLogic = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(sampleEndTBizLogic)\n\t\t\t},\n\t\t),\n\t)\n\n\tserverEndT = httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rs http.ResponseWriter, rq *http.Request) {\n\t\t\t\t_, _ = rs.Write(sampleEndTRS)\n\t\t\t},\n\t\t),\n\t)\n\t//defer func() { serverEndT.Close() }()\n}", "func TestHandshakeCoreData(t *testing.T) {\n\n\t// node 1\n\tport := crypto.GetRandomUserPort()\n\taddress := fmt.Sprintf(\"0.0.0.0:%d\", port)\n\n\tnode1Local, err := NewNodeIdentity(address, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node1\", err)\n\t}\n\n\t// this will be node 2 view of node 1\n\tnode1Remote, _ := NewRemoteNode(node1Local.String(), address)\n\n\t// node 2\n\tport1 := crypto.GetRandomUserPort()\n\taddress1 := fmt.Sprintf(\"0.0.0.0:%d\", port1)\n\n\tnode2Local, err := NewNodeIdentity(address1, nodeconfig.ConfigValues, false)\n\n\tif err != nil {\n\t\tt.Error(\"failed to create local node2\", err)\n\t}\n\n\t// this will be node1 view of node 2\n\tnode2Remote, _ := NewRemoteNode(node2Local.String(), address1)\n\n\t// STEP 1: Node1 generates handshake data and sends it to node2 ....\n\tdata, session, err := generateHandshakeRequestData(node1Local, node2Remote)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session, \"expected session\")\n\tassert.NotNil(t, data, \"expected session\")\n\n\tlog.Info(\"Node 1 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session.ID()), hex.EncodeToString(session.KeyE()))\n\n\tassert.False(t, session.IsAuthenticated(), \"Expected session to be not authenticated yet\")\n\n\t// STEP 2: Node2 gets handshake data from node 1 and processes it to establish a session with a shared AES key\n\n\tresp, session1, err := processHandshakeRequest(node2Local, node1Remote, data)\n\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.NotNil(t, session1, \"expected session\")\n\tassert.NotNil(t, resp, \"expected resp data\")\n\n\tlog.Info(\"Node 2 session data: Id:%s, AES-KEY:%s\", hex.EncodeToString(session1.ID()), hex.EncodeToString(session1.KeyE()))\n\n\tassert.Equal(t, string(session.ID()), string(session1.ID()), \"expected agreed Id\")\n\tassert.Equal(t, string(session.KeyE()), string(session1.KeyE()), \"expected same shared AES enc key\")\n\tassert.Equal(t, string(session.KeyM()), string(session1.KeyM()), \"expected same shared AES mac key\")\n\tassert.Equal(t, string(session.PubKey()), string(session1.PubKey()), \"expected same shared secret\")\n\n\tassert.True(t, session1.IsAuthenticated(), \"expected session1 to be authenticated\")\n\n\t// STEP 3: Node2 sends data1 back to node1.... Node 1 validates the data and sets its network session to authenticated\n\terr = processHandshakeResponse(node1Local, node2Remote, session, resp)\n\n\tassert.True(t, session.IsAuthenticated(), \"expected session to be authenticated\")\n\tassert.NoErr(t, err, \"failed to authenticate or process response\")\n\n\t// test session sym enc / dec\n\n\tconst msg = \"hello spacemesh - hello spacemesh - hello spacemesh :-)\"\n\tcipherText, err := session.Encrypt([]byte(msg))\n\tassert.NoErr(t, err, \"expected no error\")\n\n\tclearText, err := session1.Decrypt(cipherText)\n\tassert.NoErr(t, err, \"expected no error\")\n\tassert.True(t, bytes.Equal(clearText, []byte(msg)), \"Expected enc/dec to work\")\n\n\tnode1Local.Shutdown()\n\tnode2Local.Shutdown()\n}", "func (c *ClientConn) handshake() error {\n\tvar magics handshakeMagics\n\n\tif _, err := c.Write(clientVersion); err != nil {\n\t\treturn err\n\t}\n\tif err := c.Flush(); err != nil {\n\t\treturn err\n\t}\n\tmagics.clientVersion = clientVersion[:len(clientVersion)-2]\n\n\t// read remote server version\n\tversion, err := readVersion(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmagics.serverVersion = version\n\tclientKexInit := kexInitMsg{\n\t\tKexAlgos: supportedKexAlgos,\n\t\tServerHostKeyAlgos: supportedHostKeyAlgos,\n\t\tCiphersClientServer: c.config.Crypto.ciphers(),\n\t\tCiphersServerClient: c.config.Crypto.ciphers(),\n\t\tMACsClientServer: supportedMACs,\n\t\tMACsServerClient: supportedMACs,\n\t\tCompressionClientServer: supportedCompressions,\n\t\tCompressionServerClient: supportedCompressions,\n\t}\n\tkexInitPacket := marshal(msgKexInit, clientKexInit)\n\tmagics.clientKexInit = kexInitPacket\n\n\tif err := c.writePacket(kexInitPacket); err != nil {\n\t\treturn err\n\t}\n\tpacket, err := c.readPacket()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmagics.serverKexInit = packet\n\n\tvar serverKexInit kexInitMsg\n\tif err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {\n\t\treturn err\n\t}\n\n\tkexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)\n\tif !ok {\n\t\treturn errors.New(\"ssh: no common algorithms\")\n\t}\n\n\tif serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {\n\t\t// The server sent a Kex message for the wrong algorithm,\n\t\t// which we have to ignore.\n\t\tif _, err := c.readPacket(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar H, K []byte\n\tvar hashFunc crypto.Hash\n\tswitch kexAlgo {\n\tcase kexAlgoDH14SHA1:\n\t\thashFunc = crypto.SHA1\n\t\tdhGroup14Once.Do(initDHGroup14)\n\t\tH, K, err = c.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)\n\tdefault:\n\t\terr = fmt.Errorf(\"ssh: unexpected key exchange algorithm %v\", kexAlgo)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = c.writePacket([]byte{msgNewKeys}); err != nil {\n\t\treturn err\n\t}\n\tif err = c.transport.writer.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {\n\t\treturn err\n\t}\n\tif packet, err = c.readPacket(); err != nil {\n\t\treturn err\n\t}\n\tif packet[0] != msgNewKeys {\n\t\treturn UnexpectedMessageError{msgNewKeys, packet[0]}\n\t}\n\tif err := c.transport.reader.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {\n\t\treturn err\n\t}\n\treturn c.authenticate(H)\n}", "func TestPreservesTLS(t *testing.T) {\n\tsrv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"ok\"))\n\t})\n\tdefer srv.Close()\n\n\t// forwarder will proxy the request to whatever destination\n\tfwd, err := forward.New()\n\trequire.NoError(t, err)\n\n\tvar cs *tls.ConnectionState\n\t// this is our redirect to server\n\trdr := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tcs = req.TLS\n\t\treq.URL = testutils.ParseURI(srv.URL)\n\t\tfwd.ServeHTTP(w, req)\n\t})\n\n\t// stream handler will forward requests to redirect\n\tst, err := New(rdr)\n\trequire.NoError(t, err)\n\n\tproxy := httptest.NewUnstartedServer(st)\n\tproxy.StartTLS()\n\tdefer proxy.Close()\n\n\tre, _, err := testutils.Get(proxy.URL)\n\trequire.NoError(t, err)\n\tassert.Equal(t, http.StatusOK, re.StatusCode)\n\tassert.NotNil(t, cs)\n}", "func handlePacket(packet gopacket.Packet) {\n\t// Get the TCP layer from this packet\n\tif tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {\n\t\ttcp, _ := tcpLayer.(*layers.TCP)\n\t\tpayload := tcp.BaseLayer.Payload\n\n\t\t/*\n\t\t * We are searching for a TLS record header\n\t\t * (http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session)\n\t\t * First byte: 0x16 for ALLPLICATION_DATA\n\t\t * Two consecutive bytes: 0x0303 for TLS 1.2\n\t\t */\n\n\t\t// Payload must be bigger than 5 bytes (TLS header is 5 bytes)\n\t\tif len(payload) >= 5 {\n\t\t\t// Make sure we have a TLS record here.\n\t\t\tif payload[0] == tlsRecordHandshake {\n\t\t\t\t// See if message type in handshake layer is TLSRecordHandshakeClientHello\n\t\t\t\tTLSRecordHandshakeMessageType := payload[5]\n\n\t\t\t\t/*\n\t\t\t\t * If TLS handshake HELLO is CLIENT_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeClientHello {\n\t\t\t\t\t// TLS version in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11]) // Catch two bytes and interpret as single number (0xXXXX)\n\n\t\t\t\t\ttlsVersionsClients[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Get ciphers\n\t\t\t\t\t */\n\n\t\t\t\t\t// After payload byte 43 there is session ID length and session ID\n\t\t\t\t\t// In most cases session ID length is 0x00, so there is no session ID byte.\n\t\t\t\t\t// Check the length of the session ID and contunie from there\n\t\t\t\t\t// After the session ID length and session ID bytes, the cipher part starts\n\t\t\t\t\t// Anatomy of th CLIENT_HELLO handshake message:\n\t\t\t\t\t// \t<TLS VERSION 2B> | <RANDOM 32B> | <SESS ID LENGTH 1B> | <SESS ID 0..nB> | <CIPHER SUITES LEN 2B> | <CIPHER 1 2B> | CIPHER 2 2B> | ...\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\tCiphersLengthBytes := binary.BigEndian.Uint16(payload[cipherSuitesStart : cipherSuitesStart+2])\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\tvar i uint16\n\t\t\t\t\tfor i = 0; i < CiphersLengthBytes; i += 2 {\n\t\t\t\t\t\tcipherpos := cipherSuitesStart + 2 + byte(i)\n\t\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\t\tciphersClients[cipher]++ // Increment counter for this cipher\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * If TLS Handshake HELLO is SERVER_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeServerHello {\n\t\t\t\t\t// TLS in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11])\n\n\t\t\t\t\ttlsVersionsServers[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\t// (Not needed for server part, because only one cipher is suggested by server)\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\t// (no walking needed, because there is only one cipher suggested)\n\t\t\t\t\tcipherpos := cipherSuitesStart\n\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\tciphersServers[cipher]++ // Increment counter for this cipher\n\n\t\t\t\t}\n\t\t\t} else if payload[0] == tlsRecordAlert {\n\t\t\t\t/*\n\t\t\t\t * If there is an alert message\n\t\t\t\t * Search for any Handshake failures\n\t\t\t\t */\n\t\t\t\ttlsAlertLength := binary.BigEndian.Uint16(payload[3:5])\n\t\t\t\t// Alerts need to have length 2 bytes\n\t\t\t\tif tlsAlertLength == 2 {\n\t\t\t\t\ttlsAlertDescription := payload[6]\n\t\t\t\t\talerts[uint16(tlsAlertDescription)]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *MockConn) serve() {\n\tif tlsConn, ok := c.rwc.(*tls.Conn); ok {\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\treturn\n\t\t}\n\t\ttlsState := tlsConn.ConnectionState()\n\t\tproto := tlsState.NegotiatedProtocol\n\t\tif fn := c.server.Config.TLSNextProto[proto]; fn != nil {\n\t\t\th := c.server.Config.Handler\n\t\t\tfn(c.server.Config, tlsConn, h)\n\t\t}\n\t} else {\n\t\tfn := c.server.Handler\n\t\tfn(c.rwc)\n\t}\n}", "func signBlindlySchnorr (conn net.Conn, suite abstract.Suite, kv crypto.SchnorrKeyset, sharedinfo []byte) {\n \n defer conn.Close()\n\n fmt.Println(\"SERVER\", \"Sending initial parameters\")\n\n signerParams, err := crypto.NewPrivateParams(suite, sharedinfo)\n if err != nil {\n fmt.Println(\"SERVER\", \"Error creating new private parameters\", err.Error())\n return\n }\n\n // \"send\" these to the user.\n userPublicParams := signerParams.DerivePubParams()\n buffer := bytes.Buffer{} \n abstract.Write(&buffer, &userPublicParams, suite)\n conn.Write(buffer.Bytes())\n\n // now we need to wait for the client to send us \"e\"\n ch := make(chan []byte)\n errorCh := make(chan error)\n\n // this neat little routine for wrapping read connections\n // in a class unashamedly stolen from stackoverflow:\n // http://stackoverflow.com/a/9764191\n go func(ch chan []byte, eCh chan error) {\n for {\n // try to read the data\n fmt.Println(\"SERVER\", \"Read goroutine off and going\")\n buffer := make([]byte, 1026)\n _,err := conn.Read(buffer)\n if err != nil {\n // send an error if it's encountered\n errorCh <- err\n return\n }\n // send data if we read some.\n ch <- buffer\n }\n }(ch, errorCh)\n\n for {\n select {\n case data := <-ch:\n fmt.Println(\"SERVER\", \"Received Message\")\n\n var challenge crypto.WISchnorrChallengeMessage\n buffer := bytes.NewBuffer(data)\n err = abstract.Read(buffer, &challenge, suite)\n if err != nil {\n fmt.Println(\"SERVER\", \"Error\", err.Error())\n return\n }\n\n response := crypto.ServerGenerateResponse(suite, challenge, signerParams, kv)\n respbuffer := bytes.Buffer{} \n abstract.Write(&respbuffer, &response, suite)\n conn.Write(respbuffer.Bytes())\n\n fmt.Println(\"SERVER\", \"We're done\")\n return\n\n case err := <- errorCh:\n if err == io.EOF {\n return\n }\n // we should, really, log instead.\n fmt.Println(\"Encountered error serving client\")\n fmt.Println(err.Error())\n break\n } \n }\n\n}", "func newTLSServer(handler http.Handler) *httptest.Server {\n\tts := httptest.NewUnstartedServer(handler)\n\tts.TLS = new(tls.Config)\n\tts.TLS.NextProtos = []string{\"h2\"}\n\tts.StartTLS()\n\treturn ts\n}", "func testNoClientCert(t *testing.T) {\n\tsrv := getServer(rootPort, testdataDir, \"\", 0, t)\n\tsrv = getTLSConfig(srv, \"NoClientCert\", []string{})\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Root server start failed: %s\", err)\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tclientConfig := &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t},\n\t}\n\n\trawURL := fmt.Sprintf(\"https://admin:adminpw@localhost:%d\", rootPort)\n\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to enroll over TLS with no client authentication required: %s\", err)\n\t}\n\n\terr = srv.Stop()\n\tif err != nil {\n\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t}\n}", "func doTLS(address string, port string, tcpDialTimeout time.Duration, tlsHandshakeTimeout time.Duration,\n) (*TLSInfo, error) {\n\tvar tlsInfo TLSInfo\n\n\tcfg := constructTLSConfig()\n\n\t// Create a TCP connection to the target address\n\tdailAddress := address\n\tif port != \"\" {\n\t\tdailAddress += \":\" + port\n\t} else {\n\t\tdailAddress += \":443\"\n\t}\n\tconn, err := net.DialTimeout(\"tcp\", dailAddress, tcpDialTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsClient := tls.Client(conn, cfg)\n\n\t// Taken from http.transport.go:persistConn.addTLS\n\terrChannel := make(chan error, 2)\n\tvar timer *time.Timer // for canceling TLS handshake\n\n\t// Create a timer to allow the tls handshake to timeout if tlsHandshakeTimeout is greater than 0\n\tif tlsHandshakeTimeout != 0 {\n\t\ttimer = time.AfterFunc(tlsHandshakeTimeout, func() {\n\t\t\terrChannel <- tlsHandshakeTimeoutError{}\n\t\t})\n\t}\n\n\t// Use the timer to enforce a timeout if tlsHandshakeTimeout is greater than 0\n\tgo func() {\n\t\terr := tlsClient.Handshake()\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t\terrChannel <- err\n\t}()\n\n\t// A TLS error occurred\n\tif tlsHandshakeErr := <-errChannel; tlsHandshakeErr != nil {\n\t\treturn nil, tlsHandshakeErr\n\t}\n\tdefer func(tlsClient *tls.Conn) {\n\t\terr := tlsClient.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error closing TLS connection for address \" + address + \": \" + err.Error())\n\t\t}\n\t}(tlsClient)\n\tconnState := tlsClient.ConnectionState()\n\n\t// Populate a TLSInfo and return it\n\ttlsInfo = TLSInfo{\n\t\tServerName: cfg.ServerName,\n\t\tAddress: address,\n\t\tVersion: connState.Version,\n\t\tCipherSuite: connState.CipherSuite,\n\t\tNegotiatedProtocol: connState.NegotiatedProtocol,\n\t\tPeerCertificates: connState.PeerCertificates,\n\t\tOCSPResponse: connState.OCSPResponse,\n\t}\n\treturn &tlsInfo, nil\n}", "func handshake_send(cl Client, lp common.Signer, data common.Encoder) error {\n\tlog.Debug(\"Handshaking with \", cl.conn.RemoteAddr().String())\n\n\theader := Message{\n\t\tHeader: ProtoHeader,\n\t}\n\n\terr := header.Write(data)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = cl.WriteMessage(header)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg, err := cl.ReadMessage()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !msg.Ok() {\n\t\treturn errors.New(\"Peer refused header\")\n\t}\n\n\tlog.Debug(\"Header sent, sending cap\")\n\n\tmsgCaps := Message{\n\t\tHeader: ProtoCap,\n\t}\n\n\tmsgCaps.Write(lp.(ProtocolHandler).GetCapabilities())\n\n\terr = cl.WriteMessage(msgCaps)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg, err = cl.ReadMessage()\n\tlog.Debug(\"Cookie\")\n\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\n\tlog.Info(\"Cookie recieved, signing\")\n\n\t// the peer expects us to sign the *decompressed* cookie. So do that.\n\tvar cookie [20]byte\n\tmsg.Read(&cookie)\n\tsig := lp.Sign(cookie[:])\n\n\tmsg = &Message{\n\t\tHeader: ProtoSig,\n\t}\n\n\terr = msg.Write(sig)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = cl.WriteMessage(msg)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg, err = cl.ReadMessage()\n\tlog.Debug(\"Written cookie\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !msg.Ok() {\n\t\treturn errors.New(\"Peer refused signature\")\n\t}\n\n\tlog.Info(\"Handshake sent ok\")\n\n\treturn nil\n}", "func speedtest1_run(tls *libc.TLS) { /* speedtest1.c:532:6: */\n\tbp := tls.Alloc(8)\n\tdefer tls.Free(8)\n\n\tvar i int32\n\tvar n int32\n\tvar len int32\n\tif g.bSqlOnly != 0 {\n\t\treturn\n\t}\n\n\tg.nResult = 0\n\tfor sqlite3.Xsqlite3_step(tls, g.pStmt) == 100 {\n\t\tn = sqlite3.Xsqlite3_column_count(tls, g.pStmt)\n\t\tfor i = 0; i < n; i++ {\n\t\t\tvar z uintptr = sqlite3.Xsqlite3_column_text(tls, g.pStmt, i)\n\t\t\tif z == uintptr(0) {\n\t\t\t\tz = ts + 2732 /* \"nil\" */\n\t\t\t}\n\t\t\tlen = int32(libc.Xstrlen(tls, z))\n\t\t\tif g.bVerify != 0 {\n\t\t\t\tvar eType int32 = sqlite3.Xsqlite3_column_type(tls, g.pStmt, i)\n\t\t\t\t// var zPrefix [2]uint8 at bp, 2\n\n\t\t\t\t*(*uint8)(unsafe.Pointer(bp /* &zPrefix[0] */ + uintptr(0))) = uint8('\\n')\n\t\t\t\t*(*uint8)(unsafe.Pointer(bp /* &zPrefix[0] */ + uintptr(1))) = uint8(*(*int8)(unsafe.Pointer(ts + 2736 /* \"-IFTBN\" */ + uintptr(eType))))\n\t\t\t\tif g.nResByte != 0 {\n\t\t\t\t\tHashUpdate(tls, bp /* &zPrefix[0] */, uint32(2))\n\t\t\t\t} else {\n\t\t\t\t\tHashUpdate(tls, (bp /* &zPrefix[0] */ + uintptr(1)), uint32(1))\n\t\t\t\t}\n\t\t\t\tif eType == 2 {\n\t\t\t\t\t// Omit the value of floating-point results from the verification\n\t\t\t\t\t// hash. The only thing we record is the fact that the result was\n\t\t\t\t\t// a floating-point value.\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (uint64(2))\n\t\t\t\t} else if eType == 4 {\n\t\t\t\t\tvar nBlob int32 = sqlite3.Xsqlite3_column_bytes(tls, g.pStmt, i)\n\t\t\t\t\tvar iBlob int32\n\t\t\t\t\t// var zChar [2]uint8 at bp+2, 2\n\n\t\t\t\t\tvar aBlob uintptr = sqlite3.Xsqlite3_column_blob(tls, g.pStmt, i)\n\t\t\t\t\tfor iBlob = 0; iBlob < nBlob; iBlob++ {\n\t\t\t\t\t\t*(*uint8)(unsafe.Pointer(bp + 2 /* &zChar[0] */ + uintptr(0))) = uint8(*(*int8)(unsafe.Pointer(ts + 2743 /* \"0123456789abcdef\" */ + uintptr((int32(*(*uint8)(unsafe.Pointer(aBlob + uintptr(iBlob)))) >> 4)))))\n\t\t\t\t\t\t*(*uint8)(unsafe.Pointer(bp + 2 /* &zChar[0] */ + uintptr(1))) = uint8(*(*int8)(unsafe.Pointer(ts + 2743 /* \"0123456789abcdef\" */ + uintptr((int32(*(*uint8)(unsafe.Pointer(aBlob + uintptr(iBlob)))) & 15)))))\n\t\t\t\t\t\tHashUpdate(tls, bp+2 /* &zChar[0] */, uint32(2))\n\t\t\t\t\t}\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (u64((nBlob * 2) + 2))\n\t\t\t\t} else {\n\t\t\t\t\tHashUpdate(tls, z, uint32(len))\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (u64(len + 2))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (uint32(g.nResult + len)) < (uint32(unsafe.Sizeof([3000]int8{})) - uint32(2)) {\n\t\t\t\tif g.nResult > 0 {\n\t\t\t\t\t*(*int8)(unsafe.Pointer((uintptr(unsafe.Pointer(&g)) + 100 /* &.zResult */) + uintptr(libc.PostIncInt32(&g.nResult, 1)))) = int8(' ')\n\t\t\t\t}\n\t\t\t\tlibc.Xmemcpy(tls, ((uintptr(unsafe.Pointer(&g)) + 100 /* &.zResult */) + uintptr(g.nResult)), z, (uint32(len + 1)))\n\t\t\t\t*(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 96 /* &.nResult */)) += (len)\n\t\t\t}\n\t\t}\n\t}\n\tif g.bReprepare != 0 {\n\t\t// var pNew uintptr at bp+4, 4\n\n\t\tsqlite3.Xsqlite3_prepare_v2(tls, g.db, sqlite3.Xsqlite3_sql(tls, g.pStmt), -1, bp+4 /* &pNew */, uintptr(0))\n\t\tsqlite3.Xsqlite3_finalize(tls, g.pStmt)\n\t\tg.pStmt = *(*uintptr)(unsafe.Pointer(bp + 4 /* pNew */))\n\t} else {\n\t\tsqlite3.Xsqlite3_reset(tls, g.pStmt)\n\t}\n\tspeedtest1_shrink_memory(tls)\n}", "func TestClientServer(t *testing.T) {\n\t// Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t// Create the certs and configs.\n\tCreateCA(root)\n\n\tCreateSignedCert(root, CA, \"01\", \"servers\", \"Servers CA\")\n\tCreateSignedCert(root, \"servers\", \"01\", \"server-instance\", \"server.example.com\")\n\n\tCreateSignedCert(root, CA, \"02\", \"clients\", \"Clients CA\")\n\tCreateSignedCert(root, \"clients\", \"01\", \"client-instance\", \"Client Instance\")\n\tserverConfig, err := vttls.ServerConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"clients-cert.pem\"))\n\tif err != nil {\n\t\tt.Fatalf(\"TLSServerConfig failed: %v\", err)\n\t}\n\tclientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"client-instance-cert.pem\"),\n\t\tpath.Join(root, \"client-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\t// Create a TLS server listener.\n\tlistener, err := tls.Listen(\"tcp\", \":0\", serverConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"Listen failed: %v\", err)\n\t}\n\taddr := listener.Addr().String()\n\tdefer listener.Close()\n\n\twg := sync.WaitGroup{}\n\n\t//\n\t// Positive case: accept on server side, connect a client, send data.\n\t//\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tclientConn, err := tls.Dial(\"tcp\", addr, clientConfig)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Dial failed: %v\", err)\n\t\t}\n\n\t\tclientConn.Write([]byte{42})\n\t\tclientConn.Close()\n\t}()\n\n\tserverConn, err := listener.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"Accept failed: %v\", err)\n\t}\n\n\tresult := make([]byte, 1)\n\tif n, err := serverConn.Read(result); (err != nil && err != io.EOF) || n != 1 {\n\t\tt.Fatalf(\"Read failed: %v %v\", n, err)\n\t}\n\tif result[0] != 42 {\n\t\tt.Fatalf(\"Read returned wrong result: %v\", result)\n\t}\n\tserverConn.Close()\n\n\twg.Wait()\n\n\t//\n\t// Negative case: connect a client with wrong cert (using the\n\t// server cert on the client side).\n\t//\n\n\tbadClientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\t// We expect the Accept to work, but the first read to fail.\n\t\tdefer wg.Done()\n\t\tserverConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Connection failed: %v\", err)\n\t\t}\n\n\t\t// This will fail.\n\t\tresult := make([]byte, 1)\n\t\tif n, err := serverConn.Read(result); err == nil {\n\t\t\tfmt.Printf(\"Was able to read from server: %v\\n\", n)\n\t\t}\n\t\tserverConn.Close()\n\t}()\n\n\t// When using TLS 1.2, the Dial will fail.\n\t// With TLS 1.3, the Dial will succeed and the first Read will fail.\n\tclientConn, err := tls.Dial(\"tcp\", addr, badClientConfig)\n\tif err != nil {\n\t\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t\t}\n\t\treturn\n\t}\n\tdata := make([]byte, 1)\n\t_, err = clientConn.Read(data)\n\tif err == nil {\n\t\tt.Fatalf(\"Dial or first Read was expected to fail\")\n\t}\n\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t}\n}", "func (ch *clientSecureChannel) Open(ctx context.Context) error {\n\tch.Lock()\n\tdefer ch.Unlock()\n\n\tremoteURL, err := url.Parse(ch.endpointURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(ch.remoteCertificate) > 0 {\n\t\tcert, err := x509.ParseCertificate(ch.remoteCertificate)\n\t\tif err != nil {\n\t\t\treturn ua.BadSecurityChecksFailed\n\t\t}\n\t\t_, err = validateServerCertificate(cert, remoteURL.Hostname(), ch.trustedCertsFile, ch.suppressHostNameInvalid, ch.suppressCertificateExpired, ch.suppressCertificateChainIncomplete)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tch.conn, err = net.DialTimeout(\"tcp\", remoteURL.Host, time.Duration(ch.connectTimeout)*time.Millisecond)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := *(bytesPool.Get().(*[]byte))\n\tdefer bytesPool.Put(&buf)\n\tvar writer = ua.NewWriter(buf)\n\tvar enc = ua.NewBinaryEncoder(writer, ch)\n\tenc.WriteUInt32(ua.MessageTypeHello)\n\tenc.WriteUInt32(uint32(32 + len(ch.endpointURL)))\n\tenc.WriteUInt32(protocolVersion)\n\tenc.WriteUInt32(defaultBufferSize)\n\tenc.WriteUInt32(defaultBufferSize)\n\tenc.WriteUInt32(defaultMaxMessageSize)\n\tenc.WriteUInt32(defaultMaxChunkCount)\n\tenc.WriteString(ch.endpointURL)\n\t_, err = ch.Write(writer.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if ch.trace {\n\t// \tlog.Printf(\"Hello{\\\"Version\\\":%d,\\\"ReceiveBufferSize\\\":%d,\\\"SendBufferSize\\\":%d,\\\"MaxMessageSize\\\":%d,\\\"MaxChunkCount\\\":%d,\\\"EndpointURL\\\":\\\"%s\\\"}\\n\", protocolVersion, defaultBufferSize, defaultBufferSize, defaultMaxMessageSize, defaultMaxChunkCount, ch.endpointURL)\n\t// }\n\n\t_, err = ch.Read(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar reader = bytes.NewReader(buf)\n\tvar dec = ua.NewBinaryDecoder(reader, ch)\n\tvar msgType uint32\n\tif err := dec.ReadUInt32(&msgType); err != nil {\n\t\treturn err\n\t}\n\tvar msgLen uint32\n\tif err := dec.ReadUInt32(&msgLen); err != nil {\n\t\treturn err\n\t}\n\n\tswitch msgType {\n\tcase ua.MessageTypeAck:\n\t\tif msgLen < 28 {\n\t\t\treturn ua.BadDecodingError\n\t\t}\n\t\tvar remoteProtocolVersion uint32\n\t\tif err := dec.ReadUInt32(&remoteProtocolVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif remoteProtocolVersion < protocolVersion {\n\t\t\treturn ua.BadProtocolVersionUnsupported\n\t\t}\n\t\tif err := dec.ReadUInt32(&ch.sendBufferSize); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dec.ReadUInt32(&ch.receiveBufferSize); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dec.ReadUInt32(&ch.maxMessageSize); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dec.ReadUInt32(&ch.maxChunkCount); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// if ch.trace {\n\t\t// \tlog.Printf(\"Ack{\\\"Version\\\":%d,\\\"ReceiveBufferSize\\\":%d,\\\"SendBufferSize\\\":%d,\\\"MaxMessageSize\\\":%d,\\\"MaxChunkCount\\\":%d}\\n\", remoteProtocolVersion, ch.sendBufferSize, ch.receiveBufferSize, ch.maxMessageSize, ch.maxChunkCount)\n\t\t// }\n\n\tcase ua.MessageTypeError:\n\t\tif msgLen < 16 {\n\t\t\treturn ua.BadDecodingError\n\t\t}\n\t\tvar remoteCode uint32\n\t\tif err := dec.ReadUInt32(&remoteCode); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar unused string\n\t\tif err = dec.ReadString(&unused); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn ua.StatusCode(remoteCode)\n\n\tdefault:\n\t\treturn ua.BadDecodingError\n\t}\n\n\t// setSecurityPolicy\n\tswitch ch.securityPolicyURI {\n\tcase ua.SecurityPolicyURINone:\n\t\tch.securityPolicy = new(ua.SecurityPolicyNone)\n\n\tcase ua.SecurityPolicyURIBasic128Rsa15:\n\t\tch.securityPolicy = new(ua.SecurityPolicyBasic128Rsa15)\n\n\tcase ua.SecurityPolicyURIBasic256:\n\t\tch.securityPolicy = new(ua.SecurityPolicyBasic256)\n\n\tcase ua.SecurityPolicyURIBasic256Sha256:\n\t\tch.securityPolicy = new(ua.SecurityPolicyBasic256Sha256)\n\n\tcase ua.SecurityPolicyURIAes128Sha256RsaOaep:\n\t\tch.securityPolicy = new(ua.SecurityPolicyAes128Sha256RsaOaep)\n\n\tcase ua.SecurityPolicyURIAes256Sha256RsaPss:\n\t\tch.securityPolicy = new(ua.SecurityPolicyAes256Sha256RsaPss)\n\n\tdefault:\n\t\treturn ua.BadSecurityPolicyRejected\n\t}\n\n\tch.localSigningKey = make([]byte, ch.securityPolicy.SymSignatureKeySize())\n\tch.localEncryptingKey = make([]byte, ch.securityPolicy.SymEncryptionKeySize())\n\tch.localInitializationVector = make([]byte, ch.securityPolicy.SymEncryptionBlockSize())\n\tch.remoteSigningKey = make([]byte, ch.securityPolicy.SymSignatureKeySize())\n\tch.remoteEncryptingKey = make([]byte, ch.securityPolicy.SymEncryptionKeySize())\n\tch.remoteInitializationVector = make([]byte, ch.securityPolicy.SymEncryptionBlockSize())\n\n\tswitch ch.securityMode {\n\tcase ua.MessageSecurityModeSignAndEncrypt, ua.MessageSecurityModeSign:\n\t\tif ch.localPrivateKey == nil {\n\t\t\treturn ua.BadSecurityChecksFailed\n\t\t}\n\t\tch.localPrivateKeySize = ch.localPrivateKey.Size()\n\t\tif ch.remotePublicKey == nil {\n\t\t\treturn ua.BadSecurityChecksFailed\n\t\t}\n\t\tch.remotePublicKeySize = ch.remotePublicKey.Size()\n\t}\n\n\tch.pendingResponseCh = make(chan *ua.ServiceOperation, 32)\n\tch.pendingResponses = make(map[uint32]*ua.ServiceOperation)\n\tch.cancellation = make(chan struct{})\n\tch.channelID = 0\n\tch.tokenID = 0\n\tch.sendingTokenID = 0\n\tch.receivingTokenID = 0\n\n\tgo ch.responseWorker()\n\n\trequest := &ua.OpenSecureChannelRequest{\n\t\tClientProtocolVersion: protocolVersion,\n\t\tRequestType: ua.SecurityTokenRequestTypeIssue,\n\t\tSecurityMode: ch.securityMode,\n\t\tClientNonce: ua.ByteString(getNextNonce(ch.securityPolicy.NonceSize())),\n\t\tRequestedLifetime: ch.tokenRequestedLifetime,\n\t}\n\tres, err := ch.Request(ctx, request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := res.(*ua.OpenSecureChannelResponse)\n\tif response.ServerProtocolVersion < protocolVersion {\n\t\treturn ua.BadProtocolVersionUnsupported\n\t}\n\n\tch.tokenLock.Lock()\n\tch.tokenRenewalTime = time.Now().Add(time.Duration(response.SecurityToken.RevisedLifetime*75/100) * time.Millisecond)\n\tch.channelID = response.SecurityToken.ChannelID\n\tch.tokenID = response.SecurityToken.TokenID\n\tch.localNonce = []byte(request.ClientNonce)\n\tch.remoteNonce = []byte(response.ServerNonce)\n\tch.tokenLock.Unlock()\n\treturn nil\n}", "func (tc *testConn) uncheckedHandshake() {\n\ttc.t.Helper()\n\tdefer func(saved map[byte]bool) {\n\t\ttc.ignoreFrames = saved\n\t}(tc.ignoreFrames)\n\ttc.ignoreFrames = map[byte]bool{\n\t\tframeTypeAck: true,\n\t\tframeTypeCrypto: true,\n\t\tframeTypeNewConnectionID: true,\n\t}\n\tif tc.conn.side == serverSide {\n\t\ttc.writeFrames(packetTypeInitial,\n\t\t\tdebugFrameCrypto{\n\t\t\t\tdata: tc.cryptoDataIn[tls.QUICEncryptionLevelInitial],\n\t\t\t})\n\t\ttc.writeFrames(packetTypeHandshake,\n\t\t\tdebugFrameCrypto{\n\t\t\t\tdata: tc.cryptoDataIn[tls.QUICEncryptionLevelHandshake],\n\t\t\t})\n\t\ttc.wantFrame(\"send HANDSHAKE_DONE after handshake completes\",\n\t\t\tpacketType1RTT, debugFrameHandshakeDone{})\n\t\ttc.writeFrames(packetType1RTT,\n\t\t\tdebugFrameAck{\n\t\t\t\tackDelay: unscaledAckDelayFromDuration(\n\t\t\t\t\tmaxAckDelay, ackDelayExponent),\n\t\t\t\tranges: []i64range[packetNumber]{{0, tc.lastPacket.num + 1}},\n\t\t\t})\n\t} else {\n\t\ttc.wantIdle(\"initial frames are ignored\")\n\t\ttc.writeFrames(packetTypeInitial,\n\t\t\tdebugFrameCrypto{\n\t\t\t\tdata: tc.cryptoDataIn[tls.QUICEncryptionLevelInitial],\n\t\t\t})\n\t\ttc.writeFrames(packetTypeHandshake,\n\t\t\tdebugFrameCrypto{\n\t\t\t\tdata: tc.cryptoDataIn[tls.QUICEncryptionLevelHandshake],\n\t\t\t})\n\t\ttc.wantIdle(\"don't expect any frames we aren't ignoring\")\n\t\t// Send the next two frames in separate packets, so the client sends an\n\t\t// ack immediately without delay. We want to consume that ack here, rather\n\t\t// than returning with a delayed ack waiting to be sent.\n\t\ttc.ignoreFrames = nil\n\t\ttc.writeFrames(packetType1RTT,\n\t\t\tdebugFrameHandshakeDone{})\n\t\ttc.writeFrames(packetType1RTT,\n\t\t\tdebugFrameCrypto{\n\t\t\t\tdata: tc.cryptoDataIn[tls.QUICEncryptionLevelApplication],\n\t\t\t})\n\t\ttc.wantFrame(\"client ACKs server's first 1-RTT packet\",\n\t\t\tpacketType1RTT, debugFrameAck{\n\t\t\t\tranges: []i64range[packetNumber]{{0, 2}},\n\t\t\t})\n\n\t}\n\ttc.wantIdle(\"handshake is done\")\n}", "func NewClient(ssl bool) {\n\taddr := os.Args[len(os.Args)-1]\n\tlog.Println(\"Connecting to\", addr)\n\tvar (\n\t\tc diam.Conn\n\t\terr error\n\t)\n\t// Handle ACA incoming messages.\n\tvar counter int\n\tmux := diam.NewServeMux()\n\tmux.HandleFunc(\"ACA\", func(c diam.Conn, m *diam.Message) {\n\t\tcounter++\n\t\tif counter == benchMessages {\n\t\t\tc.Close()\n\t\t}\n\t})\n\t// Connect using the our custom mux and default dictionary.\n\tif ssl {\n\t\tc, err = diam.DialTLS(addr, \"\", \"\", mux, nil)\n\t} else {\n\t\tc, err = diam.Dial(addr, mux, nil)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Build CER\n\tm := diam.NewRequest(diam.CapabilitiesExchange, 0, nil)\n\tm.NewAVP(avp.OriginHost, avp.Mbit, 0, identity)\n\tm.NewAVP(avp.OriginRealm, avp.Mbit, 0, realm)\n\tladdr := c.LocalAddr()\n\tip, _, _ := net.SplitHostPort(laddr.String())\n\tm.NewAVP(avp.HostIPAddress, avp.Mbit, 0, datatype.Address(net.ParseIP(ip)))\n\tm.NewAVP(avp.VendorID, avp.Mbit, 0, vendorID)\n\tm.NewAVP(avp.ProductName, 0, 0, productName)\n\tm.NewAVP(avp.OriginStateID, avp.Mbit, 0, datatype.Unsigned32(rand.Uint32()))\n\t// Send message to the connection\n\tif _, err := m.WriteTo(c); err != nil {\n\t\tlog.Println(\"Write failed:\", err)\n\t\treturn\n\t}\n\t// Prepare the ACR that is used for benchmarking.\n\tm = diam.NewRequest(diam.Accounting, 0, nil)\n\tm.NewAVP(avp.SessionID, avp.Mbit, 0, datatype.UTF8String(\"Hello\"))\n\tm.NewAVP(avp.OriginHost, avp.Mbit, 0, identity)\n\tm.NewAVP(avp.OriginRealm, avp.Mbit, 0, realm)\n\tm.NewAVP(avp.HostIPAddress, avp.Mbit, 0, datatype.Address(net.ParseIP(ip)))\n\tm.NewAVP(avp.VendorID, avp.Mbit, 0, vendorID)\n\tm.NewAVP(avp.ProductName, 0, 0, productName)\n\tm.NewAVP(avp.OriginStateID, avp.Mbit, 0, datatype.Unsigned32(rand.Uint32()))\n\tlog.Println(\"OK, sending messages\")\n\tvar n int\n\tgo func() {\n\t\tstart := time.Now()\n\t\t// Wait until the connection is closed.\n\t\t<-c.(diam.CloseNotifier).CloseNotify()\n\t\tn *= 2 // request+answer\n\t\telapsed := time.Since(start)\n\t\tmps := int(float64(n) / elapsed.Seconds())\n\t\tlog.Printf(\"%d messages (request+answer) in %s seconds, %d msg/s\",\n\t\t\tn, elapsed, mps)\n\t\tatomic.AddInt32(&totalMessages, int32(n))\n\t\twg.Done()\n\t}()\n\tfor ; n < benchMessages; n++ {\n\t\t// Send message to the connection\n\t\tif _, err := m.WriteTo(c); err != nil {\n\t\t\tlog.Fatal(\"Write failed:\", err)\n\t\t}\n\t}\n}", "func (ts *TcpServer) StartTlsServer(port string) (err error) {\n\n\tbelogs.Debug(\"StartTlsServer(): tlsserver port:\", port)\n\tcert, err := tls.LoadX509KeyPair(ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver LoadX509KeyPair fail: port:\", port,\n\t\t\t\" tlsPublicCrtFileName, tlsPrivateKeyFileName:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver cert:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\n\trootCrtBytes, err := ioutil.ReadFile(ts.tlsRootCrtFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver ReadFile tlsRootCrtFileName fail, port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\trootCertPool := x509.NewCertPool()\n\tok := rootCertPool.AppendCertsFromPEM(rootCrtBytes)\n\tif !ok {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver AppendCertsFromPEM tlsRootCrtFileName fail,port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, \" len(rootCrtBytes):\", len(rootCrtBytes), err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver AppendCertsFromPEM len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\tclientAuthType := tls.NoClientCert\n\tif ts.tlsVerifyClient {\n\t\tclientAuthType = tls.RequireAndVerifyClientCert\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver clientAuthType:\", clientAuthType)\n\n\t// https://stackoverflow.com/questions/63676241/how-to-set-setkeepaliveperiod-on-a-tls-conn\n\tsetTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t// Check that the underlying connection really is TCP.\n\t\tif tcpConn, ok := clientHello.Conn.(*net.TCPConn); ok {\n\t\t\ttcpConn.SetKeepAlive(true)\n\t\t\ttcpConn.SetKeepAlivePeriod(time.Second * 300)\n\t\t\tbelogs.Debug(\"StartTlsServer(): tlsserver SetKeepAlive:\")\n\t\t}\n\t\t// Make sure to return nil, nil to let the caller fall back on the default behavior.\n\t\treturn nil, nil\n\t}\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: clientAuthType,\n\t\tRootCAs: rootCertPool,\n\t\tInsecureSkipVerify: false,\n\t\tGetConfigForClient: setTCPKeepAlive,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver Listen fail, port:\", port, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): Listen ok, port:\", port)\n\n\t// get tcpListener\n\tts.tcpListener, err = NewFromTlsListener(listener)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver NewFromTlsListener fail, port: \", port, err)\n\t\treturn err\n\t}\n\tbelogs.Info(\"StartTlsServer(): tlsserver create server ok, port:\", port, \" will accept client\")\n\n\tgo ts.waitBusinessToConnMsg()\n\n\t// wait new conn\n\tts.acceptNewConn()\n\treturn nil\n}", "func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) {\n\t// Bytes to be sent to the peer. Should never block the sender.\n\tpostCh := make(chan []byte, 4)\n\t// A single error value sent when the writer completes.\n\twriteDone := make(chan error, 1)\n\t// Performs writes to the socket and ensures posts don't block.\n\tgo handshakeWriter(sock, postCh, writeDone)\n\n\tdefer func() {\n\t\tclose(postCh) // Done writing.\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t// Wait until writes complete before returning from handshake.\n\t\terr = <-writeDone\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"error writing: %s\", err)\n\t\t}\n\t}()\n\n\tpost := func(bb []byte) {\n\t\tselect {\n\t\tcase postCh <- bb:\n\t\tdefault:\n\t\t\tpanic(\"mustn't block while posting\")\n\t\t}\n\t}\n\n\tpost([]byte(Protocol))\n\tpost(extensions[:])\n\tif ih != nil { // We already know what we want.\n\t\tpost(ih[:])\n\t\tpost(peerID[:])\n\t}\n\tvar b [68]byte\n\t_, err = io.ReadFull(sock, b[:68])\n\tif err != nil {\n\t\terr = nil\n\t\treturn\n\t}\n\tif string(b[:20]) != Protocol {\n\t\treturn\n\t}\n\tmissinggo.CopyExact(&res.PeerExtensionBits, b[20:28])\n\tmissinggo.CopyExact(&res.Hash, b[28:48])\n\tmissinggo.CopyExact(&res.PeerID, b[48:68])\n\t// peerExtensions.Add(res.PeerExtensionBits.String(), 1)\n\n\t// TODO: Maybe we can just drop peers here if we're not interested. This\n\t// could prevent them trying to reconnect, falsely believing there was\n\t// just a problem.\n\tif ih == nil { // We were waiting for the peer to tell us what they wanted.\n\t\tpost(res.Hash[:])\n\t\tpost(peerID[:])\n\t}\n\n\tok = true\n\treturn\n}", "func BenchmarkEncrypt(b *testing.B) {\n\tdata := make([]byte, 1e7, 1e7) //10 mb of data for testing\n\trand.Seed(time.Now().UnixNano())\n\trand.Read(data)\n\n\tb.ResetTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tEncrypt(data, \"password\")\n\t}\n}", "func (c *peerConn) serverHandshake() error {\n\t// Whether the handshake status is based on handshake\n\tif c.handshakeCompiled() {\n\t\treturn nil\n\t}\n\n\t// Read reply data\n\thello, err := c.readHelloRequestMsg()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.logger.Debugf(\"receive handshake request by nodeId %s, version: %d\", hello.id, hello.version)\n\tif hello.version != c.version {\n\t\treturn fmt.Errorf(\"handshake check err, got version: %d, want version: %d\",\n\t\t\thello.version, c.version)\n\t}\n\tgotId := hello.receiveId\n\twantId := c.self\n\tif !bytes.Equal(gotId[:], wantId[:]) {\n\t\treturn fmt.Errorf(\"handshake check err got my name: 0x%x, my real name: 0x%x\",\n\t\t\tgotId, wantId)\n\t}\n\tc.id = hello.id\n\n\treply := &helloReRequestMsg{\n\t\tid: c.self,\n\t\treceiveId: hello.id,\n\t\tversion: c.version,\n\t}\n\n\tc.logger.Debugf(\"send handshake reply to nodeId %s\", reply.receiveId)\n\tif _, err = c.rw.Write(reply.marshal()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func testServer(t *testing.T, useTLS bool) {\n\tvar (\n\t\tclientConfig *ClientConfig\n\t)\n\n\tassert := assert.New(t)\n\tzero := 0\n\tassert.Equal(0, zero)\n\n\t// Create new TestPingServer - needed for calling RPCs\n\tmyJrpcfs := &TestPingServer{}\n\n\trrSvr := getNewServer(10*time.Second, false, useTLS)\n\tassert.NotNil(rrSvr)\n\n\t// Register the Server - sets up the methods supported by the\n\t// server\n\terr := rrSvr.Register(myJrpcfs)\n\tassert.Nil(err)\n\n\t// Start listening for requests on the ipaddr/port\n\tstartErr := rrSvr.Start()\n\tassert.Nil(startErr, \"startErr is not nil\")\n\n\t// Tell server to start accepting and processing requests\n\trrSvr.Run()\n\n\t// Now - setup a client to send requests to the server\n\tif useTLS {\n\t\tclientConfig = &ClientConfig{\n\t\t\tDNSOrIPAddr: testIPAddr,\n\t\t\tPort: testPort,\n\t\t\tRootCAx509CertificatePEM: testTLSCerts.caCertPEMBlock,\n\t\t\tCallbacks: nil,\n\t\t\tDeadlineIO: 60 * time.Second,\n\t\t\tKeepAlivePeriod: 60 * time.Second,\n\t\t\tLogger: newLogger(),\n\t\t}\n\t} else {\n\t\tclientConfig = &ClientConfig{\n\t\t\tDNSOrIPAddr: testIPAddr,\n\t\t\tPort: testPort,\n\t\t\tRootCAx509CertificatePEM: nil,\n\t\t\tCallbacks: nil,\n\t\t\tDeadlineIO: 60 * time.Second,\n\t\t\tKeepAlivePeriod: 60 * time.Second,\n\t\t\tLogger: newLogger(),\n\t\t}\n\t}\n\trrClnt, newErr := NewClient(clientConfig)\n\tassert.NotNil(rrClnt)\n\tassert.Nil(newErr)\n\n\t// Send an RPC which should return success\n\tpingRequest := &TestPingReq{Message: \"Ping Me!\"}\n\tpingReply := &TestPingReply{}\n\tsendErr := rrClnt.Send(\"RpcTestPing\", pingRequest, pingReply)\n\tassert.Nil(sendErr)\n\tassert.Equal(\"pong 8 bytes\", pingReply.Message)\n\tassert.Equal(1, rrSvr.CompletedCnt())\n\n\t// Send an RPC which expects the client ID and which should return success\n\tpingRequest = &TestPingReq{Message: \"Ping Me!\"}\n\tpingReply = &TestPingReply{}\n\tsendErr = rrClnt.Send(\"RpcTestPingWithClientID\", pingRequest, pingReply)\n\tassert.Nil(sendErr)\n\tassert.Equal(\"Client ID: 1 pong 8 bytes\", pingReply.Message)\n\tassert.Equal(2, rrSvr.CompletedCnt())\n\n\t// Send an RPC which should return an error\n\tpingRequest = &TestPingReq{Message: \"Ping Me!\"}\n\tpingReply = &TestPingReply{}\n\tsendErr = rrClnt.Send(\"RpcTestPingWithError\", pingRequest, pingReply)\n\tassert.NotNil(sendErr)\n\n\tassert.Equal(3, rrSvr.CompletedCnt())\n\n\t// Send an RPC which should return an error\n\tpingRequest = &TestPingReq{Message: \"Ping Me!\"}\n\tpingReply = &TestPingReply{}\n\tsendErr = rrClnt.Send(\"RpcTestInvalidMethod\", pingRequest, pingReply)\n\tassert.NotNil(sendErr)\n\n\tassert.Equal(4, rrSvr.CompletedCnt())\n\n\t// Stop the client before exiting\n\trrClnt.Close()\n\n\t// Stop the server before exiting\n\trrSvr.Close()\n}", "func TestPionE2ELossy(t *testing.T) {\n\t// Check for leaking routines\n\treport := transportTest.CheckRoutines(t)\n\tdefer report()\n\n\ttype runResult struct {\n\t\tdtlsConn *dtls.Conn\n\t\terr error\n\t}\n\n\tserverCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclientCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, test := range []struct {\n\t\tLossChanceRange int\n\t\tDoClientAuth bool\n\t\tCipherSuites []dtls.CipherSuiteID\n\t\tMTU int\n\t}{\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t} {\n\t\tname := fmt.Sprintf(\"Loss%d_MTU%d\", test.LossChanceRange, test.MTU)\n\t\tif test.DoClientAuth {\n\t\t\tname += \"_WithCliAuth\"\n\t\t}\n\t\tfor _, ciph := range test.CipherSuites {\n\t\t\tname += \"_With\" + ciph.String()\n\t\t}\n\t\ttest := test\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Limit runtime in case of deadlocks\n\t\t\tlim := transportTest.TimeOut(lossyTestTimeout + time.Second)\n\t\t\tdefer lim.Stop()\n\n\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\tchosenLoss := rand.Intn(9) + test.LossChanceRange //nolint:gosec\n\t\t\tserverDone := make(chan runResult)\n\t\t\tclientDone := make(chan runResult)\n\t\t\tbr := transportTest.NewBridge()\n\n\t\t\tif err = br.SetLossChance(chosenLoss); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tCipherSuites: test.CipherSuites,\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.Certificates = []tls.Certificate{clientCert}\n\t\t\t\t}\n\n\t\t\t\tclient, startupErr := dtls.Client(dtlsnet.PacketConnFromConn(br.GetConn0()), br.GetConn0().RemoteAddr(), cfg)\n\t\t\t\tclientDone <- runResult{client, startupErr}\n\t\t\t}()\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tCertificates: []tls.Certificate{serverCert},\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.ClientAuth = dtls.RequireAnyClientCert\n\t\t\t\t}\n\n\t\t\t\tserver, startupErr := dtls.Server(dtlsnet.PacketConnFromConn(br.GetConn1()), br.GetConn1().RemoteAddr(), cfg)\n\t\t\t\tserverDone <- runResult{server, startupErr}\n\t\t\t}()\n\n\t\t\ttestTimer := time.NewTimer(lossyTestTimeout)\n\t\t\tvar serverConn, clientConn *dtls.Conn\n\t\t\tdefer func() {\n\t\t\t\tif serverConn != nil {\n\t\t\t\t\tif err = serverConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif clientConn != nil {\n\t\t\t\t\tif err = clientConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif serverConn != nil && clientConn != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tbr.Tick()\n\t\t\t\tselect {\n\t\t\t\tcase serverResult := <-serverDone:\n\t\t\t\t\tif serverResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, serverError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, serverResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tserverConn = serverResult.dtlsConn\n\t\t\t\tcase clientResult := <-clientDone:\n\t\t\t\t\tif clientResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, clientError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, clientResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tclientConn = clientResult.dtlsConn\n\t\t\t\tcase <-testTimer.C:\n\t\t\t\t\tt.Errorf(\"Test expired: clientComplete(%t) serverComplete(%t) LossChance(%d)\", clientConn != nil, serverConn != nil, chosenLoss)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(10 * time.Millisecond):\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (sc *serverCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {\n\tserverConfig := sc.serverConfig.Config()\n\n\tconn := tls.Server(rawConn, &serverConfig)\n\tl := sc.logger.With(\"remote address\", conn.RemoteAddr().String())\n\tstart := time.Now()\n\tif err := conn.Handshake(); err != nil {\n\t\tl.Errorf(\"Server TLS handshake failed in %s with error %s\", time.Since(start), err)\n\t\treturn nil, nil, err\n\t}\n\tl.Debugf(\"Server TLS handshake completed in %s\", time.Since(start))\n\treturn conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil\n}", "func BenchmarkPlainStreaming(b *testing.B) {\n\tbenchmark(b, streamingHandler, false)\n}", "func TestProbeHTTPSNoScheme(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tu, err := url.Parse(server.URL)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), u.Host, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func (c *TLSConn) PrintConnectionStatus() {\n\ttlsVersions := [...]uint16{\n\t\ttls.VersionSSL30,\n\t\ttls.VersionTLS10,\n\t\ttls.VersionTLS11,\n\t\ttls.VersionTLS12,\n\t\ttls.VersionTLS13,\n\t}\n\n\tcipherSuites := [...]uint16{\n\t\ttls.TLS_RSA_WITH_RC4_128_SHA,\n\t\ttls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA256,\n\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n\t\ttls.TLS_AES_128_GCM_SHA256,\n\t\ttls.TLS_AES_256_GCM_SHA384,\n\t\ttls.TLS_CHACHA20_POLY1305_SHA256,\n\t\ttls.TLS_FALLBACK_SCSV,\n\t}\n\n\tcs := c.conn.ConnectionState()\n\n\tfor i, cert := range cs.PeerCertificates {\n\t\tif i > 0 {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t}\n\n\t\tfmt.Printf(\"Server Key and Certificate #%d\\n\", i+1)\n\t\tfmt.Println(strings.Repeat(\"*\", 85))\n\n\t\tPrintDetails(\"Subject\", cert.Subject.String())\n\t\tPrintDetails(\"Alternative Names\", strings.Join(cert.DNSNames, \",\"))\n\t\tPrintDetails(\"Serial Number\", cert.SerialNumber.Text(16))\n\t\tPrintDetails(\"Valid From\", cert.NotBefore.Format(time.RFC1123))\n\t\tPrintDetails(\"Valid Until\", fmt.Sprintf(\"%s (expires in %d days)\",\n\t\t\tcert.NotAfter.Format(time.RFC1123),\n\t\t\tint(time.Until(cert.NotAfter).Hours()/24)))\n\n\t\tPrintDetails(\"Key\", PublicKeyDetails(cert))\n\n\t\t//weak key\n\n\t\tPrintDetails(\"Issuer\", cert.Issuer.String())\n\t\tPrintDetails(\"Signature Algorithm\", cert.SignatureAlgorithm.String())\n\n\t\t//extended validation\n\t\t// I can't find any examples of extended validation.\n\n\t\t//certificate transparency\n\t\t//OCSP must staple\n\t\t//revocation information\n\t\tPrintDetails(\"Revocation Information\", strings.Join(cert.CRLDistributionPoints, \",\"))\n\n\t\t//revocation status\n\t\t//DNS CAA\n\t\t//Trusted\n\t}\n\n\tfmt.Printf(\"\\nDefault Connection Details\\n\")\n\tfmt.Println(strings.Repeat(\"*\", 85))\n\tPrintDetails(\"Version\", TLSVersionName(cs.Version))\n\tPrintDetails(\"Cipher Suite\", CipherSuiteName(cs.CipherSuite))\n\n\tfmt.Printf(\"\\nSupported TLS/SSL Versions\\n\")\n\tfmt.Println(strings.Repeat(\"*\", 85))\n\n\tfmt.Printf(\"%-45s\", \"Cipher Suite\")\n\n\tfor _, tlsVersion := range tlsVersions {\n\t\tfmt.Printf(\" %-7s\", TLSVersionName(tlsVersion))\n\t}\n\n\tfmt.Printf(\"\\n\")\n\n\tfmt.Println(strings.Repeat(\"*\", 85))\n\n\tfor _, cipherSuite := range cipherSuites {\n\t\tfmt.Printf(\"%-45s\", CipherSuiteName(cipherSuite))\n\n\t\tfor _, tlsVersion := range tlsVersions {\n\t\t\tfmt.Printf(\" %-7v\", TestTLSConfig(c.host, c.port, c.name, tlsVersion, cipherSuite))\n\t\t}\n\n\t\tfmt.Printf(\"\\n\")\n\t}\n}", "func BenchmarkConnection(b *testing.B) {\n\ttestingSetUp()\n\tdefer testingTearDown()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tconn := testPool.NewConn()\n\t\t_ = conn.Close()\n\t}\n}", "func Handshake(rw io.ReadWriter) (int, error) {\n\t// Read RFC 1928 for request and reply structure and sizes.\n\n\t/*\n\t +----+----------+----------+\n\t |VER | NMETHODS | METHODS |\n\t +----+----------+----------+\n\t | 1 | 1 | 1 to 255 |\n\t +----+----------+----------+\n\t*/\n\n\tbuf := make([]byte, MaxAddrLen)\n\n\t// read VER, NMETHODS, METHODS\n\tif _, err := io.ReadFull(rw, buf[:2]); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// check VER\n\tif buf[0] != 0x05 {\n\t\treturn 0, ErrConnectionNotAllowed\n\t}\n\n\tnmethods := buf[1]\n\tif _, err := io.ReadFull(rw, buf[:nmethods]); err != nil {\n\t\treturn 0, err\n\t}\n\n\t/*\n\t +----+--------+\n\t |VER | METHOD |\n\t +----+--------+\n\t | 1 | 1 |\n\t +----+--------+\n\t*/\n\n\t// write VER METHOD\n\tif _, err := rw.Write([]byte{0x05, 0x00}); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// read VER CMD RSV\n\tif _, err := io.ReadFull(rw, buf[:3]); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(buf[1]), nil\n}", "func newServer(cert *shared.CertInfo, handler http.Handler) *httptest.Server {\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.TLS = util.ServerTLSConfig(cert)\n\tserver.StartTLS()\n\treturn server\n}", "func New(L *lua.LState) int {\n\tvar tlsConfig *tls.Config\n\tbind := \"127.0.0.1:0\"\n\tswitch bindOrTable := L.CheckAny(1).(type) {\n\tcase lua.LString:\n\t\tbind = string(bindOrTable)\n\tcase *lua.LTable:\n\t\tif addr, ok := L.GetField(bindOrTable, \"addr\").(lua.LString); ok {\n\t\t\tbind = string(addr)\n\t\t}\n\t\tserverPublicCertPEMFile := L.GetField(bindOrTable, `server_public_cert_pem_file`)\n\t\tserverPrivateKeyPemFile := L.GetField(bindOrTable, `server_private_key_pem_file`)\n\t\tif serverPublicCertPEMFile != lua.LNil && serverPrivateKeyPemFile != lua.LNil {\n\t\t\tserverCert, err := tls.LoadX509KeyPair(serverPublicCertPEMFile.String(), serverPrivateKeyPemFile.String())\n\t\t\tif err != nil {\n\t\t\t\tL.RaiseError(\"error loading server cert: %v\", err)\n\t\t\t}\n\t\t\ttlsConfig = &tls.Config{\n\t\t\t\tCertificates: []tls.Certificate{serverCert},\n\t\t\t}\n\n\t\t\tclientAuth := L.GetField(bindOrTable, \"client_auth\")\n\t\t\tif clientAuth != lua.LNil {\n\t\t\t\tif _, ok := clientAuth.(lua.LString); !ok {\n\t\t\t\t\tL.ArgError(1, \"client_auth should be a string\")\n\t\t\t\t}\n\t\t\t\tswitch clientAuth.String() {\n\t\t\t\tcase \"NoClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.NoClientCert\n\t\t\t\tcase \"RequestClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequestClientCert\n\t\t\t\tcase \"RequireAnyClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequireAnyClientCert\n\t\t\t\tcase \"VerifyClientCertIfGiven\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.VerifyClientCertIfGiven\n\t\t\t\tcase \"RequireAndVerifyClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclientCAs := L.GetField(bindOrTable, \"client_cas_pem_file\")\n\t\t\tif clientCAs != lua.LNil {\n\t\t\t\tif _, ok := clientCAs.(lua.LString); !ok {\n\t\t\t\t\tL.ArgError(1, \"client_cas_pem_file must be a string\")\n\t\t\t\t}\n\t\t\t\tdata, err := ioutil2.ReadFile(clientCAs.String())\n\t\t\t\tif err != nil {\n\t\t\t\t\tL.RaiseError(\"error reading %s: %v\", clientCAs, err)\n\t\t\t\t}\n\t\t\t\ttlsConfig.ClientCAs = x509.NewCertPool()\n\t\t\t\tif !tlsConfig.ClientCAs.AppendCertsFromPEM(data) {\n\t\t\t\t\tL.RaiseError(\"no certs loaded from %s\", clientCAs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tl, err := net.Listen(`tcp`, bind)\n\tif err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\tif tlsConfig != nil {\n\t\tl = tls.NewListener(l, tlsConfig)\n\t}\n\tserver := &luaServer{\n\t\tListener: l,\n\t\tserveData: make(chan *serveData, 1),\n\t}\n\tserver.serve(L)\n\tud := L.NewUserData()\n\tud.Value = server\n\tL.SetMetatable(ud, L.GetTypeMetatable(\"http_server_ud\"))\n\tL.Push(ud)\n\treturn 1\n}", "func (o *Obfuscated2) Handshake(protocol [4]byte, dc int, s mtproxy.Secret) error {\n\tk, err := generateKeys(o.rand, protocol, s.Secret, dc)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"generate keys\")\n\t}\n\to.keys = k\n\n\tif _, err := o.conn.Write(o.header); err != nil {\n\t\treturn errors.Wrap(err, \"write obfuscated header\")\n\t}\n\n\treturn nil\n}", "func TestProbeHTTPS(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func speedtest1_final(tls *libc.TLS) { /* speedtest1.c:413:6: */\n\tbp := tls.Alloc(72)\n\tdefer tls.Free(72)\n\n\tif !(g.bSqlOnly != 0) {\n\t\tlibc.Xprintf(tls, ts+2583 /* \" TOTAL%.*s...\" */, libc.VaList(bp, (60-5), uintptr(unsafe.Pointer(&zDots)),\n\t\t\t(int32(g.iTotal/int64(1000))), (int32(g.iTotal%int64(1000)))))\n\t}\n\tif g.bVerify != 0 {\n\t\tvar i int32\n\t\tlibc.Xprintf(tls, ts+2611 /* \"Verification Has...\" */, libc.VaList(bp+40, g.nResByte))\n\t\tHashUpdate(tls, ts+2636 /* \"\\n\" */, uint32(1))\n\t\tHashFinal(tls)\n\t\tfor i = 0; i < 24; i++ {\n\t\t\tlibc.Xprintf(tls, ts+2638 /* \"%02x\" */, libc.VaList(bp+56, int32(*(*uint8)(unsafe.Pointer((uintptr(unsafe.Pointer(&g)) + 3104 /* &.hash */ + 259 /* &.r */) + uintptr(i))))))\n\t\t}\n\t\tif (g.hashFile != 0) && (g.hashFile != (libc.X__acrt_iob_func(tls, uint32(1)))) {\n\t\t\tlibc.Xfclose(tls, g.hashFile)\n\t\t}\n\t\tlibc.Xprintf(tls, ts+2636 /* \"\\n\" */, 0)\n\t}\n}", "func TestTransportTimeoutServerHangs(t *testing.T) {\n\tclientDone := make(chan struct{})\n\tct := newClientTester(t)\n\tct.client = func() error {\n\t\tdefer ct.cc.(*net.TCPConn).CloseWrite()\n\t\tdefer close(clientDone)\n\n\t\tbuf := make([]byte, 1<<19)\n\t\t_, err := rand.Read(buf)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"fail to gen random data\")\n\t\t}\n\t\theaderVal := hex.EncodeToString(buf)\n\n\t\treq, err := http.NewRequest(\"PUT\", \"https://dummy.tld/\", nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\t\tdefer cancel()\n\t\treq = req.WithContext(ctx)\n\t\treq.Header.Add(\"Authorization\", headerVal)\n\t\t_, err = ct.tr.RoundTrip(req)\n\t\tif err == nil {\n\t\t\treturn errors.New(\"error should not be nil\")\n\t\t}\n\t\tif ne, ok := err.(net.Error); !ok || !ne.Timeout() {\n\t\t\treturn fmt.Errorf(\"error should be a net error timeout was: +%v\", err)\n\t\t}\n\t\treturn nil\n\t}\n\tct.server = func() error {\n\t\tct.greet()\n\t\tselect {\n\t\tcase <-time.After(5 * time.Second):\n\t\tcase <-clientDone:\n\t\t}\n\t\treturn nil\n\t}\n\tct.run()\n}", "func TestLatencyTestReal(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping test in short mode.\")\n\t}\n\tserverID := \"16976\"\n\n\tconfig := configuration{\n\t\tServerID: serverID,\n\t\tTimeout: 5,\n\t\t//MaxSeconds: 4.0,\n\t}\n\n\tserver := GetServerByID(serverID)\n\tserver.Configuration = &config\n\n\tlocalAddr := net.TCPAddr{}\n\tsource, _ := net.ResolveTCPAddr(\"tcp\", localAddr.String())\n\n\tspdTest := speedtest{\n\t\tSource: source,\n\t}\n\n\tserver.Speedtest = &spdTest\n\tspdTest.Server = &server\n\n\tLatencyTest(&server)\n\tallResults := server.Results\n\n\tresults := allResults.Latency.Seconds()\n\n\tif results <= 0 {\n\t\tt.Fatalf(\"Error: Expected a positive Latency result, but got: %f, err: %s\", results, allResults.Error)\n\t}\n\tfmt.Printf(\"\\nLatency test results for server %s ... %f\\n\", serverID, results)\n}", "func TestFastPath(t *testing.T) {\n\ts1, s2 := memnet.NewConn(\"noise\", 128000)\n\tb := &bufferedWriteConn{s1, bufio.NewWriterSize(s1, 10000), false}\n\tclient, server := pairWithConns(t, b, s2)\n\n\tb.manualFlush = true\n\n\tsb := sinkReads(server)\n\n\tconst packets = 10\n\ts := \"test\"\n\tfor i := 0; i < packets; i++ {\n\t\t// Many separate writes, to force separate Noise frames that\n\t\t// all get buffered up and then all sent as a single slice to\n\t\t// the server.\n\t\tif _, err := io.WriteString(client, s); err != nil {\n\t\t\tt.Fatalf(\"client write1 failed: %v\", err)\n\t\t}\n\t}\n\tif err := b.w.Flush(); err != nil {\n\t\tt.Fatalf(\"client flush failed: %v\", err)\n\t}\n\tclient.Close()\n\n\twant := strings.Repeat(s, packets)\n\tif got := sb.String(len(want)); got != want {\n\t\tt.Fatalf(\"wrong content received: got %q, want %q\", got, want)\n\t}\n\tif err := sb.Error(); err != io.EOF {\n\t\tt.Fatalf(\"client close wasn't seen by server\")\n\t}\n}", "func (self *nntpConnection) outboundHandshake(conn *textproto.Conn) (stream, reader bool, err error) {\n log.Println(self.name, \"outbound handshake\")\n var code int\n var line string\n for err == nil {\n code, line, err = conn.ReadCodeLine(-1)\n log.Println(self.name, line)\n if err == nil {\n if code == 200 {\n // send capabilities\n log.Println(self.name, \"ask for capabilities\")\n err = conn.PrintfLine(\"CAPABILITIES\")\n if err == nil {\n // read response\n dr := conn.DotReader()\n r := bufio.NewReader(dr)\n for {\n line, err = r.ReadString('\\n')\n if err == io.EOF {\n // we are at the end of the dotreader\n // set err back to nil and break out\n err = nil\n break\n } else if err == nil {\n // we got a line\n if line == \"MODE-READER\\n\" || line == \"READER\\n\" {\n log.Println(self.name, \"supports READER\")\n reader = true\n } else if line == \"STREAMING\\n\" {\n stream = true\n log.Println(self.name, \"supports STREAMING\")\n } else if line == \"POSTIHAVESTREAMING\\n\" {\n stream = true\n reader = false\n log.Println(self.name, \"is SRNd\")\n }\n } else {\n // we got an error\n log.Println(\"error reading capabilities\", err)\n break\n }\n }\n // return after reading\n return\n }\n } else if code == 201 {\n log.Println(\"feed\", self.name,\"does not allow posting\")\n // we don't do auth yet\n break\n } else {\n continue\n }\n }\n }\n return\n}", "func TestNewKeepAliveListener(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected listen error: %v\", err)\n\t}\n\n\tln, err = NewKeepAliveListener(ln, \"http\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"http://\" + ln.Addr().String())\n\tconn, err := ln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*keepAliveConn); !ok {\n\t\tt.Fatalf(\"Unexpected conn type: %T, wanted *keepAliveConn\", conn)\n\t}\n\tconn.Close()\n\tln.Close()\n\n\tln, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Listen error: %v\", err)\n\t}\n\n\t// tls\n\ttlsinfo, err := createSelfCert(t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create tmpfile: %v\", err)\n\t}\n\ttlsInfo := TLSInfo{CertFile: tlsinfo.CertFile, KeyFile: tlsinfo.KeyFile}\n\ttlsInfo.parseFunc = fakeCertificateParserFunc(tls.Certificate{}, nil)\n\ttlscfg, err := tlsInfo.ServerConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected serverConfig error: %v\", err)\n\t}\n\ttlsln, err := NewKeepAliveListener(ln, \"https\", tlscfg)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"https://\" + tlsln.Addr().String())\n\tconn, err = tlsln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*tls.Conn); !ok {\n\t\tt.Errorf(\"failed to accept *tls.Conn\")\n\t}\n\tconn.Close()\n\ttlsln.Close()\n}", "func Benchmark_Ctx_SendString_B(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tbody := \"Hello, world!\"\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.SendString(body)\n\t}\n\tutils.AssertEqual(b, []byte(\"Hello, world!\"), c.Fasthttp.Response.Body())\n}", "func testReadWithCustomServer(t *testing.T, testData []byte, serverFunc func(conn *WSConn)) {\n\t// Start the server.\n\twst := newWSTester(serverFunc)\n\tdefer wst.Close()\n\n\t// Connect a client that reads all of the data at once.\n\tclient, err := wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treadBuf := make([]byte, len(testData))\n\t_, err = io.ReadFull(client, readBuf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n\n\t// Connect a client that reads 2 times 50% of the data.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[:len(readBuf)/2])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[len(readBuf)/2:])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n\n\t// Connect a client that reads more than the available data.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tn, err := client.Read(readBuf)\n\tif n != 0 || err != nil {\n\t\tt.Fatal(\"expecte n == 0 and err == nil\", n, err)\n\t}\n\n\t// Connect a client that reads only half the data without closing the conn.\n\t// This shouldn't block the next client.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = io.ReadFull(client, readBuf[:len(readBuf)/2])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Connect a client that does random reading until all of the data is read.\n\tclient, err = wst.NewClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar readBytes int\n\tfor remainingBytes := len(testData) - readBytes; remainingBytes > 0; remainingBytes = len(testData) - readBytes {\n\t\ttoRead := fastrand.Intn(remainingBytes) + 1\n\t\t_, err = io.ReadFull(client, readBuf[readBytes:][:toRead])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\treadBytes += toRead\n\t}\n\tif !bytes.Equal(readBuf, testData) {\n\t\tt.Fatal(\"readBuf doesn't match testData\")\n\t}\n}", "func testClientAuth(t *testing.T) {\n\tsrv := getServer(rootPort, testdataDir, \"\", 0, t)\n\tsrv = getTLSConfig(srv, \"RequireAndVerifyClientCert\", []string{\"../testdata/root.pem\"})\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Root server start failed: %s\", err)\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tclientConfig := &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t},\n\t}\n\n\trawURL := fmt.Sprintf(\"https://admin:adminpw@localhost:%d\", rootPort)\n\n\t// Enrolling without any client certificate and key information set\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err == nil {\n\t\tt.Errorf(\"Client Auth Type: RequireAndVerifyClientCert, should have failed as no client cert was provided\")\n\t}\n\n\t// Client created with certificate and key for TLS\n\tclientConfig = &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t\tClient: tls.KeyCertFiles{\n\t\t\t\tKeyFile: \"../testdata/tls_client-key.pem\",\n\t\t\t\tCertFile: \"../testdata/tls_client-cert.pem\",\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err != nil {\n\t\tt.Errorf(\"Client Auth Type: RequireAndVerifyClientCert, failed to enroll over TLS with client certificate provided\")\n\t}\n\n\terr = srv.Stop()\n\tif err != nil {\n\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t}\n}", "func Server(conn net.Conn, ctx *Ctx) (*Conn, error) {\n\tc, err := newConn(conn, ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tC.SSL_set_accept_state(c.ssl)\n\treturn c, nil\n}", "func TestConnMemoryOverhead(t *testing.T) {\n\tnum := 1000\n\tif testing.Short() {\n\t\tnum = 100\n\t}\n\tng0 := runtime.NumGoroutine()\n\n\truntime.GC()\n\tvar ms0 runtime.MemStats\n\truntime.ReadMemStats(&ms0)\n\n\tvar closers []io.Closer\n\tcloseAll := func() {\n\t\tfor _, c := range closers {\n\t\t\tc.Close()\n\t\t}\n\t\tclosers = nil\n\t}\n\tdefer closeAll()\n\n\tfor i := 0; i < num; i++ {\n\t\tclient, server := pair(t)\n\t\tclosers = append(closers, client, server)\n\t\tgo func() {\n\t\t\tvar buf [1]byte\n\t\t\tclient.Read(buf[:])\n\t\t}()\n\t}\n\n\tt0 := time.Now()\n\tdeadline := t0.Add(3 * time.Second)\n\tvar ngo int\n\tfor time.Now().Before(deadline) {\n\t\truntime.GC()\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo >= num {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo < num {\n\t\tt.Fatalf(\"only %v goroutines; expected %v+\", ngo, num)\n\t}\n\truntime.GC()\n\tvar ms runtime.MemStats\n\truntime.ReadMemStats(&ms)\n\tgrowthTotal := int64(ms.HeapAlloc) - int64(ms0.HeapAlloc)\n\tgrowthEach := float64(growthTotal) / float64(num)\n\tt.Logf(\"Alloced %v bytes, %.2f B/each\", growthTotal, growthEach)\n\tconst max = 2000\n\tif growthEach > max {\n\t\tt.Errorf(\"allocated more than expected; want max %v bytes/each\", max)\n\t}\n\n\tcloseAll()\n\n\t// And make sure our goroutines go away too.\n\tdeadline = time.Now().Add(3 * time.Second)\n\tfor time.Now().Before(deadline) {\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo < ng0+num/10 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo >= ng0+num/10 {\n\t\tt.Errorf(\"goroutines didn't go back down; started at %v, now %v\", ng0, ngo)\n\t}\n}", "func BenchmarkGetWithQueryClient_NoNetwork(b *testing.B) {\n\t// Create the server for http transport, but without actually having it\n\t// serve HTTP requests. Instead we're going to pass it a pre-constructed\n\t// HTTP request directly.\n\tvar service pb.TransportPermutationsServer\n\t{\n\t\tservice = handlers.NewService()\n\t\t// Wrap Service with middlewares. See handlers/service_middlewares.go\n\t\tservice = handlers.WrapService(service)\n\t}\n\tvar getwithqueryEndpoint = svc.MakeGetWithQueryEndpoint(service)\n\tendpoints := svc.Endpoints{\n\t\tGetWithQueryEndpoint: getwithqueryEndpoint,\n\t}\n\tctx := context.WithValue(context.Background(), \"request-url\", \"/getwithquery\")\n\tctx = context.WithValue(ctx, \"transport\", \"HTTPJSON\")\n\tserver := httptransport.NewServer(\n\t\t// This is definitely a hack\n\t\tendpoints.GetWithQueryEndpoint,\n\t\tsvc.DecodeHTTPGetWithQueryZeroRequest,\n\t\tsvc.EncodeHTTPGenericResponse,\n\t)\n\tvar req pb.GetWithQueryRequest\n\treq.A = 12\n\treq.B = 45360\n\n\tvar testData []ServerTestData\n\tfor i := 0; i < b.N; i++ {\n\t\thttpreq, _ := http.NewRequest(\"GET\", \"http://localhost/getwithquery\", strings.NewReader(string(\"\")))\n\t\thttpclient.EncodeHTTPGetWithQueryZeroRequest(context.Background(), httpreq, &req)\n\t\tresprecorder := httptest.NewRecorder()\n\n\t\titem := ServerTestData{\n\t\t\tr: httpreq,\n\t\t\trecorder: resprecorder,\n\t\t}\n\n\t\ttestData = append(testData, item)\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tserver.ServeHTTP(testData[i].recorder, testData[i].r)\n\t}\n}" ]
[ "0.66712373", "0.6064704", "0.6039502", "0.60158074", "0.5975568", "0.5910876", "0.5748087", "0.570298", "0.56025946", "0.5589059", "0.55880636", "0.553576", "0.55318576", "0.55202806", "0.5501527", "0.5439872", "0.5435932", "0.538367", "0.5370155", "0.5365565", "0.5362963", "0.5360056", "0.535773", "0.53433037", "0.53292704", "0.53232706", "0.5322648", "0.5289218", "0.52857333", "0.52834636", "0.528132", "0.52725786", "0.5265677", "0.52627593", "0.52625316", "0.5242739", "0.52402556", "0.5202206", "0.52009845", "0.5194825", "0.518136", "0.51807004", "0.5168536", "0.516671", "0.5156937", "0.51518005", "0.5145702", "0.51449245", "0.513856", "0.51371163", "0.51284677", "0.5106948", "0.5091923", "0.5078742", "0.5075348", "0.50695646", "0.50689113", "0.5065632", "0.5064146", "0.5063459", "0.50583607", "0.5051315", "0.50502485", "0.5039564", "0.5035367", "0.5032212", "0.50097036", "0.49911255", "0.49911022", "0.49890697", "0.4971866", "0.496611", "0.49620318", "0.49583033", "0.49558228", "0.49387768", "0.49369347", "0.4935595", "0.4924729", "0.49200132", "0.4915966", "0.4913177", "0.49118182", "0.4895638", "0.4895152", "0.4885281", "0.48831815", "0.4881488", "0.48790595", "0.48789942", "0.48750198", "0.4869479", "0.48638585", "0.4863309", "0.4862238", "0.48572192", "0.48570338", "0.48516157", "0.4847929", "0.48462036" ]
0.8009402
0
BenchmarkTLSStreaming measures endtoend TLS streaming performance for fasthttp client and server. It issues http requests over a small number of TLS keepalive connections.
func BenchmarkTLSStreaming(b *testing.B) { benchmark(b, streamingHandler, true) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tcpTLSDo(ctx context.Context, config *tcpTLSConfig) {\n\tconst timeout = 15 * time.Second\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\tdefer config.Wg.Done()\n\tout := &tcpResultPair{\n\t\tAddress: config.Address,\n\t\tEndpoint: config.Endpoint,\n\t\tTCP: model.THTCPConnectResult{},\n\t\tTLS: nil, // means: not measured\n\t}\n\tdefer func() {\n\t\tconfig.Out <- out\n\t}()\n\tol := measurexlite.NewOperationLogger(\n\t\tconfig.Logger,\n\t\t\"TCPConnect %s EnableTLS=%v SNI=%s\",\n\t\tconfig.Endpoint,\n\t\tconfig.EnableTLS,\n\t\tconfig.URLHostname,\n\t)\n\tdialer := config.NewDialer(config.Logger)\n\tdefer dialer.CloseIdleConnections()\n\tconn, err := dialer.DialContext(ctx, \"tcp\", config.Endpoint)\n\tout.TCP.Failure = tcpMapFailure(newfailure(err))\n\tout.TCP.Status = err == nil\n\tdefer measurexlite.MaybeClose(conn)\n\tif err != nil || !config.EnableTLS {\n\t\tol.Stop(err)\n\t\treturn\n\t}\n\t// See https://github.com/ooni/probe/issues/2413 to understand\n\t// why we're using a cached cert pool.\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{\"h2\", \"http/1.1\"},\n\t\tRootCAs: certpool,\n\t\tServerName: config.URLHostname,\n\t}\n\tthx := config.NewTSLHandshaker(config.Logger)\n\ttlsConn, _, err := thx.Handshake(ctx, conn, tlsConfig)\n\tol.Stop(err)\n\tout.TLS = &ctrlTLSResult{\n\t\tServerName: config.URLHostname,\n\t\tStatus: err == nil,\n\t\tFailure: newfailure(err),\n\t}\n\tmeasurexlite.MaybeClose(tlsConn)\n}", "func BenchmarkPlainStreaming(b *testing.B) {\n\tbenchmark(b, streamingHandler, false)\n}", "func TestPreservesTLS(t *testing.T) {\n\tsrv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"ok\"))\n\t})\n\tdefer srv.Close()\n\n\t// forwarder will proxy the request to whatever destination\n\tfwd, err := forward.New()\n\trequire.NoError(t, err)\n\n\tvar cs *tls.ConnectionState\n\t// this is our redirect to server\n\trdr := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tcs = req.TLS\n\t\treq.URL = testutils.ParseURI(srv.URL)\n\t\tfwd.ServeHTTP(w, req)\n\t})\n\n\t// stream handler will forward requests to redirect\n\tst, err := New(rdr)\n\trequire.NoError(t, err)\n\n\tproxy := httptest.NewUnstartedServer(st)\n\tproxy.StartTLS()\n\tdefer proxy.Close()\n\n\tre, _, err := testutils.Get(proxy.URL)\n\trequire.NoError(t, err)\n\tassert.Equal(t, http.StatusOK, re.StatusCode)\n\tassert.NotNil(t, cs)\n}", "func measureTailLatency(t *testing.T, vmNum int, images []string, latencyCh chan LatencyStat) {\n\tvar (\n\t\tidx int\n\t\tvmGroup sync.WaitGroup\n\t\ttimes = make([]float64, *latSamples)\n\t\tdone = make(chan bool)\n\t\tduraInMs = *profileTime * 1000 / float64(*latSamples)\n\t)\n\tif duraInMs*float64(vmNum) < 500 {\n\t\tduraInMs = 500\n\t\tlog.Warnf(\"Too many latency samples for %d VM, measure %.0f samples instead.\", vmNum, *profileTime*1000/duraInMs)\n\t\ttimes = times[:int(*profileTime*1000/duraInMs)]\n\t}\n\tduration := time.Duration(duraInMs)\n\n\ttime.Sleep(time.Duration(*warmUpTime) * time.Second)\n\tticker := time.NewTicker(duration * time.Millisecond)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tvmGroup.Add(1)\n\t\t\t\tgo func(idx int) {\n\t\t\t\t\tdefer vmGroup.Done()\n\t\t\t\t\tvar (\n\t\t\t\t\t\ttStart = time.Now()\n\t\t\t\t\t\tvmID = idx % vmNum\n\t\t\t\t\t\tvmIDString = strconv.Itoa(vmID)\n\t\t\t\t\t)\n\t\t\t\t\tresp, _, err := funcPool.Serve(context.Background(), vmIDString, images[vmID%len(images)], \"replay\")\n\t\t\t\t\trequire.Equal(t, resp.IsColdStart, false)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Debugf(\"VM %s: Function returned error %v\", vmIDString, err)\n\t\t\t\t\t} else if resp.Payload != \"Hello, replay_response!\" {\n\t\t\t\t\t\tlog.Debugf(\"Function returned invalid: %s\", resp.Payload)\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttimes[idx] = float64(time.Since(tStart).Milliseconds())\n\t\t\t\t\t}\n\t\t\t\t}(idx)\n\t\t\t\tidx = idx + 1\n\t\t\tcase <-done:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\ttime.Sleep(time.Duration(*profileTime) * time.Second)\n\tdone <- true\n\tvmGroup.Wait()\n\tdata := stats.LoadRawData(times)\n\tmean, err := stats.Mean(data)\n\trequire.NoError(t, err, \"Compute mean returned error\")\n\tpercentile, err := stats.Percentile(data, 90)\n\trequire.NoError(t, err, \"Compute 90 percentile returned error\")\n\tlatencyCh <- LatencyStat{\n\t\tmeanLatency: mean,\n\t\ttailLatency: percentile,\n\t}\n}", "func BenchmarkNewFetchHTTP_Parallel(b *testing.B) {\n\t// This parent benchmark function runs only once as soon as there is another\n\t// sub-benchmark.\n\n\t// Full integration benchmark test which starts a HTTP file server and uses\n\t// TCP to query it on the localhost.\n\tconst backendURL = \"http://127.0.0.1:8283/cart_example.html\"\n\tconst lenCartExampleHTML = 21601\n\n\t// grpc_server_main also reads the file from the disk so stay conistent when\n\t// running benchmarks.\n\tcmd := esitesting.StartProcess(\"go\", \"run\", \"http_server_main.go\")\n\tgo cmd.Wait() // waits forever until killed\n\tdefer cmd.Process.Kill() // kills the go process but not the main startet server\n\tdefer esitesting.KillZombieProcess(\"http_server_main\")\n\n\t// Wait until http server has been started\n\tfor i := 300; ; i = i + 100 {\n\t\td := time.Duration(i) * time.Millisecond\n\t\ttime.Sleep(d)\n\t\t_, err := http.Get(backendURL)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"BenchmarkNewFetchHTTP_Parallel: %s => Sleept %s\\n\", err, d)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tb.Run(\"Insecure\", func(b *testing.B) {\n\n\t\tfh := backend.NewFetchHTTP(backend.DefaultHTTPTransport)\n\t\trfa := &esitag.ResourceArgs{\n\t\t\tExternalReq: getExternalReqWithExtendedHeaders(),\n\t\t\tURL: backendURL,\n\t\t\tTag: esitag.Config{\n\t\t\t\tTimeout: time.Second,\n\t\t\t\tMaxBodySize: 22001,\n\t\t\t},\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tb.ReportAllocs()\n\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\tvar content []byte\n\t\t\tvar hdr http.Header\n\t\t\tvar err error\n\n\t\t\tfor pb.Next() {\n\t\t\t\thdr, content, err = fh.DoRequest(rfa)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"%+v\", err)\n\t\t\t\t}\n\t\t\t\tif hdr != nil {\n\t\t\t\t\tb.Fatal(\"Header should be nil\")\n\t\t\t\t}\n\t\t\t\tif len(content) != lenCartExampleHTML {\n\t\t\t\t\tb.Fatalf(\"Want %d\\nHave %d\", lenCartExampleHTML, len(content))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "func (s *ProxyServer) serveGenericTLS(listener net.Listener, tlsConfig *tls.Config, dbName string) error {\n\ts.log.Debugf(\"Started %s proxy.\", dbName)\n\tdefer s.log.Debugf(\"%s proxy exited.\", dbName)\n\tfor {\n\t\tclientConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif utils.IsOKNetworkError(err) || trace.IsConnectionProblem(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tgo func() {\n\t\t\tdefer clientConn.Close()\n\t\t\ttlsConn := tls.Server(clientConn, tlsConfig)\n\t\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\t\tif !utils.IsOKNetworkError(err) {\n\t\t\t\t\ts.log.WithError(err).Errorf(\"%s TLS handshake failed.\", dbName)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := s.handleConnection(tlsConn)\n\t\t\tif err != nil {\n\t\t\t\ts.log.WithError(err).Errorf(\"Failed to handle %s client connection.\", dbName)\n\t\t\t}\n\t\t}()\n\t}\n}", "func TestV3Curl_MaxStreams_BelowLimit_TLS_Small(t *testing.T) {\n\ttestV3CurlMaxStream(t, false, withCfg(*e2e.NewConfigTLS()), withMaxConcurrentStreams(3))\n}", "func TestMaxConnectionAge(t *testing.T) {\n\tt.Parallel()\n\tconst maxAge = 3 * time.Second\n\tsrv := &test.GrpcTestingServer{\n\t\tStreamingFunc: func(server test.Testing_StreamingRequestResponseServer) error {\n\t\t\t//start := time.Now()\n\t\t\t//ctx := server.Context()\n\t\t\t//<-ctx.Done()\n\t\t\t//t.Logf(\"ctx.Err() = %v after %s\", ctx.Err(), time.Since(start))\n\t\t\t//return ctx.Err()\n\t\t\ttime.Sleep(maxAge + maxAge*2/10) // +20%\n\t\t\treturn nil\n\t\t},\n\t}\n\ttestClient := func(t *testing.T, client test.TestingClient) {\n\t\tstart := time.Now()\n\t\tresp, err := client.StreamingRequestResponse(context.Background())\n\t\trequire.NoError(t, err)\n\t\t_, err = resp.Recv()\n\t\trequire.Equal(t, io.EOF, err, \"%s. Elapsed: %s\", err, time.Since(start))\n\t}\n\tkp := keepalive.ServerParameters{\n\t\tMaxConnectionAge: maxAge,\n\t\tMaxConnectionAgeGrace: maxAge,\n\t}\n\tsh := NewJoinStatHandlers()\n\tt.Run(\"gRPC\", func(t *testing.T) {\n\t\ttestKeepalive(t, false, kp, sh, srv, testClient)\n\t})\n\tt.Run(\"WebSocket\", func(t *testing.T) {\n\t\ttestKeepalive(t, true, kp, sh, srv, testClient)\n\t})\n}", "func ListenAndServeTLS(opt *Options, httpHandler http.Handler, grpcHandler *grpc.Server) error {\n\tif opt == nil {\n\t\topt = defaultOptions\n\t} else {\n\t\topt.applyDefaults()\n\t}\n\tvar cert *tls.Certificate\n\tvar err error\n\tif opt.Cert != \"\" && opt.Key != \"\" {\n\t\tcert, err = decodeCertificate(opt.Cert, opt.Key)\n\t} else {\n\t\tcert, err = readCertificateFile(opt.CertFile, opt.KeyFile)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: failed loading x509 certificate: %v\", err)\n\t}\n\tconfig, err := newDefaultTLSConfig(cert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\tln, err := net.Listen(\"tcp\", opt.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln = tls.NewListener(ln, config)\n\n\tvar h http.Handler\n\tif grpcHandler == nil {\n\t\th = httpHandler\n\t} else {\n\t\th = grpcHandlerFunc(grpcHandler, httpHandler)\n\t}\n\tsublogger := log.With().Str(\"addr\", opt.Addr).Logger()\n\n\t// Set up the main server.\n\tserver := &http.Server{\n\t\tReadHeaderTimeout: 10 * time.Second,\n\t\tReadTimeout: 30 * time.Second,\n\t\t// WriteTimeout is set to 0 for streaming replies\n\t\tWriteTimeout: 0,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tTLSConfig: config,\n\t\tHandler: h,\n\t\tErrorLog: stdlog.New(&log.StdLogWrapper{Logger: &sublogger}, \"\", 0),\n\t}\n\n\treturn server.Serve(ln)\n}", "func TestUpdateTLS_NoneToTLS(t *testing.T) {\n\ttestCases := []*TLSUpdateCase{\n\t\tNewTLSUpdateCase(t, protocol.HTTP1, util.NewHTTPServer(t, nil)),\n\t\t// NewTLSUpdateCase(t, protocol.HTTP2, util.NewUpstreamHTTP2(t, appaddr, nil)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(false)\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tt.Logf(\"verify non-tls\")\n\t\tverify()\n\t\t// update to tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{DefaultTLSConfig}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tt.Logf(\"verify tls\")\n\t\tverify()\n\t\ttc.FinishCase()\n\n\t}\n}", "func BenchmarkTLSHandshakeRSAWithClientSessionCache(b *testing.B) {\n\tbc := &benchConfig{\n\t\tIsTLS: true,\n\t\tDisableClientSessionCache: false,\n\t}\n\tbenchmarkExt(b, handshakeHandler, bc)\n}", "func HTTPAPIServerStreamHLSTS(c *gin.Context) {\n\trequestLogger := log.WithFields(logrus.Fields{\n\t\t\"module\": \"http_hls\",\n\t\t\"stream\": c.Param(\"uuid\"),\n\t\t\"channel\": c.Param(\"channel\"),\n\t\t\"func\": \"HTTPAPIServerStreamHLSTS\",\n\t})\n\n\tif !Storage.StreamChannelExist(c.Param(\"uuid\"), c.Param(\"channel\")) {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotFound.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamChannelExist\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\tcodecs, err := Storage.StreamChannelCodecs(c.Param(\"uuid\"), c.Param(\"channel\"))\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamCodecs\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\toutfile := bytes.NewBuffer([]byte{})\n\tMuxer := ts.NewMuxer(outfile)\n\tMuxer.PaddingToMakeCounterCont = true\n\terr = Muxer.WriteHeader(codecs)\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"WriteHeader\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\tseqData, err := Storage.StreamHLSTS(c.Param(\"uuid\"), c.Param(\"channel\"), stringToInt(c.Param(\"seq\")))\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamHLSTS\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\tif len(seqData) == 0 {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotHLSSegments.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"seqData\",\n\t\t}).Errorln(ErrorStreamNotHLSSegments.Error())\n\t\treturn\n\t}\n\tfor _, v := range seqData {\n\t\tv.CompositionTime = 1\n\t\terr = Muxer.WritePacket(*v)\n\t\tif err != nil {\n\t\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\"call\": \"WritePacket\",\n\t\t\t}).Errorln(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\terr = Muxer.WriteTrailer()\n\tif err != nil {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"WriteTrailer\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\t_, err = c.Writer.Write(outfile.Bytes())\n\tif err != nil {\n\t\tc.IndentedJSON(400, Message{Status: 0, Payload: err.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"Write\",\n\t\t}).Errorln(err.Error())\n\t\treturn\n\t}\n\n}", "func BenchmarkTCPFindCipherFail(b *testing.B) {\n\tb.StopTimer()\n\tb.ResetTimer()\n\n\tlistener, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 0})\n\tif err != nil {\n\t\tb.Fatalf(\"ListenTCP failed: %v\", err)\n\t}\n\n\tcipherList, err := MakeTestCiphers(ss.MakeTestSecrets(100))\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\ttestPayload := ss.MakeTestPayload(50)\n\tfor n := 0; n < b.N; n++ {\n\t\tgo func() {\n\t\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"Failed to dial %v: %v\", listener.Addr(), err)\n\t\t\t}\n\t\t\tconn.Write(testPayload)\n\t\t\tconn.Close()\n\t\t}()\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"AcceptTCP failed: %v\", err)\n\t\t}\n\t\tclientIP := clientConn.RemoteAddr().(*net.TCPAddr).IP\n\t\tb.StartTimer()\n\t\tfindAccessKey(clientConn, clientIP, cipherList)\n\t\tb.StopTimer()\n\t}\n}", "func TestUpdateTLS_TLSToNone(t *testing.T) {\n\ttestCases := []*TLSUpdateCase{\n\t\tNewTLSUpdateCase(t, protocol.HTTP1, util.NewHTTPServer(t, nil)),\n\t\t// NewTLSUpdateCase(t, protocol.HTTP2, util.NewUpstreamHTTP2(t, appaddr, nil)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(true)\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tverify()\n\t\t// update to non-tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{v2.TLSConfig{}}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tverify()\n\t\t// finish\n\t\ttc.FinishCase()\n\t}\n\n}", "func BenchmarkPlainHandshake(b *testing.B) {\n\tbenchmark(b, handshakeHandler, false)\n}", "func HTTP2ALPNTLSWrap(conn *net.TCPConn, cfg *tls.Config, tFunc TLSWrapperFunc) (*tls.Conn, error) {\n\tprotoCfg := cfg.Clone()\n\t// TODO: append here\n\tprotoCfg.NextProtos = []string{http2.NextProtoTLS}\n\tprotoCfg.MinVersion = tls.VersionTLS12\n\n\tvar tlsConn *tls.Conn\n\tfor {\n\t\tif err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConn = tFunc(conn, protoCfg)\n\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\t\tif netErr.Timeout() || netErr.Temporary() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := conn.SetDeadline(time.Time{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\t}\n\n\t// Check if we're creating a client conn before checking verification\n\tif isTLSClient(tFunc) {\n\t\tif !protoCfg.InsecureSkipVerify {\n\t\t\tif err := tlsConn.VerifyHostname(protoCfg.ServerName); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tstate := tlsConn.ConnectionState()\n\tif p := state.NegotiatedProtocol; p != http2.NextProtoTLS {\n\t\treturn nil, fmt.Errorf(\"http2: unexpected ALPN protocol %q; want %q\", p, http2.NextProtoTLS)\n\t}\n\n\tif !state.NegotiatedProtocolIsMutual {\n\t\treturn nil, fmt.Errorf(\"http2: could not negotiate protocol mutually\")\n\t}\n\n\treturn tlsConn, nil\n}", "func setupBatchTCPTest(logf logger.Logf, traf *TrafficGen) {\n\tsl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tlog.Fatalf(\"listen: %v\", err)\n\t}\n\n\tvar slCloseOnce sync.Once\n\tslClose := func() {\n\t\tslCloseOnce.Do(func() {\n\t\t\tsl.Close()\n\t\t})\n\t}\n\n\ts1, err := net.Dial(\"tcp\", sl.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"dial: %v\", err)\n\t}\n\n\ts2, err := sl.Accept()\n\tif err != nil {\n\t\tlog.Fatalf(\"accept: %v\", err)\n\t}\n\n\ts1.(*net.TCPConn).SetWriteBuffer(1024 * 1024)\n\ts2.(*net.TCPConn).SetReadBuffer(1024 * 1024)\n\n\tch := make(chan int)\n\n\tgo func() {\n\t\t// transmitter\n\t\tdefer slClose()\n\t\tdefer s1.Close()\n\n\t\tbs1 := bufio.NewWriterSize(s1, 1024*1024)\n\n\t\tb := make([]byte, 1600)\n\t\ti := 0\n\t\tfor {\n\t\t\ti += 1\n\t\t\tn := traf.Generate(b, 16)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i == 1 {\n\t\t\t\tch <- n\n\t\t\t}\n\t\t\tbs1.Write(b[16 : n+16])\n\n\t\t\t// TODO: this is a pretty half-baked batching\n\t\t\t// function, which we'd never want to employ in\n\t\t\t// a real-life program.\n\t\t\t//\n\t\t\t// In real life, we'd probably want to flush\n\t\t\t// immediately when there are no more packets to\n\t\t\t// generate, and queue up only if we fall behind.\n\t\t\t//\n\t\t\t// In our case however, we just want to see the\n\t\t\t// technical benefits of batching 10 syscalls\n\t\t\t// into 1, so a fixed ratio makes more sense.\n\t\t\tif (i % 10) == 0 {\n\t\t\t\tbs1.Flush()\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// receiver\n\t\tdefer slClose()\n\t\tdefer s2.Close()\n\n\t\tbs2 := bufio.NewReaderSize(s2, 1024*1024)\n\n\t\t// Find out the packet size (we happen to know they're\n\t\t// all the same size)\n\t\tpacketSize := <-ch\n\n\t\tb := make([]byte, packetSize)\n\t\tfor traf.Running() {\n\t\t\t// TODO: can't use ReadFrom() here, which is\n\t\t\t// unfair compared to UDP. (ReadFrom for UDP\n\t\t\t// apparently allocates memory per packet, which\n\t\t\t// this test does not.)\n\t\t\tn, err := io.ReadFull(bs2, b)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"s2.Read: %v\", err)\n\t\t\t}\n\t\t\ttraf.GotPacket(b[:n], 0)\n\t\t}\n\t}()\n}", "func TestProbeHTTPSTimeout(t *testing.T) {\n\tserver, _, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Fprintln(w, \"Hello world\")\n\t})\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err == nil {\n\t\tt.Fatalf(\"Expected error but returned error was nil\")\n\t}\n}", "func (ts *TcpServer) StartTlsServer(port string) (err error) {\n\n\tbelogs.Debug(\"StartTlsServer(): tlsserver port:\", port)\n\tcert, err := tls.LoadX509KeyPair(ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver LoadX509KeyPair fail: port:\", port,\n\t\t\t\" tlsPublicCrtFileName, tlsPrivateKeyFileName:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver cert:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\n\trootCrtBytes, err := ioutil.ReadFile(ts.tlsRootCrtFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver ReadFile tlsRootCrtFileName fail, port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\trootCertPool := x509.NewCertPool()\n\tok := rootCertPool.AppendCertsFromPEM(rootCrtBytes)\n\tif !ok {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver AppendCertsFromPEM tlsRootCrtFileName fail,port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, \" len(rootCrtBytes):\", len(rootCrtBytes), err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver AppendCertsFromPEM len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\tclientAuthType := tls.NoClientCert\n\tif ts.tlsVerifyClient {\n\t\tclientAuthType = tls.RequireAndVerifyClientCert\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver clientAuthType:\", clientAuthType)\n\n\t// https://stackoverflow.com/questions/63676241/how-to-set-setkeepaliveperiod-on-a-tls-conn\n\tsetTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t// Check that the underlying connection really is TCP.\n\t\tif tcpConn, ok := clientHello.Conn.(*net.TCPConn); ok {\n\t\t\ttcpConn.SetKeepAlive(true)\n\t\t\ttcpConn.SetKeepAlivePeriod(time.Second * 300)\n\t\t\tbelogs.Debug(\"StartTlsServer(): tlsserver SetKeepAlive:\")\n\t\t}\n\t\t// Make sure to return nil, nil to let the caller fall back on the default behavior.\n\t\treturn nil, nil\n\t}\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: clientAuthType,\n\t\tRootCAs: rootCertPool,\n\t\tInsecureSkipVerify: false,\n\t\tGetConfigForClient: setTCPKeepAlive,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver Listen fail, port:\", port, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): Listen ok, port:\", port)\n\n\t// get tcpListener\n\tts.tcpListener, err = NewFromTlsListener(listener)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver NewFromTlsListener fail, port: \", port, err)\n\t\treturn err\n\t}\n\tbelogs.Info(\"StartTlsServer(): tlsserver create server ok, port:\", port, \" will accept client\")\n\n\tgo ts.waitBusinessToConnMsg()\n\n\t// wait new conn\n\tts.acceptNewConn()\n\treturn nil\n}", "func doTLS(address string, port string, tcpDialTimeout time.Duration, tlsHandshakeTimeout time.Duration,\n) (*TLSInfo, error) {\n\tvar tlsInfo TLSInfo\n\n\tcfg := constructTLSConfig()\n\n\t// Create a TCP connection to the target address\n\tdailAddress := address\n\tif port != \"\" {\n\t\tdailAddress += \":\" + port\n\t} else {\n\t\tdailAddress += \":443\"\n\t}\n\tconn, err := net.DialTimeout(\"tcp\", dailAddress, tcpDialTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsClient := tls.Client(conn, cfg)\n\n\t// Taken from http.transport.go:persistConn.addTLS\n\terrChannel := make(chan error, 2)\n\tvar timer *time.Timer // for canceling TLS handshake\n\n\t// Create a timer to allow the tls handshake to timeout if tlsHandshakeTimeout is greater than 0\n\tif tlsHandshakeTimeout != 0 {\n\t\ttimer = time.AfterFunc(tlsHandshakeTimeout, func() {\n\t\t\terrChannel <- tlsHandshakeTimeoutError{}\n\t\t})\n\t}\n\n\t// Use the timer to enforce a timeout if tlsHandshakeTimeout is greater than 0\n\tgo func() {\n\t\terr := tlsClient.Handshake()\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t\terrChannel <- err\n\t}()\n\n\t// A TLS error occurred\n\tif tlsHandshakeErr := <-errChannel; tlsHandshakeErr != nil {\n\t\treturn nil, tlsHandshakeErr\n\t}\n\tdefer func(tlsClient *tls.Conn) {\n\t\terr := tlsClient.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error closing TLS connection for address \" + address + \": \" + err.Error())\n\t\t}\n\t}(tlsClient)\n\tconnState := tlsClient.ConnectionState()\n\n\t// Populate a TLSInfo and return it\n\ttlsInfo = TLSInfo{\n\t\tServerName: cfg.ServerName,\n\t\tAddress: address,\n\t\tVersion: connState.Version,\n\t\tCipherSuite: connState.CipherSuite,\n\t\tNegotiatedProtocol: connState.NegotiatedProtocol,\n\t\tPeerCertificates: connState.PeerCertificates,\n\t\tOCSPResponse: connState.OCSPResponse,\n\t}\n\treturn &tlsInfo, nil\n}", "func TestServerTLS(t *testing.T) {\n\tca1 := newSelfSignedCA(t)\n\tca2 := newSelfSignedCA(t)\n\n\t// trusted certificates with proxy roles.\n\tclient1 := setupClient(t, ca1, ca1, types.RoleProxy)\n\t_, serverDef1 := setupServer(t, \"s1\", ca1, ca1, types.RoleProxy)\n\terr := client1.updateConnections([]types.Server{serverDef1})\n\trequire.NoError(t, err)\n\tstream, _, err := client1.dial([]string{\"s1\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n\n\t// trusted certificates with incorrect server role.\n\tclient2 := setupClient(t, ca1, ca1, types.RoleNode)\n\t_, serverDef2 := setupServer(t, \"s2\", ca1, ca1, types.RoleProxy)\n\terr = client2.updateConnections([]types.Server{serverDef2})\n\trequire.NoError(t, err) // connection succeeds but is in transient failure state\n\t_, _, err = client2.dial([]string{\"s2\"}, &proto.DialRequest{})\n\trequire.Error(t, err)\n\n\t// certificates with correct role from different CAs\n\tclient3 := setupClient(t, ca1, ca2, types.RoleProxy)\n\t_, serverDef3 := setupServer(t, \"s3\", ca2, ca1, types.RoleProxy)\n\terr = client3.updateConnections([]types.Server{serverDef3})\n\trequire.NoError(t, err)\n\tstream, _, err = client3.dial([]string{\"s3\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n}", "func (s *Server) RunTLS(addr string, certPairs []CertPair) error {\n\tcfg := tls.Config{RootCAs: x509.NewCertPool()}\n\tcfg.Certificates = make([]tls.Certificate, 0, len(certPairs))\n\n\tfor _, cp := range certPairs {\n\t\tcert, err := tls.LoadX509KeyPair(cp.CertFile, cp.KeyFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: %v\", cp.CertFile, err)\n\t\t}\n\t\tcfg.Certificates = append(cfg.Certificates, cert)\n\t}\n\n\tcfg.BuildNameToCertificate()\n\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrv := s.newHTTPServer(ln.Addr().String())\n\tsrv.TLSConfig = &cfg\n\n\ts.serversMux.Lock()\n\ts.servers = append(s.servers, srv)\n\ts.serversMux.Unlock()\n\n\tif s.opts.KeepAlivePeriod == -1 {\n\t\treturn srv.ServeTLS(ln, \"\", \"\")\n\t}\n\n\treturn srv.ServeTLS(&tcpKeepAliveListener{ln.(*net.TCPListener), s.opts.KeepAlivePeriod}, \"\", \"\")\n}", "func BenchmarkDialTCP(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tDialTCP(TEST_HOST, TEST_USER, TEST_PASSWD, TEST_DBNAME)\n\t}\n}", "func main() {\n\tstartBenchmark := time.Now()\n\tnc, err := nats.Connect(nats.DefaultURL)\n\tL.PanicIf(err, `nats.Connect`)\n\tjs, err := nc.JetStream(nats.PublishAsyncMaxPending(256))\n\tL.PanicIf(err, `nc.JetStream`)\n\tdefer nc.Close()\n\n\t// create stream\n\tstream, err := js.StreamInfo(TOPIC)\n\tL.IsError(err, `js.StreamInfo`)\n\tif stream == nil {\n\t\tlog.Printf(\"creating stream %q and subjects %q\", TOPIC, TOPIC)\n\t\t_, err = js.AddStream(&nats.StreamConfig{\n\t\t\tName: TOPIC,\n\t\t\tSubjects: []string{TOPIC},\n\t\t})\n\t\tL.IsError(err, `js.AddStream`)\n\t}\n\n\twgConsume := &sync.WaitGroup{}\n\twgConsume.Add(PRODUCERS * MSGS) // includes consuming\n\tfailConsume := int64(0)\n\tdoubleConsume := int64(0)\n\tdurConsume := int64(0)\n\tmaxLatency := int64(0)\n\tconsumed := int64(0)\n\tconsume := sync.Map{}\n\n\tgo func() {\n\t\tfor z := 0; z < CONSUMERS; z++ {\n\t\t\tgo func(z int) {\n\t\t\t\tnc, err := nats.Connect(nats.DefaultURL)\n\t\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\t\tjs, err := nc.JetStream()\n\t\t\t\tL.PanicIf(err, `nc.JetStream`)\n\t\t\t\t//defer nc.Close() // don't close or it will not consume\n\t\t\t\t//fmt.Println(`Consumer spawned`, z)\n\t\t\t\t_, err = js.QueueSubscribe(TOPIC, ``, func(msg *nats.Msg) {\n\t\t\t\t\t//atomic.AddInt64(&failConsume, int64(len(errs)))\n\t\t\t\t\t//L.Print(errs)\n\t\t\t\t\tm := M.SX{}\n\t\t\t\t\terr := json.Unmarshal(msg.Data, &m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tatomic.AddInt64(&failConsume, 1)\n\t\t\t\t\t\tL.Print(err)\n\t\t\t\t\t}\n\t\t\t\t\tif _, exists := consume.LoadOrStore(m.GetInt(`idx`), struct{}{}); !exists {\n\t\t\t\t\t\tdur := time.Now().UnixNano() - m.GetInt(`when`)\n\t\t\t\t\t\tatomic.AddInt64(&durConsume, dur) // bottleneck, TODO: change to channel\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\told := maxLatency\n\t\t\t\t\t\t\tif dur <= old {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif atomic.CompareAndSwapInt64(&maxLatency, old, dur) {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif atomic.AddInt64(&consumed, 1)%PROGRESS == 0 {\n\t\t\t\t\t\t\tfmt.Print(\"C\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_ = msg.Ack()\n\t\t\t\t\t\twgConsume.Done()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tatomic.AddInt64(&doubleConsume, 1)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tL.PanicIf(err, `js.Subscribe %d`, z)\n\t\t\t}(z)\n\t\t}\n\t}()\n\n\twgProduce := &sync.WaitGroup{}\n\twgProduce.Add(PRODUCERS * MSGS)\n\tfailProduce := int64(0)\n\tdurProduce := int64(0)\n\tproduced := int64(0)\n\n\tstartProduce := time.Now().UnixNano()\n\tfor z := 0; z < PRODUCERS; z++ {\n\t\tgo func(z int) {\n\t\t\t// multiple producers works fast\n\t\t\tnc, err := nats.Connect(nats.DefaultURL)\n\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\tjs, err := nc.JetStream()\n\t\t\tL.PanicIf(err, `nc.JetStream`)\n\t\t\t_, _ = js.AddStream(&nats.StreamConfig{\n\t\t\t\tName: TOPIC,\n\t\t\t\tSubjects: []string{TOPIC},\n\t\t\t\tReplicas: 1,\n\t\t\t})\n\t\t\tdefer nc.Close()\n\t\t\t//fmt.Println(`Producer spawned`, z)\n\t\t\tfor y := 0; y < MSGS; y++ {\n\t\t\t\t_, err := js.Publish(TOPIC, []byte(M.SX{\n\t\t\t\t\t`when`: time.Now().UnixNano(),\n\t\t\t\t\t`idx`: z*MSGS + y,\n\t\t\t\t}.ToJson()))\n\t\t\t\tif err != nil {\n\t\t\t\t\tatomic.AddInt64(&failProduce, 1)\n\t\t\t\t\tL.Print(err, z)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twgProduce.Done()\n\t\t\t\tif atomic.AddInt64(&produced, 1)%PROGRESS == 0 {\n\t\t\t\t\tfmt.Print(\"P\")\n\t\t\t\t}\n\t\t\t}\n\t\t}(z)\n\t}\n\n\twgProduce.Wait()\n\tdurProduce = time.Now().UnixNano() - startProduce\n\twgConsume.Wait()\n\n\tfmt.Println(`FailProduce: `, failProduce)\n\tfmt.Println(`FailConsume: `, failConsume)\n\tfmt.Println(`DoubleConsume: `, doubleConsume)\n\tfmt.Println(`Produced (ms): `, durProduce/1000/1000)\n\tfmt.Println(`MaxLatency (ms): `, maxLatency/1000/1000)\n\tfmt.Println(`AvgLatency (ms): `, durConsume/PRODUCERS/MSGS/1000/1000)\n\tfmt.Println(`Total (s)`, time.Since(startBenchmark))\n}", "func TestXUpdateTLS_NoneToTLS(t *testing.T) {\n\tappaddr := \"127.0.0.1:8080\"\n\ttestCases := []*XExtendTLSUpdateCase{\n\t\tNewXExtendTLSUpdateCase(t, bolt.ProtocolName, util.NewRPCServer(t, appaddr, bolt.ProtocolName)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(false)\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tt.Logf(\"verify non-tls\")\n\t\tverify()\n\t\t// update to tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{DefaultTLSConfig}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tt.Logf(\"verify tls\")\n\t\tverify()\n\t\ttc.FinishCase()\n\n\t}\n}", "func handlePacket(packet gopacket.Packet) {\n\t// Get the TCP layer from this packet\n\tif tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {\n\t\ttcp, _ := tcpLayer.(*layers.TCP)\n\t\tpayload := tcp.BaseLayer.Payload\n\n\t\t/*\n\t\t * We are searching for a TLS record header\n\t\t * (http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session)\n\t\t * First byte: 0x16 for ALLPLICATION_DATA\n\t\t * Two consecutive bytes: 0x0303 for TLS 1.2\n\t\t */\n\n\t\t// Payload must be bigger than 5 bytes (TLS header is 5 bytes)\n\t\tif len(payload) >= 5 {\n\t\t\t// Make sure we have a TLS record here.\n\t\t\tif payload[0] == tlsRecordHandshake {\n\t\t\t\t// See if message type in handshake layer is TLSRecordHandshakeClientHello\n\t\t\t\tTLSRecordHandshakeMessageType := payload[5]\n\n\t\t\t\t/*\n\t\t\t\t * If TLS handshake HELLO is CLIENT_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeClientHello {\n\t\t\t\t\t// TLS version in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11]) // Catch two bytes and interpret as single number (0xXXXX)\n\n\t\t\t\t\ttlsVersionsClients[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Get ciphers\n\t\t\t\t\t */\n\n\t\t\t\t\t// After payload byte 43 there is session ID length and session ID\n\t\t\t\t\t// In most cases session ID length is 0x00, so there is no session ID byte.\n\t\t\t\t\t// Check the length of the session ID and contunie from there\n\t\t\t\t\t// After the session ID length and session ID bytes, the cipher part starts\n\t\t\t\t\t// Anatomy of th CLIENT_HELLO handshake message:\n\t\t\t\t\t// \t<TLS VERSION 2B> | <RANDOM 32B> | <SESS ID LENGTH 1B> | <SESS ID 0..nB> | <CIPHER SUITES LEN 2B> | <CIPHER 1 2B> | CIPHER 2 2B> | ...\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\tCiphersLengthBytes := binary.BigEndian.Uint16(payload[cipherSuitesStart : cipherSuitesStart+2])\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\tvar i uint16\n\t\t\t\t\tfor i = 0; i < CiphersLengthBytes; i += 2 {\n\t\t\t\t\t\tcipherpos := cipherSuitesStart + 2 + byte(i)\n\t\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\t\tciphersClients[cipher]++ // Increment counter for this cipher\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * If TLS Handshake HELLO is SERVER_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeServerHello {\n\t\t\t\t\t// TLS in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11])\n\n\t\t\t\t\ttlsVersionsServers[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\t// (Not needed for server part, because only one cipher is suggested by server)\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\t// (no walking needed, because there is only one cipher suggested)\n\t\t\t\t\tcipherpos := cipherSuitesStart\n\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\tciphersServers[cipher]++ // Increment counter for this cipher\n\n\t\t\t\t}\n\t\t\t} else if payload[0] == tlsRecordAlert {\n\t\t\t\t/*\n\t\t\t\t * If there is an alert message\n\t\t\t\t * Search for any Handshake failures\n\t\t\t\t */\n\t\t\t\ttlsAlertLength := binary.BigEndian.Uint16(payload[3:5])\n\t\t\t\t// Alerts need to have length 2 bytes\n\t\t\t\tif tlsAlertLength == 2 {\n\t\t\t\t\ttlsAlertDescription := payload[6]\n\t\t\t\t\talerts[uint16(tlsAlertDescription)]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) ServeTLS(ctx context.Context, ln net.Listener) error {\n\tln = tls.NewListener(ln, s.TLSConfig.Clone())\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgo func(conn net.Conn) {\n\t\t\tif err := conn.(*tls.Conn).Handshake(); err != nil {\n\t\t\t\ts.logf(\"dns handshake: %s\", err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.serveStream(ctx, conn)\n\t\t}(conn)\n\t}\n}", "func tls() {\n\t// init server w/ ctrl+c support\n\tvar s = webfmwk.InitServer(webfmwk.WithCtrlC())\n\n\t// expose /test\n\ts.GET(\"/test\", func(c webfmwk.Context) error {\n\t\treturn c.JSONOk(\"ok\")\n\t})\n\n\t// start asynchronously on :4242\n\ts.StartTLS(\":4242\", webfmwk.TLSConfig{\n\t\tCert: \"/path/to/cert\",\n\t\tKey: \"/path/to/key\",\n\t\tInsecure: false,\n\t})\n\n\t// ctrl+c is handled internaly\n\tdefer s.WaitAndStop()\n}", "func newTLSServer(handler http.Handler) *httptest.Server {\n\tts := httptest.NewUnstartedServer(handler)\n\tts.TLS = new(tls.Config)\n\tts.TLS.NextProtos = []string{\"h2\"}\n\tts.StartTLS()\n\treturn ts\n}", "func sendTcpTlsMsmtStopRequest(addr string, port int, callSize int) {\n\ttcpObj := clientProtos.NewTcpObj(\"TcpTlsMsmtStopReqConn\", addr, port, callSize)\n\n\treqDataObj := new(shared.DataObj)\n\treqDataObj.Type = shared.MEASUREMENT_STOP_REQUEST\n\n\tif val, ok := idStorage[\"host-uuid\"]; ok {\n\t\treqDataObj.Id = val\n\t} else {\n\t\tfmt.Println(\"\\nFound not the id\")\n\t}\n\n\tseqNo++\n\treqDataObj.Seq = strconv.FormatUint(seqNo, 10)\n\treqDataObj.Secret = \"fancySecret\"\n\n\tif val, ok := msmtIdStorage[\"tcp-tls-throughput1\"]; ok {\n\t\treqDataObj.Measurement_id = val\n\t} else {\n\t\tfmt.Println(\"\\nFound not the measurement id for tcp tls throughput\")\n\t}\n\n\treqJson := shared.ConvDataStructToJson(reqDataObj)\n\t// debug fmt.Printf(\"\\nmsmt stop request JSON is: % s\", reqJson)\n\n\tmsmtStopRep := tcpObj.StopMeasurement(reqJson)\n\tprepareOutput(msmtStopRep)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) (err error) {\n\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{http2NextProtoTLS, http2Rev14, http11},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\n\ttlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\tl, err := kmsnet.NewTCPListenerNoShutdown(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(l, tlsConfig)\n\n\ts := &http.Server{Addr: tlsListener.Addr().String(), Handler: handler, TLSConfig: tlsConfig}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: tlsListener,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func (c *TLSUpdateCase) RequestTLS(isTLS bool, n int, interval int) {\n\tvar call func() error\n\tswitch c.Protocol {\n\tcase protocol.HTTP1:\n\t\ttr := http.DefaultTransport.(*http.Transport)\n\t\tpool := x509.NewCertPool()\n\t\tpool.AppendCertsFromPEM([]byte(caPEM))\n\t\ttr.TLSClientConfig = &tls.Config{\n\t\t\tRootCAs: pool,\n\t\t}\n\t\thttpClient := http.Client{\n\t\t\tTransport: tr,\n\t\t}\n\t\tcall = func() error {\n\t\t\tscheme := \"http://\"\n\t\t\tif isTLS {\n\t\t\t\tscheme = \"https://\"\n\t\t\t}\n\t\t\tresp, err := httpClient.Get(fmt.Sprintf(\"%s%s/\", scheme, c.MeshAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"response status: %d\", resp.StatusCode)\n\t\t\t}\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.T.Logf(\"HTTP client receive data: %s\\n\", string(b))\n\t\t\treturn nil\n\t\t}\n\tcase protocol.HTTP2:\n\t\tvar httpClient http.Client\n\t\tif !isTLS {\n\t\t\ttr := &http2.Transport{\n\t\t\t\tAllowHTTP: true,\n\t\t\t\tDialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {\n\t\t\t\t\treturn net.Dial(netw, addr)\n\t\t\t\t},\n\t\t\t}\n\t\t\thttpClient = http.Client{Transport: tr}\n\n\t\t} else {\n\t\t\tpool := x509.NewCertPool()\n\t\t\tpool.AppendCertsFromPEM([]byte(caPEM))\n\t\t\thttpClient = http.Client{\n\t\t\t\tTransport: &http2.Transport{\n\t\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\t\tRootCAs: pool,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tcall = func() error {\n\t\t\tscheme := \"http://\"\n\t\t\tif isTLS {\n\t\t\t\tscheme = \"https://\"\n\t\t\t}\n\t\t\tresp, err := httpClient.Get(fmt.Sprintf(\"%s%s/\", scheme, c.MeshAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"response status: %d\", resp.StatusCode)\n\n\t\t\t}\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.T.Logf(\"HTTP2 client receive data: %s\\n\", string(b))\n\t\t\treturn nil\n\t\t}\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tif err := call(); err != nil {\n\t\t\tc.C <- err\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Duration(interval) * time.Millisecond)\n\t}\n\tc.C <- nil\n}", "func main() {\n\n\tst := time.Now()\n\n\tll.Printf(\"%stag:%s connsess:%s starts\\n\",\n\t\texampid, tag, sngecomm.Lcs)\n\n\t// TLS Configuration.\n\ttc = new(tls.Config)\n\ttc.InsecureSkipVerify = true // Do *not* check the server's certificate\n\n\t// Usually one will use the default cipher suites that go provides.\n\t// However, if a custom cipher squite list is needed/required this\n\t// is how it is accomplished.\n\tif sngecomm.UseCustomCiphers() { // Set custom cipher suite list\n\t\ttc.CipherSuites = append(tc.CipherSuites, sngecomm.CustomCiphers()...)\n\t}\n\n\t// Standard example TLS connect sequence\n\tn, conn, e := sngecomm.CommonTLSConnect(exampid, tag, ll, tc)\n\tif e != nil {\n\t\tll.Fatalf(\"%stag:%s connsess:%s main_on_connect error:%v\",\n\t\t\texampid, tag, sngecomm.Lcs,\n\t\t\te.Error()) // Handle this ......\n\t}\n\n\tnc := n.(*tls.Conn)\n\tsngecomm.DumpTLSConfig(exampid, tc, nc)\n\n\t// *NOTE* application specific functionaltiy starts here!\n\t// For you to add.\n\t// *NOTE* application specific functionaltiy ends here!\n\n\t// Standard example disconnect sequence\n\te = sngecomm.CommonDisconnect(n, conn, exampid, tag, ll)\n\tif e != nil {\n\t\tll.Fatalf(\"%s %s\\n\", exampid, e.Error()) // Handle this ......\n\t}\n\n\tll.Printf(\"%stag:%s connsess:%s main_elapsed:%v\\n\",\n\t\texampid, tag, conn.Session(),\n\t\ttime.Now().Sub(st))\n\n}", "func GenericTLSWrap(conn *net.TCPConn, cfg *tls.Config, tFunc TLSWrapperFunc) (*tls.Conn, error) {\n\tvar tConn *tls.Conn\n\n\ttCfg := cfg.Clone()\n\ttCfg.MinVersion = tls.VersionTLS12\n\n\tfor {\n\t\tif err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttConn = tFunc(conn, tCfg)\n\n\t\t// check if the connection is upgraded before returning\n\t\t// we want to catch the error early\n\t\tif err := tConn.Handshake(); err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\t\tif netErr.Timeout() || netErr.Temporary() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := conn.SetDeadline(time.Time{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\t}\n\n\treturn tConn, nil\n}", "func TestNewKeepAliveListener(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected listen error: %v\", err)\n\t}\n\n\tln, err = NewKeepAliveListener(ln, \"http\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"http://\" + ln.Addr().String())\n\tconn, err := ln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*keepAliveConn); !ok {\n\t\tt.Fatalf(\"Unexpected conn type: %T, wanted *keepAliveConn\", conn)\n\t}\n\tconn.Close()\n\tln.Close()\n\n\tln, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Listen error: %v\", err)\n\t}\n\n\t// tls\n\ttlsinfo, err := createSelfCert(t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create tmpfile: %v\", err)\n\t}\n\ttlsInfo := TLSInfo{CertFile: tlsinfo.CertFile, KeyFile: tlsinfo.KeyFile}\n\ttlsInfo.parseFunc = fakeCertificateParserFunc(tls.Certificate{}, nil)\n\ttlscfg, err := tlsInfo.ServerConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected serverConfig error: %v\", err)\n\t}\n\ttlsln, err := NewKeepAliveListener(ln, \"https\", tlscfg)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"https://\" + tlsln.Addr().String())\n\tconn, err = tlsln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*tls.Conn); !ok {\n\t\tt.Errorf(\"failed to accept *tls.Conn\")\n\t}\n\tconn.Close()\n\ttlsln.Close()\n}", "func TestXUpdateTLS_TLSToNone(t *testing.T) {\n\tappaddr := \"127.0.0.1:8080\"\n\ttestCases := []*XExtendTLSUpdateCase{\n\t\tNewXExtendTLSUpdateCase(t, bolt.ProtocolName, util.NewRPCServer(t, appaddr, bolt.ProtocolName)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(true)\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tverify()\n\t\t// update to non-tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{v2.TLSConfig{}}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tverify()\n\t\t// finish\n\t\ttc.FinishCase()\n\t}\n\n}", "func TestNATSServer_Cluster_TLS(t *testing.T) {\n\tconst CONN_COUNT = 3\n\tconfigs := createNATSServerConfigsWithTLS(CONN_COUNT)\n\tservers := createNATSServers(t, configs)\n\tstartServers(servers)\n\tdefer shutdownServers(servers)\n\tlogNATServerInfo(servers, \"Servers have been started\")\n\tif err := waitforClusterMeshToForm(servers); err != nil {\n\t\tt.Fatalf(\"Full mesh did not form : %v\", err)\n\t}\n\n\tfor i, server := range servers {\n\t\tif server.Cluster() != configs[i].Cluster {\n\t\t\tt.Errorf(\"Cluster name does not match : %s != %s\", server.Cluster(), configs[i].Cluster)\n\t\t}\n\t}\n\n\t// connect to each server\n\t// create a subscription on each server\n\t// create a queue subscription on each server\n\tconst TOPIC = \"TestNewNATSServer\"\n\tconst QUEUE = \"TestNewNATSServer\"\n\tvar subscriptions []messaging.Subscription\n\tvar qsubscriptions []messaging.QueueSubscription\n\tvar conns []*opnats.ManagedConn\n\tfor _, config := range configs {\n\t\tconn, err := nats.Connect(fmt.Sprintf(\"tls://localhost:%d\", config.ServerPort), nats.Secure(clientTLSConfig()))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to connect : %v\", err)\n\t\t}\n\n\t\tmanagedConn := opnats.NewManagedConn(config.Cluster, fmt.Sprintf(\"%s:%d\", config.Cluster, config.ServerPort), conn, nil)\n\t\tconns = append(conns, managedConn)\n\t\tsub, err := managedConn.TopicSubscribe(TOPIC, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tsubscriptions = append(subscriptions, sub)\n\n\t\tqsub, err := managedConn.TopicQueueSubscribe(TOPIC, QUEUE, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create queue subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tqsubscriptions = append(qsubscriptions, qsub)\n\n\t\tlogNATServerInfo(servers, fmt.Sprintf(\"created subscription on %d\", config.ServerPort))\n\t}\n\tlogNATServerInfo(servers, \"Connected to each server and created a subsription on each server\")\n\tif err := checkClientConnectionCounts(servers, 1); err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\twaitForClusterToBecomeAwareOfAllSubscriptions(servers, len(qsubscriptions)+len(qsubscriptions))\n\n\t// publish a message on each connection\n\ti := 0\n\tfor _, conn := range conns {\n\t\ti++\n\t\tconn.Publish(TOPIC, []byte(fmt.Sprintf(\"MSG #%d\", i)))\n\t}\n\tlog.Logger.Info().Msg(\"Published messages\")\n\n\tvar (\n\t\tSUBSCRIBER_EXPECTED_MSG_COUNT = (CONN_COUNT * len(subscriptions))\n\t\tQSUBSCRIBER_EXPECTED_MSG_COUNT = len(conns)\n\t)\n\tsubscriberMsgCount := receiveMessagesOnSubscriptions(subscriptions, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\tqsubscriberMsgCount := receiveMessagesOnQueueSubscriptions(qsubscriptions, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\tif subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", subscriberMsgCount, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n\tif qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", qsubscriberMsgCount, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n}", "func TestBigData(t *testing.T) {\n\tclient, server := pair(t)\n\n\tserverReads := sinkReads(server)\n\tclientReads := sinkReads(client)\n\n\tconst sz = 15 * 1024 // 15KiB\n\tclientStr := strings.Repeat(\"abcde\", sz/5)\n\tserverStr := strings.Repeat(\"fghij\", sz/5*2)\n\n\tif _, err := io.WriteString(client, clientStr); err != nil {\n\t\tt.Fatalf(\"writing client>server: %v\", err)\n\t}\n\tif _, err := io.WriteString(server, serverStr); err != nil {\n\t\tt.Fatalf(\"writing server>client: %v\", err)\n\t}\n\n\tif serverGot := serverReads.String(sz); serverGot != clientStr {\n\t\tt.Error(\"server didn't receive what client sent\")\n\t}\n\tif clientGot := clientReads.String(2 * sz); clientGot != serverStr {\n\t\tt.Error(\"client didn't receive what server sent\")\n\t}\n\n\tgetNonce := func(n [chp.NonceSize]byte) uint64 {\n\t\tif binary.BigEndian.Uint32(n[:4]) != 0 {\n\t\t\tpanic(\"unexpected nonce\")\n\t\t}\n\t\treturn binary.BigEndian.Uint64(n[4:])\n\t}\n\n\t// Reach into the Conns and verify the cipher nonces advanced as\n\t// expected.\n\tif getNonce(client.tx.nonce) != getNonce(server.rx.nonce) {\n\t\tt.Error(\"desynchronized client tx nonce\")\n\t}\n\tif getNonce(server.tx.nonce) != getNonce(client.rx.nonce) {\n\t\tt.Error(\"desynchronized server tx nonce\")\n\t}\n\tif n := getNonce(client.tx.nonce); n != 4 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 4\", n)\n\t}\n\tif n := getNonce(server.tx.nonce); n != 8 {\n\t\tt.Errorf(\"wrong client tx nonce, got %d want 8\", n)\n\t}\n}", "func TestListener(t *testing.T) {\n\tlistener := &fakeListener{}\n\tdoh, _ := NewTransport(testURL, ips, nil, nil, listener)\n\ttransport := doh.(*transport)\n\trt := makeTestRoundTripper()\n\ttransport.client.Transport = rt\n\n\tgo func() {\n\t\treq := <-rt.req\n\t\ttrace := httptrace.ContextClientTrace(req.Context())\n\t\ttrace.GotConn(httptrace.GotConnInfo{\n\t\t\tConn: &fakeConn{\n\t\t\t\tremoteAddr: &net.TCPAddr{\n\t\t\t\t\tIP: net.ParseIP(\"192.0.2.2\"),\n\t\t\t\t\tPort: 443,\n\t\t\t\t}}})\n\n\t\tr, w := io.Pipe()\n\t\trt.resp <- &http.Response{\n\t\t\tStatusCode: 200,\n\t\t\tBody: r,\n\t\t\tRequest: &http.Request{URL: parsedURL},\n\t\t}\n\t\tw.Write([]byte{0, 0, 8, 9, 10})\n\t\tw.Close()\n\t}()\n\n\tdoh.Query(simpleQueryBytes)\n\ts := listener.summary\n\tif s.Latency < 0 {\n\t\tt.Errorf(\"Negative latency: %f\", s.Latency)\n\t}\n\tif !bytes.Equal(s.Query, simpleQueryBytes) {\n\t\tt.Errorf(\"Wrong query: %v\", s.Query)\n\t}\n\tif !bytes.Equal(s.Response, []byte{0xbe, 0xef, 8, 9, 10}) {\n\t\tt.Errorf(\"Wrong response: %v\", s.Response)\n\t}\n\tif s.Server != \"192.0.2.2\" {\n\t\tt.Errorf(\"Wrong server IP string: %s\", s.Server)\n\t}\n\tif s.Status != Complete {\n\t\tt.Errorf(\"Wrong status: %d\", s.Status)\n\t}\n}", "func runEchoStream(b *testing.B, chunkCnt, payloadSize int, random bool) {\n\tb.ReportAllocs()\n\tinternal.CallEchoStream(b, ctx, serverAddr, b.N, chunkCnt, payloadSize, random, benchmark.AddStats(b, 16))\n}", "func TestConnectOK(t *testing.T) {\n\tconnectReq := \"CONNECT %s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n\"\n\n\ttestHTTP := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t_, err = conn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestTLS := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t// HTTPS-Tunneled HTTPS\n\t\ttunnConn := tls.Client(conn, &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t})\n\t\ttunnConn.Handshake()\n\n\t\t_, err = tunnConn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(tunnConn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestRoundTrip(t, httpProxyAddr, false, httpOriginServer, testHTTP)\n\ttestRoundTrip(t, tlsProxyAddr, true, httpOriginServer, testHTTP)\n\n\ttestRoundTrip(t, httpProxyAddr, false, tlsOriginServer, testTLS)\n\ttestRoundTrip(t, tlsProxyAddr, true, tlsOriginServer, testTLS)\n}", "func TestDynamicGrpcBackendTLS(t *testing.T) {\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tclientProtocol string\n\t\tmethodOrUrl string\n\t\tmtlsCertFile string\n\t\tuseWrongBackendCert bool\n\t\theader http.Header\n\t\twantResp string\n\t\twantError string\n\t}{\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"http\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantResp: `{\"id\":\"200\",\"theme\":\"Classic\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http2 client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend with mTLS succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ServerCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"HTTP2 client calling gRPCs remote backend through mTLS failed with incorrect client root cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ProxyCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\targs := utils.CommonArgs()\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\ts := env.NewTestEnv(platform.TestDynamicGrpcBackendTLS, platform.GrpcBookstoreRemote)\n\t\t\tdefer s.TearDown(t)\n\t\t\ts.UseWrongBackendCertForDR(tc.useWrongBackendCert)\n\t\t\tif tc.mtlsCertFile != \"\" {\n\t\t\t\ts.SetBackendMTLSCert(tc.mtlsCertFile)\n\t\t\t\targs = append(args, fmt.Sprintf(\"--ssl_backend_client_cert_path=%v\", platform.GetFilePath(platform.TestDataFolder)))\n\t\t\t}\n\n\t\t\tif err := s.Setup(args); err != nil {\n\t\t\t\tt.Fatalf(\"fail to setup test env, %v\", err)\n\t\t\t}\n\t\t\taddr := fmt.Sprintf(\"%v:%v\", platform.GetLoopbackAddress(), s.Ports().ListenerPort)\n\t\t\tresp, err := bsclient.MakeCall(tc.clientProtocol, addr, \"GET\", tc.methodOrUrl, \"\", tc.header)\n\t\t\tif tc.wantError != \"\" && (err == nil || !strings.Contains(err.Error(), tc.wantError)) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %v\", tc.desc, tc.wantError, err)\n\t\t\t}\n\n\t\t\tif tc.wantError == \"\" && err != nil {\n\t\t\t\tt.Errorf(\"Test (%s): got unexpected error: %s\", tc.desc, resp)\n\t\t\t}\n\n\t\t\tif !strings.Contains(resp, tc.wantResp) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %s\", tc.desc, tc.wantResp, resp)\n\t\t\t}\n\t\t})\n\t}\n}", "func BenchmarkTCPConnWithoutPool(b *testing.B) {\n\tb.ReportAllocs()\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr = write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\n\t\t\t\terr = write(conn, \"close\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error closing: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func main() {\n\ttestsize := 10000\n\tt0 := time.Now()\n\tStatePass(testsize)\n\tt1 := time.Now()\n\tfmt.Println(\"StatePass: \", t1.Sub(t0))\n\t\n\tt2 := time.Now()\n\tstream := Stream(testsize)\n\tfor {\n\t\tif _, ok := <- stream; !ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tt3 := time.Now()\t\n\tfmt.Println(\"Stream: \", t3.Sub(t2))\n}", "func startBatchModeServer(ctl chan bool) {\n\tlogger.SetOutput(os.Stderr)\n\tlogger.Info(\"starting batcher...https://test.test.test\")\n\n\t// load endpoints\n\tvar TLSConfig tls.Config\n\tif options.Batch.IsTLSEnabled {\n\t\tTLSConfig = configBatchModeTLS()\n\t\tlogger.Info(\"batcher: TLS + HTTP redirect configuration loaded\")\n\t} else {\n\t\tlogger.Info(\"batcher: HTTP configuration loaded\")\n\t}\n\n\tredirectServer, endpointServer, err := configBatchModeServers(&TLSConfig)\n\tif err != nil {\n\t\tlogger.Error(\"batcher: \", err.Error())\n\t} else {\n\t\tif options.Batch.IsTLSEnabled {\n\t\t\tlogger.Info(\"batcher: TLS + HTTP redirect endpoints configured\")\n\t\t} else {\n\t\t\tlogger.Info(\"batcher: HTTP endpoint configured\")\n\t\t}\n\t}\n\n\t// assign handler\n\tendpointServer.Handler = http.HandlerFunc(BatchModeEndpointRouter)\n\n\tif endpointServer.Handler != nil {\n\t\tlogger.Info(\"batcher: handler attached\")\n\t} else {\n\t\tlogger.Error(\"batcher: handler has experienced an error\")\n\t\treturn\n\t}\n\n\t// start endpoints\n\tif options.Batch.IsTLSEnabled {\n\t\tlogger.Info(\"batcher: starting TLS + HTTP redirect endpoint servers\")\n\n\t\tgo func() {\n\n\t\t\tif err := redirectServer.ListenAndServe(); err != nil {\n\t\t\t\tif err == http.ErrServerClosed {\n\t\t\t\t\tlogger.Debug(\"batcher: HTTP redirect endpoint closed\")\n\t\t\t\t\tlogger.Debug(\"batcher: \", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlogger.Error(\"batcher: HTTP redirector error\")\n\t\t\t\tlogger.Error(\"batcher: \", err.Error())\n\t\t\t}\n\n\t\t}()\n\n\t\tgo func() {\n\n\t\t\tif err := endpointServer.ListenAndServeTLS(options.Batch.TlsCert, options.Batch.TlsKey); err != nil {\n\t\t\t\tif err == http.ErrServerClosed {\n\t\t\t\t\tlogger.Debug(\"batcher: TLS endpoint closed\")\n\t\t\t\t\tlogger.Debug(\"batcher: \", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlogger.Error(\"batcher: TLS endpoint error)\")\n\t\t\t\tlogger.Error(\"batcher: \", err.Error())\n\t\t\t}\n\n\t\t}()\n\n\t} else {\n\n\t\tlogger.Warn(\"batcher: starting HTTP endpoint server [highly recommended you use TLS!]\")\n\t\tgo func() {\n\n\t\t\tif err := endpointServer.ListenAndServe(); err != nil {\n\t\t\t\tif err == http.ErrServerClosed {\n\t\t\t\t\tlogger.Debug(\"batcher: HTTP endpoint closed\")\n\t\t\t\t\tlogger.Debug(\"batcher: \", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlogger.Debug(\"batcher: HTTP endpoint error\")\n\t\t\t\tlogger.Error(\"batcher: \", err.Error())\n\t\t\t}\n\n\t\t}()\n\n\t}\n\n\t// listen for stop signals\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\n\t<-stop\n\n\t// true, exit batchScheduler\n\tctl <- true\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tif err := redirectServer.Shutdown(ctx); err != nil {\n\t\tlogger.Error(\"batcher: HTTP redirect endpoint shutdown error\")\n\t\tlogger.Error(\"batcher: \", err.Error())\n\t}\n\tif err := endpointServer.Shutdown(ctx); err != nil {\n\t\tlogger.Error(\"batcher: TLS/HTTP endpoint error\")\n\t\tlogger.Error(\"batcher: \", err.Error())\n\t}\n\n\tlogger.Println()\n\tlogger.Info(\"batcher: exit..\")\n\treturn\n}", "func Test_Ctx_SendStream(t *testing.T) {\n\tt.Parallel()\n\tapp := New()\n\tctx := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(ctx)\n\n\tctx.SendStream(bytes.NewReader([]byte(\"Don't crash please\")))\n\tutils.AssertEqual(t, \"Don't crash please\", string(ctx.Fasthttp.Response.Body()))\n\n\tctx.SendStream(bytes.NewReader([]byte(\"Don't crash please\")), len([]byte(\"Don't crash please\")))\n\tutils.AssertEqual(t, \"Don't crash please\", string(ctx.Fasthttp.Response.Body()))\n\n\tctx.SendStream(bufio.NewReader(bytes.NewReader([]byte(\"Hello bufio\"))))\n\tutils.AssertEqual(t, \"Hello bufio\", string(ctx.Fasthttp.Response.Body()))\n\n\tfile, err := os.Open(\"./.github/index.html\")\n\tutils.AssertEqual(t, nil, err)\n\tctx.SendStream(bufio.NewReader(file))\n\tutils.AssertEqual(t, true, (ctx.Fasthttp.Response.Header.ContentLength() > 200))\n}", "func connStream(t *testing.T) {\n}", "func TestLatencyTestReal(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping test in short mode.\")\n\t}\n\tserverID := \"16976\"\n\n\tconfig := configuration{\n\t\tServerID: serverID,\n\t\tTimeout: 5,\n\t\t//MaxSeconds: 4.0,\n\t}\n\n\tserver := GetServerByID(serverID)\n\tserver.Configuration = &config\n\n\tlocalAddr := net.TCPAddr{}\n\tsource, _ := net.ResolveTCPAddr(\"tcp\", localAddr.String())\n\n\tspdTest := speedtest{\n\t\tSource: source,\n\t}\n\n\tserver.Speedtest = &spdTest\n\tspdTest.Server = &server\n\n\tLatencyTest(&server)\n\tallResults := server.Results\n\n\tresults := allResults.Latency.Seconds()\n\n\tif results <= 0 {\n\t\tt.Fatalf(\"Error: Expected a positive Latency result, but got: %f, err: %s\", results, allResults.Error)\n\t}\n\tfmt.Printf(\"\\nLatency test results for server %s ... %f\\n\", serverID, results)\n}", "func upgradeTLS(c *v1Conn, line string, hooks EventHooks) (err error) {\n\tif c.tlsConfig == nil {\n\t\terr = c.printfLine(\"%s TLS not supported\", RPL_TLSRejected)\n\t} else {\n\t\terr = c.printfLine(\"%s Continue with TLS Negotiation\", RPL_TLSContinue)\n\t\tif err == nil {\n\t\t\ttconn := tls.Server(c.conn, c.tlsConfig)\n\t\t\terr = tconn.Handshake()\n\t\t\tif err == nil {\n\t\t\t\t// successful tls handshake\n\t\t\t\tc.tlsConn = tconn\n\t\t\t\tc.C = textproto.NewConn(c.tlsConn)\n\t\t\t} else {\n\t\t\t\t// tls failed\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"pkg\": \"nntp-conn\",\n\t\t\t\t\t\"addr\": c.conn.RemoteAddr(),\n\t\t\t\t\t\"state\": c.state,\n\t\t\t\t}).Warn(\"TLS Handshake failed \", err)\n\t\t\t\t// fall back to plaintext\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func TestSmoke(t *testing.T) {\n\ta := assert.New(t)\n\tconst backendCount = 4\n\tconst payloadSize = 4096\n\tconst requestCount = 64\n\tconst requestWorkers = 8\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tbackends := make([]*CharGenServer, backendCount)\n\ttier := config.Tier{\n\t\tDialFailureTimeout: 10 * time.Second,\n\t}\n\tfor i := range backends {\n\t\tvar err error\n\t\tbackends[i], err = startChargen(ctx, payloadSize)\n\t\tif !a.NoError(err) {\n\t\t\treturn\n\t\t}\n\t\ttier.Targets = append(tier.Targets, config.Target{\n\t\t\tHosts: []string{backends[i].Addr.IP.String()},\n\t\t\tPort: backends[i].Addr.Port,\n\t\t\tProto: config.TCP,\n\t\t})\n\t}\n\n\tcfg := &config.Config{\n\t\tFrontends: []config.Frontend{\n\t\t\t{\n\t\t\t\tRebalanceDuration: time.Millisecond,\n\t\t\t\tBackendPool: config.BackendPool{\n\t\t\t\t\t// Disable extra pings so our request counts are correct.\n\t\t\t\t\tLatencyBucket: -1,\n\t\t\t\t\tTiers: []config.Tier{tier},\n\t\t\t\t},\n\t\t\t\tBindAddress: \":13013\",\n\t\t\t\tIdleDuration: time.Minute,\n\t\t\t},\n\t\t},\n\t}\n\tif !a.NoError(cfg.Validate()) {\n\t\treturn\n\t}\n\n\tfe := frontend.Frontend{}\n\tif !a.NoError(fe.Ensure(ctx, cfg)) {\n\t\treturn\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(requestWorkers)\n\tvar remainingRequests = int32(requestCount)\n\tfor i := 0; i < requestWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt32(&remainingRequests, -1) < 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\t\t\t\tif !a.NoError(err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcount, err := io.Copy(ioutil.Discard, conn)\n\t\t\t\t_ = conn.Close()\n\t\t\t\ta.NoError(err)\n\t\t\t\ta.Equal(payloadSize, int(count))\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\tfe.Wait()\n\n\t// Ensure that the total number of requests was made.\n\tcount := uint64(0)\n\tfor _, cg := range backends {\n\t\tcount += cg.ConnectionCount()\n\t}\n\ta.Equal(requestCount, int(count))\n\n\tdata, err := yaml.Marshal(&fe)\n\ta.NoError(err)\n\tlog.Print(string(data))\n\n\t// Test tearing down a frontend.\n\tcfg.Frontends = []config.Frontend{}\n\ta.NoError(fe.Ensure(ctx, cfg))\n\t_, err = net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\ta.Errorf(err, \"connection refused\")\n}", "func streamMultiNonReuseConn(opts []grpc.DialOption) {\n\tfor i := 0; i < 10; i++ {\n\t\tfunc() {\n\t\t\tconn := conn(opts)\n\t\t\tdefer closerClose(conn)\n\t\t\tclient := pb.NewRouteGuideClient(conn)\n\t\t\t// Looking for a valid feature\n\t\t\tprintFeatures(client, &pb.Rectangle{\n\t\t\t\tLo: &pb.Point{Latitude: 400000000, Longitude: -750000000},\n\t\t\t\tHi: &pb.Point{Latitude: 420000000, Longitude: -730000000},\n\t\t\t})\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}()\n\t}\n}", "func (self *Proxy) StartTLS(cert string, key string) error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTPs client request at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServeTLS(cert, key)\n}", "func TestPerConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tserver1, server2 := startAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// setting bandwidth limit per connection\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 2\n\tserver1.conn.SetReadCPS(reqSpeed1)\n\treqSpeed2 := reqSpeedC / 3\n\tserver2.conn.SetReadCPS(reqSpeed2)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error {\n\tselect {\n\tcase <-s.ctx.Done():\n\t\treturn ContextErr(s.ctx.Err())\n\tcase <-t.ctx.Done():\n\t\treturn ErrConnClosing\n\tdefault:\n\t}\n\n\tif hdr == nil && data == nil && opts.Last {\n\n\t\tt.controlBuf.put(&dataFrame{streamID: s.id, endStream: true, f: func() {}})\n\t\treturn nil\n\t}\n\n\temptyLen := http2MaxFrameLen - len(hdr)\n\tif emptyLen > len(data) {\n\t\temptyLen = len(data)\n\t}\n\thdr = append(hdr, data[:emptyLen]...)\n\tdata = data[emptyLen:]\n\tvar (\n\t\tstreamQuota int\n\t\tstreamQuotaVer uint32\n\t\terr error\n\t)\n\tfor idx, r := range [][]byte{hdr, data} {\n\t\tfor len(r) > 0 {\n\t\t\tsize := http2MaxFrameLen\n\t\t\tif size > len(r) {\n\t\t\t\tsize = len(r)\n\t\t\t}\n\t\t\tif streamQuota == 0 { // Used up all the locally cached stream quota.\n\n\t\t\t\tstreamQuota, streamQuotaVer, err = s.sendQuotaPool.get(math.MaxInt32, s.waiters)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif size > streamQuota {\n\t\t\t\tsize = streamQuota\n\t\t\t}\n\n\t\t\ttq, _, err := t.sendQuotaPool.get(size, s.waiters)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif tq < size {\n\t\t\t\tsize = tq\n\t\t\t}\n\t\t\tltq, _, err := t.localSendQuota.get(size, s.waiters)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tstreamQuota -= size\n\t\t\tp := r[:size]\n\t\t\tvar endStream bool\n\n\t\t\tif opts.Last {\n\t\t\t\tif len(r)-size == 0 { // No more data in r after this iteration.\n\t\t\t\t\tif idx == 0 { // We're writing data header.\n\t\t\t\t\t\tif len(data) == 0 { // There's no data to follow.\n\t\t\t\t\t\t\tendStream = true\n\t\t\t\t\t\t}\n\t\t\t\t\t} else { // We're writing data.\n\t\t\t\t\t\tendStream = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuccess := func() {\n\t\t\t\tltq := ltq\n\t\t\t\tt.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { t.localSendQuota.add(ltq) }})\n\t\t\t\tr = r[size:]\n\t\t\t}\n\t\t\tfailure := func() { // The stream quota version must have changed.\n\n\t\t\t\ts.sendQuotaPool.lockedAdd(streamQuota + size)\n\t\t\t}\n\t\t\tif !s.sendQuotaPool.compareAndExecute(streamQuotaVer, success, failure) {\n\n\t\t\t\tt.sendQuotaPool.add(size)\n\t\t\t\tt.localSendQuota.add(ltq)\n\t\t\t\tstreamQuota = 0\n\t\t\t}\n\t\t}\n\t}\n\tif streamQuota > 0 { // Add the left over quota back to stream.\n\t\ts.sendQuotaPool.add(streamQuota)\n\t}\n\tif !opts.Last {\n\t\treturn nil\n\t}\n\ts.mu.Lock()\n\tif s.state != streamDone {\n\t\ts.state = streamWriteDone\n\t}\n\ts.mu.Unlock()\n\treturn nil\n}", "func TestClientServer(t *testing.T) {\n\t// Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t// Create the certs and configs.\n\tCreateCA(root)\n\n\tCreateSignedCert(root, CA, \"01\", \"servers\", \"Servers CA\")\n\tCreateSignedCert(root, \"servers\", \"01\", \"server-instance\", \"server.example.com\")\n\n\tCreateSignedCert(root, CA, \"02\", \"clients\", \"Clients CA\")\n\tCreateSignedCert(root, \"clients\", \"01\", \"client-instance\", \"Client Instance\")\n\tserverConfig, err := vttls.ServerConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"clients-cert.pem\"))\n\tif err != nil {\n\t\tt.Fatalf(\"TLSServerConfig failed: %v\", err)\n\t}\n\tclientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"client-instance-cert.pem\"),\n\t\tpath.Join(root, \"client-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\t// Create a TLS server listener.\n\tlistener, err := tls.Listen(\"tcp\", \":0\", serverConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"Listen failed: %v\", err)\n\t}\n\taddr := listener.Addr().String()\n\tdefer listener.Close()\n\n\twg := sync.WaitGroup{}\n\n\t//\n\t// Positive case: accept on server side, connect a client, send data.\n\t//\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tclientConn, err := tls.Dial(\"tcp\", addr, clientConfig)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Dial failed: %v\", err)\n\t\t}\n\n\t\tclientConn.Write([]byte{42})\n\t\tclientConn.Close()\n\t}()\n\n\tserverConn, err := listener.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"Accept failed: %v\", err)\n\t}\n\n\tresult := make([]byte, 1)\n\tif n, err := serverConn.Read(result); (err != nil && err != io.EOF) || n != 1 {\n\t\tt.Fatalf(\"Read failed: %v %v\", n, err)\n\t}\n\tif result[0] != 42 {\n\t\tt.Fatalf(\"Read returned wrong result: %v\", result)\n\t}\n\tserverConn.Close()\n\n\twg.Wait()\n\n\t//\n\t// Negative case: connect a client with wrong cert (using the\n\t// server cert on the client side).\n\t//\n\n\tbadClientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\t// We expect the Accept to work, but the first read to fail.\n\t\tdefer wg.Done()\n\t\tserverConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Connection failed: %v\", err)\n\t\t}\n\n\t\t// This will fail.\n\t\tresult := make([]byte, 1)\n\t\tif n, err := serverConn.Read(result); err == nil {\n\t\t\tfmt.Printf(\"Was able to read from server: %v\\n\", n)\n\t\t}\n\t\tserverConn.Close()\n\t}()\n\n\t// When using TLS 1.2, the Dial will fail.\n\t// With TLS 1.3, the Dial will succeed and the first Read will fail.\n\tclientConn, err := tls.Dial(\"tcp\", addr, badClientConfig)\n\tif err != nil {\n\t\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t\t}\n\t\treturn\n\t}\n\tdata := make([]byte, 1)\n\t_, err = clientConn.Read(data)\n\tif err == nil {\n\t\tt.Fatalf(\"Dial or first Read was expected to fail\")\n\t}\n\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t}\n}", "func TestAllConn(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tstartAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// changing limits in runtime (applies to all existing connections)\n\treqSpeedC := int64(speedC) / 10\n\treqSpeed1 := reqSpeedC / 3\n\treqSpeed2 := reqSpeedC / 3\n\tl.(*netlisten.Listener).ReadLimiter().SetPerChildCPS(reqSpeed1)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviation1 := (speed1 - float64(reqSpeed1)) / float64(reqSpeed1)\n\tdeviation2 := (speed2 - float64(reqSpeed2)) / float64(reqSpeed2)\n\n\tfmt.Printf(\"Limits: 1 %d, 2 %d: speed 1: %f (d: %3.3f), speed 2: %f (d: %3.3f), common: %f\\n\", reqSpeed1, reqSpeed2, speed1, deviation1, speed2, deviation2, speedC)\n\n\tif math.Abs(deviation1) > MaxDeviation {\n\t\tt.Errorf(\"1 deviation too big: %3.3f\", deviation1)\n\t}\n\tif math.Abs(deviation2) > MaxDeviation {\n\t\tt.Errorf(\"2 deviation too big: %3.3f\", deviation2)\n\t}\n}", "func BenchmarkStreamingDecode_Protobuf(b *testing.B) {\n\tframe := getTestFrame(b, TypeProtobuf, 10000)\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\ttestDecodingFrame(b, frame, TypeProtobuf)\n\t\t}\n\t})\n}", "func (m *Mock) StartTLS() *httptest.Server {\n\tm.Ts.StartTLS()\n\treturn m.Ts\n}", "func TestPlaintextDialTLS(t *testing.T) {\n\turi, err := ParseURI(integrationURLFromEnv())\n\tif err != nil {\n\t\tt.Fatalf(\"parse URI error: %s\", err)\n\t}\n\n\t// We can only test when we have a plaintext listener\n\tif uri.Scheme != \"amqp\" {\n\t\tt.Skip(\"requires server listening for plaintext connections\")\n\t}\n\n\tconn, err := DialTLS(uri.String(), &tls.Config{MinVersion: tls.VersionTLS12})\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected dial error, got %v\", err)\n\t}\n\tconn.Close()\n}", "func TLS(address string) bool {\n\td := &net.Dialer{Timeout: timeout}\n\tconn, err := tls.DialWithDialer(d, \"tcp\", address, nil)\n\tif err != nil {\n\t\treturn false\n\t}\n\tconn.Close()\n\treturn true\n}", "func (srv *TCPServer) ServeTLS(l net.Listener, certFile, keyFile string) (err error) {\n\tconfig := srv.TLSConfig\n\tif config == nil {\n\t\tconfig = &tls.Config{}\n\t}\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\ttlsListener := tls.NewListener(l, config)\n\treturn srv.Serve(tlsListener)\n}", "func BenchmarkStreamPipeline(b *testing.B) {\n\tb.ReportAllocs()\n\tnumbers := gen(1_000_000)\n\tfor i := 0; i < b.N; i++ {\n\t\tfor _, num := range numbers {\n\t\t\tsMultiply(sAdd(sMultiply(num, 2), 1), 2)\n\t\t}\n\t}\n}", "func main() {\n\tkvURL, kvCert := mustArgs()\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create credentials\", zap.Error(err))\n\t}\n\n\tkvs, err := keyvault.NewShim(kvURL, cred)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create keyvault client\", zap.Error(err))\n\t}\n\n\ttlsCert, err := kvs.GetLatestTLSCertificate(context.TODO(), kvCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get tls cert from keyvault\", zap.Error(err))\n\t}\n\n\tclientTLSConfig, err := createClientTLSConfig(tlsCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create client tls config\", zap.Error(err))\n\t}\n\n\tserver := http.Server{\n\t\tAddr: serverAddr,\n\t\tHandler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t_, _ = writer.Write([]byte(\"hello\"))\n\t\t}),\n\t\tTLSConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{tlsCert},\n\t\t\tClientCAs: clientTLSConfig.RootCAs,\n\t\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\t},\n\t}\n\n\tgo func() {\n\t\tif err := server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tlogger.Fatal(\"could not serve tls\", zap.Error(err))\n\t\t}\n\t}()\n\n\t// wait for a short time to allow server to start\n\ttime.Sleep(time.Second)\n\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: clientTLSConfig,\n\t\t},\n\t}\n\n\taddr := fmt.Sprintf(\"https://%s\", serverAddr)\n\tresp, err := client.Get(addr)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get response\", zap.String(\"host\", addr), zap.Error(err))\n\t}\n\n\tprintTLSConnState(resp.TLS)\n\n\tbs, _ := io.ReadAll(resp.Body)\n\tlogger.Info(\"response from tls server\", zap.String(\"body bytes\", string(bs)))\n}", "func TestPlainHTTPServer(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{\n\t\t// The default context uses embedded certs.\n\t\tInsecure: true,\n\t})\n\tdefer s.Stopper().Stop()\n\tts := s.(*TestServer)\n\n\thttpClient, err := s.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thttpURL := \"http://\" + ts.Ctx.HTTPAddr + healthPath\n\tif resp, err := httpClient.Get(httpURL); err != nil {\n\t\tt.Fatalf(\"error requesting health at %s: %s\", httpURL, err)\n\t} else {\n\t\tdefer resp.Body.Close()\n\t\tvar data serverpb.HealthResponse\n\t\tif err := jsonpb.Unmarshal(resp.Body, &data); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\thttpsURL := \"https://\" + ts.Ctx.HTTPAddr + healthPath\n\tif _, err := httpClient.Get(httpsURL); err == nil {\n\t\tt.Fatalf(\"unexpected success fetching %s\", httpsURL)\n\t}\n}", "func TestHTTPSServer(t *testing.T) {\n\n\tcaCert := path.Join(assetsDir, \"rootCA.crt\")\n\tserverCert := path.Join(assetsDir, \"server.crt\")\n\tserverKey := path.Join(assetsDir, \"server.key\")\n\tclientCert := path.Join(assetsDir, \"client.crt\")\n\tclientKey := path.Join(assetsDir, \"client.key\")\n\tuntrustedClientCert := path.Join(assetsDir, \"other_client.crt\")\n\tuntrustedClientKey := path.Join(assetsDir, \"other_client.key\")\n\n\tauthServer := AuthServer{\n\t\tAddr: \":3457\",\n\t\tSpiffeID: \"spiffe://example.com/service\",\n\t\tCertFile: serverCert,\n\t\tKeyFile: serverKey,\n\t\tCaCert: caCert,\n\t\tCertValidator: validator.SvidValidator{},\n\t}\n\n\t// Run the HTTPS server\n\tgo func() {\n\t\tauthServer.Start()\n\t}()\n\n\t// Create a client with a trusted SpiffeID\n\tclient := createClient(clientCert, clientKey, caCert)\n\n\t// Perform a the authentication request\n\tres, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Response code was %v; want 200\", res.StatusCode)\n\t}\n\n\t// Create a client with an untrusted SpiffeID\n\tclient = createClient(untrustedClientCert, untrustedClientKey, caCert)\n\n\t// Perform a the authentication request\n\tres2, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res2.Body.Close()\n\n\tif res2.StatusCode != 401 {\n\t\tt.Errorf(\"Response code was %v; want 401\", res.StatusCode)\n\t}\n\n\t// Send signal to shutdown the server\n\tshutdown <- 1\n}", "func (serv *Server) RunTLS(addr, certFile, keyFile string) (err error) {\n\tdebugPrint(\"Listening and serving HTTPS on %s\\n\", addr)\n\tdefer func() { debugPrintError(err) }()\n\n\terr = http.ListenAndServeTLS(addr, certFile, keyFile, serv)\n\treturn\n}", "func Server(conn net.Conn, config *Config) *Conn {\n\ttls := new(Conn);\n\ttls.Conn = conn;\n\n\twriteChan := make(chan []byte);\n\treadChan := make(chan []byte);\n\trequestChan := make(chan interface{});\n\n\ttls.writeChan = writeChan;\n\ttls.readChan = readChan;\n\ttls.requestChan = requestChan;\n\n\thandshakeWriterChan := make(chan interface{});\n\tprocessorHandshakeChan := make(chan interface{});\n\thandshakeProcessorChan := make(chan interface{});\n\treaderProcessorChan := make(chan *record);\n\n\tgo new(recordWriter).loop(conn, writeChan, handshakeWriterChan);\n\tgo recordReader(readerProcessorChan, conn);\n\tgo new(recordProcessor).loop(readChan, requestChan, handshakeProcessorChan, readerProcessorChan, processorHandshakeChan);\n\tgo new(serverHandshake).loop(handshakeWriterChan, handshakeProcessorChan, processorHandshakeChan, config);\n\n\treturn tls;\n}", "func TestLineBufferParallel(t *testing.T) {\n\tsrc := &sourceTailer{lines: make(chan string)}\n\tbuffered := BufferedTailerWithMetrics(src)\n\tvar wg sync.WaitGroup\n\tgo func() {\n\t\tstart := time.Now()\n\t\tfor i := 0; i < 10000; i++ {\n\t\t\tsrc.lines <- fmt.Sprintf(\"This is line number %v.\", i)\n\t\t\tif rand.Int()%64 == 0 { // Sleep from time to time\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Producer took %v.\\n\", time.Since(start))\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tstart := time.Now()\n\t\tfor i := 0; i < 10000; i++ {\n\t\t\tline := <-buffered.Lines()\n\t\t\tif line != fmt.Sprintf(\"This is line number %v.\", i) {\n\t\t\t\tt.Errorf(\"Expected 'This is line number %v', but got '%v'.\", i, line)\n\t\t\t}\n\t\t\tif rand.Int()%64 == 0 { // Sleep from time to time\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"Consumer took %v.\\n\", time.Since(start))\n\t\twg.Done()\n\t}()\n\twg.Add(2)\n\twg.Wait()\n\tbuffered.Close()\n\t_, stillOpen := <-buffered.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Buffered tailer was not closed.\")\n\t}\n\t_, stillOpen = <-src.Lines()\n\tif stillOpen {\n\t\tt.Error(\"Source tailer was not closed.\")\n\t}\n}", "func BenchmarkTCPConnWithPool(b *testing.B) {\n\tb.ReportAllocs()\n\tpool := &sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\tconn, err := net.Dial(\"tcp\", \":8080\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"could not dial: %v\", err)\n\t\t\t}\n\t\t\treturn conn\n\t\t},\n\t}\n\tpool.Put(pool.New())\n\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tconnects := 50\n\tfor i := 0; i < b.N; i += connects {\n\t\tfor j := 0; j < connects; j++ {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tconn := pool.Get().(*net.TCPConn)\n\t\t\t\tpool.Put(conn)\n\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\terr := write(conn, \"write\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error writing: %v\", err)\n\t\t\t\t}\n\t\t\t\t_, err = read(conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Errorf(\"error reading: %v\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func TLSConnect(\n\tctx context.Context, config TLSConnectConfig,\n) *TLSConnectResults {\n\tvar (\n\t\tmu sync.Mutex\n\t\tresults = new(TLSConnectResults)\n\t)\n\tchannel := make(chan modelx.Measurement)\n\troot := &modelx.MeasurementRoot{\n\t\tBeginning: time.Now(),\n\t\tHandler: &channelHandler{\n\t\t\tch: channel,\n\t\t},\n\t}\n\tctx = modelx.WithMeasurementRoot(ctx, root)\n\tdialer := netx.NewDialer(handlers.NoHandler)\n\t// TODO(bassosimone): tell dialer to use specific CA bundle?\n\tresolver, err := configureDNS(\n\t\ttime.Now().UnixNano(),\n\t\tconfig.DNSServerNetwork,\n\t\tconfig.DNSServerAddress,\n\t)\n\tif err != nil {\n\t\tresults.Error = err\n\t\treturn results\n\t}\n\tdialer.SetResolver(resolver)\n\t// TODO(bassosimone): can this call really fail?\n\tdialer.ForceSpecificSNI(config.SNI)\n\tresults.TestKeys.collect(channel, config.Handler, func() {\n\t\tconn, err := dialer.DialTLSContext(ctx, \"tcp\", config.Address)\n\t\tif conn != nil {\n\t\t\tdefer conn.Close()\n\t\t}\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tresults.Error = err\n\t})\n\treturn results\n}", "func (pc *PeerConnection) Stream() error {\n\t// Wait for ICE agent to establish a connection.\n\ttimeoutCtx, _ := context.WithTimeout(pc.ctx, connectTimeout)\n\tdataStream, err := pc.iceAgent.GetDataStream(timeoutCtx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dataStream.Close()\n\n\t// Instantiate a new net.Conn multiplexer\n\tdataMux := mux.NewMux(dataStream, 8192)\n\tdefer dataMux.Close()\n\n\t// Instantiate a new endpoint for DTLS from multiplexer\n\tdtlsEndpoint := dataMux.NewEndpoint(mux.MatchDTLS)\n\n\t// Instantiate a new endpoint for SRTP from multiplexer\n\tsrtpEndpoint := dataMux.NewEndpoint(func(b []byte) bool {\n\t\t// First byte looks like 10??????, representing RTP version 2.\n\t\treturn b[0]&0xb0 == 0x80\n\t})\n\n\t// Configuration for DTLS handshake, namely certificate and private key\n\tconfig := &dtls.Config{Certificate: pc.certificate, PrivateKey: pc.privateKey}\n\n\t// Initiate a DTLS handshake as a client\n\tdtlsConn, err := dtls.Client(dtlsEndpoint, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create SRTP keys from DTLS handshake (see RFC5764 Section 4.2)\n\tkeys, err := dtlsConn.ExportKeyingMaterial(\"EXTRACTOR-dtls_srtp\", nil, 2*keyLen+2*saltLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkeyReader := bytes.NewBuffer(keys)\n\twriteKey := keyReader.Next(keyLen)\n\treadKey := keyReader.Next(keyLen)\n\twriteSalt := keyReader.Next(saltLen)\n\treadSalt := keyReader.Next(saltLen)\n\n\trtpSession := rtp.NewSession(rtp.SessionOptions{\n\t\tMuxConn: srtpEndpoint, // rtcp-mux assumed\n\t\tReadKey: readKey,\n\t\tReadSalt: readSalt,\n\t\tWriteKey: writeKey,\n\t\tWriteSalt: writeSalt,\n\t})\n\n\tvideoStreamOpts := rtp.StreamOptions{\n\t\tDirection: \"sendonly\",\n\t}\n\tfor _, m := range pc.localDescription.Media {\n\t\tif m.Type == \"video\" {\n\t\t\tfmt.Sscanf(m.GetAttr(\"ssrc\"), \"%d cname:%s\", &videoStreamOpts.LocalSSRC, &videoStreamOpts.LocalCNAME)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, m := range pc.remoteDescription.Media {\n\t\tif m.Type == \"video\" {\n\t\t\tfmt.Sscanf(m.GetAttr(\"ssrc\"), \"%d cname:%s\", &videoStreamOpts.RemoteSSRC, &videoStreamOpts.RemoteCNAME)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvideoStream := rtpSession.AddStream(videoStreamOpts)\n\tgo videoStream.SendVideo(pc.ctx.Done(), pc.DynamicType, pc.localVideo)\n\n\t//rtpSession, err := rtp.NewSecureSession(rtpEndpoint, readKey, readSalt, writeKey, writeSalt)\n\t//go streamH264(pc.ctx, pc.localVideoTrack, rtpSession.NewH264Stream(ssrc, cname))\n\n\t// Start goroutine for processing incoming SRTCP packets\n\t//go srtcpReaderRunloop(dataMux, readKey, readSalt)\n\n\t// Begin a new SRTP session\n\t//srtpSession, err := srtp.NewSession(srtpEndpoint, pc.DynamicType, writeKey, writeSalt)\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t// There are two termination conditions that we need to deal with here:\n\t// 1. Context cancellation. If Close() is called explicitly, or if the\n\t// parent context is canceled, we should terminate cleanly.\n\t// 2. Connection timeout. If the remote peer disconnects unexpectedly, the\n\t// read loop on the underlying net.UDPConn will time out. The associated\n\t// ice.DataStream will then be marked dead, which we check for here.\n\tselect {\n\tcase <-pc.ctx.Done():\n\t\treturn nil\n\tcase <-dataStream.Done():\n\t\treturn dataStream.Err()\n\t}\n}", "func TestFileTLS(t *testing.T) {\n\t// Create a temporary directory\n\tdir, err := ioutil.TempDir(\"\", \"gorilla_test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\t// Setup TLS auth\n\tdownloadCfg.TLSAuth = true\n\tdownloadCfg.TLSClientCert = \"testdata/client.pem\"\n\tdownloadCfg.TLSClientKey = \"testdata/client.key\"\n\tdownloadCfg.TLSServerCert = \"testdata/server.pem\"\n\tserverKeyPath := \"testdata/server.key\"\n\tcaCertPath := \"testdata/rootCA.pem\"\n\n\t// Create a test server\n\tts := httptest.NewUnstartedServer(router())\n\n\t// Prepare server certs\n\tserverCert, _ := ioutil.ReadFile(downloadCfg.TLSServerCert)\n\tserverKey, _ := ioutil.ReadFile(serverKeyPath)\n\tcaCert, _ := ioutil.ReadFile(caCertPath)\n\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(caCert)\n\n\tcert, err := tls.X509KeyPair(serverCert, serverKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Set TLS configuration\n\tts.TLS = &tls.Config{\n\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\tClientCAs: certPool,\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\n\t// Start server\n\tts.StartTLS()\n\tdefer ts.Close()\n\n\t// Compile the url with hostname instead of ip address\n\tu, err := url.Parse(ts.URL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttlsURL := \"https://localhost:\" + u.Port() + \"/tlsauth\"\n\n\t// Run the code\n\tfileErr := File(dir, tlsURL)\n\n\t// Check that we did not receive an error\n\tif fileErr != nil {\n\t\tt.Errorf(\"File download with TLS auth failed':\\n%v\", fileErr)\n\t}\n\n}", "func fastBenchmarkHTTP(ctx *fasthttp.RequestCtx) {\n\t_, err := ctx.Write([]byte(\"Retry !\"))\n\tcommonutils.Check(err, \"fastBenchmarkHTTP\")\n}", "func BenchmarkParallelProcess(b *testing.B) {\n\trand.Seed(18)\n\tp := protocols{}\n\tp.tcp = make(map[protos.Protocol]protos.TcpProtocolPlugin)\n\tp.tcp[1] = &TestProtocol{Ports: []int{ServerPort}}\n\ttcp, _ := NewTcp(p)\n\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tpkt := &protos.Packet{\n\t\t\t\tTs: time.Now(),\n\t\t\t\tTuple: common.NewIpPortTuple(4,\n\t\t\t\t\tnet.ParseIP(ServerIp), ServerPort,\n\t\t\t\t\tnet.ParseIP(ClientIp), uint16(rand.Intn(65535))),\n\t\t\t\tPayload: []byte{1, 2, 3, 4},\n\t\t\t}\n\t\t\ttcp.Process(&layers.TCP{}, pkt)\n\t\t}\n\t})\n}", "func ListenAndServeHTTP(addr string, connLimit int, certFile *string, keyFile *string, handler http.Handler, readTimeout *int, writeTimeout *int, http2Enabled bool) error {\n\tvar config *tls.Config\n\tif certFile != nil {\n\t\tconfig = &tls.Config{}\n\t\tconfig.MinVersion = tls.VersionTLS10 // Disable SSLv3 due to POODLE vulnerability\n\t\tprotocolsEnabled := []string{\"http/1.1\"}\n\t\tif http2Enabled {\n\t\t\tprotocolsEnabled = []string{\"h2\", \"http/1.1\"}\n\t\t}\n\t\tconfig.NextProtos = protocolsEnabled\n\t\tLogTo(\"HTTP\", \"Protocols enabled: %v on %v\", config.NextProtos, addr)\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tvar err error\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(*certFile, *keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlistener, err := ThrottledListen(\"tcp\", addr, connLimit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tlistener = tls.NewListener(listener, config)\n\t}\n\tdefer listener.Close()\n\tserver := &http.Server{Addr: addr, Handler: handler}\n\tif readTimeout != nil {\n\t\tserver.ReadTimeout = time.Duration(*readTimeout) * time.Second\n\t}\n\tif writeTimeout != nil {\n\t\tserver.WriteTimeout = time.Duration(*writeTimeout) * time.Second\n\t}\n\n\treturn server.Serve(listener)\n}", "func Server(conn net.Conn, config *tls.Config,) *tls.Conn", "func TestV3Curl_MaxStreams_BelowLimit_NoTLS_Small(t *testing.T) {\n\ttestV3CurlMaxStream(t, false, withCfg(*e2e.NewConfigNoTLS()), withMaxConcurrentStreams(3))\n}", "func TestProbeHTTPS(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TestPerServer(t *testing.T) {\n\tl := listen()\n\n\tclientG := new(int64)\n\tclient1, client2 := startClients(l.Addr(), clientG)\n\n\tserverG := new(int64)\n\tstartAccept(l, serverG)\n\n\tstartTime := time.Now()\n\n\ttime.Sleep(Interval / 3)\n\n\tcurTime := time.Now()\n\tspeed1 := float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 := float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC := float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tfmt.Printf(\"Unlimited: speed 1: %f, speed 2: %f, common: %f\\n\", speed1, speed2, speedC)\n\n\t// setting bandwidth limit per server\n\treqSpeedC := int64(speedC) / 10\n\tl.(*netlisten.Listener).ReadLimiter().SetCommonCPS(reqSpeedC)\n\tatomic.StoreInt64(client1.total, 0)\n\tatomic.StoreInt64(client2.total, 0)\n\tatomic.StoreInt64(clientG, 0)\n\n\tstartTime = time.Now()\n\ttime.Sleep(TestDuration)\n\n\tcurTime = time.Now()\n\tspeed1 = float64(atomic.LoadInt64(client1.total)) / curTime.Sub(startTime).Seconds()\n\tspeed2 = float64(atomic.LoadInt64(client2.total)) / curTime.Sub(startTime).Seconds()\n\tspeedC = float64(atomic.LoadInt64(clientG)) / curTime.Sub(startTime).Seconds()\n\n\tdeviationC := (speedC - float64(reqSpeedC)) / float64(reqSpeedC)\n\n\tfmt.Printf(\"Limits: common %d: speed 1: %f, speed 2: %f, common: %f (d: %3.3f) \\n\", reqSpeedC, speed1, speed2, speedC, deviationC)\n\n\tif math.Abs(deviationC) > MaxDeviation {\n\t\tt.Errorf(\"common deviation too big: %3.3f\", deviationC)\n\t}\n}", "func TestApiSpeed (t *testing.T) {\n\tgo setUpApi() \t//run the service asynchronously\n\n\tclient := http.Client{\n\t\tTimeout: time.Second * 2,\n\t} //Initialize the client\n\n\n\tfor i := 10990; i < 11010 ; i++{\n\t\tstart:= time.Now()\n\t\tcallApiWithCount(i,client)\n\t\telapsed := time.Since(start)\n\t\tt.Logf(\"%v took %s\\n\", i, elapsed)\n\t}\n\n}", "func TestConnMemoryOverhead(t *testing.T) {\n\tnum := 1000\n\tif testing.Short() {\n\t\tnum = 100\n\t}\n\tng0 := runtime.NumGoroutine()\n\n\truntime.GC()\n\tvar ms0 runtime.MemStats\n\truntime.ReadMemStats(&ms0)\n\n\tvar closers []io.Closer\n\tcloseAll := func() {\n\t\tfor _, c := range closers {\n\t\t\tc.Close()\n\t\t}\n\t\tclosers = nil\n\t}\n\tdefer closeAll()\n\n\tfor i := 0; i < num; i++ {\n\t\tclient, server := pair(t)\n\t\tclosers = append(closers, client, server)\n\t\tgo func() {\n\t\t\tvar buf [1]byte\n\t\t\tclient.Read(buf[:])\n\t\t}()\n\t}\n\n\tt0 := time.Now()\n\tdeadline := t0.Add(3 * time.Second)\n\tvar ngo int\n\tfor time.Now().Before(deadline) {\n\t\truntime.GC()\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo >= num {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo < num {\n\t\tt.Fatalf(\"only %v goroutines; expected %v+\", ngo, num)\n\t}\n\truntime.GC()\n\tvar ms runtime.MemStats\n\truntime.ReadMemStats(&ms)\n\tgrowthTotal := int64(ms.HeapAlloc) - int64(ms0.HeapAlloc)\n\tgrowthEach := float64(growthTotal) / float64(num)\n\tt.Logf(\"Alloced %v bytes, %.2f B/each\", growthTotal, growthEach)\n\tconst max = 2000\n\tif growthEach > max {\n\t\tt.Errorf(\"allocated more than expected; want max %v bytes/each\", max)\n\t}\n\n\tcloseAll()\n\n\t// And make sure our goroutines go away too.\n\tdeadline = time.Now().Add(3 * time.Second)\n\tfor time.Now().Before(deadline) {\n\t\tngo = runtime.NumGoroutine()\n\t\tif ngo < ng0+num/10 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif ngo >= ng0+num/10 {\n\t\tt.Errorf(\"goroutines didn't go back down; started at %v, now %v\", ng0, ngo)\n\t}\n}", "func TestReceivePerformance(t *testing.T) {\n\tt.Skip(\"Skipped by default\")\n\n\tconst defaultNumGoRoutines = 100\n\tdefaultReceiveProfile := func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 0 }\n\tdefaultProcessProfile := func(bool) time.Duration { return 0 }\n\n\ttests := []struct {\n\t\tdescription string\n\t\t// See the defaults above.\n\t\tnumGoRoutines int\n\t\treceiveProfile func(bool, int) (int, time.Duration)\n\t\tprocessProfile func(bool) time.Duration\n\t}{\n\t\t{\n\t\t\tdescription: \"baseline\",\n\t\t},\n\t\t{\n\t\t\tdescription: \"1 goroutine\",\n\t\t\tnumGoRoutines: 1,\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 100ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 100 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 1s\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 1 * time.Second },\n\t\t},\n\t\t{\n\t\t\tdescription: \"process 100ms\",\n\t\t\tprocessProfile: func(bool) time.Duration { return 100 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"process 1s\",\n\t\t\tprocessProfile: func(bool) time.Duration { return 1 * time.Second },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 1s process 70ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, 1 * time.Second\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return 70 * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"receive 250ms+stddev 150ms, process 10ms + stddev 5ms\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, time.Duration(rand.NormFloat64()*150+250) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty message arrival\",\n\t\t\treceiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {\n\t\t\t\t// When in the middle third of the running time, return 0 messages.\n\t\t\t\tn := maxMessages\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\tn = 0\n\t\t\t\t}\n\t\t\t\treturn n, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty receive time\",\n\t\t\treceiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {\n\t\t\t\t// When in the middle third of the running time, 10x the RPC time.\n\t\t\t\td := time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\td *= 10\n\t\t\t\t}\n\t\t\t\treturn maxMessages, d\n\t\t\t},\n\t\t\tprocessProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },\n\t\t},\n\t\t{\n\t\t\tdescription: \"bursty process time\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\treturn maxMessages, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond\n\t\t\t},\n\t\t\tprocessProfile: func(inMiddleThird bool) time.Duration {\n\t\t\t\td := time.Duration(rand.NormFloat64()*5+10) * time.Millisecond\n\t\t\t\tif inMiddleThird {\n\t\t\t\t\td *= 100\n\t\t\t\t}\n\t\t\t\treturn d\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"intermittent\",\n\t\t\treceiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {\n\t\t\t\tn := rand.Int() % 2\n\t\t\t\treturn n, 250 * time.Millisecond\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif test.numGoRoutines == 0 {\n\t\t\ttest.numGoRoutines = defaultNumGoRoutines\n\t\t}\n\t\tif test.receiveProfile == nil {\n\t\t\ttest.receiveProfile = defaultReceiveProfile\n\t\t}\n\t\tif test.processProfile == nil {\n\t\t\ttest.processProfile = defaultProcessProfile\n\t\t}\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\trunBenchmark(t, test.description, test.numGoRoutines, test.receiveProfile, test.processProfile)\n\t\t})\n\t}\n}", "func (lb *LB) ServeTLS(tlsConfig *tls.Config, certFile, keyFile string) error {\n\tlisner, err := net.Listen(\"tcp\", lb.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlb.TLSConfig = tlsConfig\n\n\tglg.Success(\"Load Balancer starting on \" + lb.Addr)\n\terr = lb.Server.ServeTLS(lisner, certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestProbeHTTPSProxy(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tproxyServer, err := test.SetupHTTPProxyServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tproxyServer.Start()\n\tdefer proxyServer.Close()\n\n\tproxyURL, err := url.Parse(proxyServer.URL)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tbadProxyURL, err := url.Parse(\"http://localhost:6666\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t\tHTTPS: config.HTTPSProbe{\n\t\t\t// Test with a bad proxy url first\n\t\t\tProxyURL: config.URL{URL: badProxyURL},\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err == nil {\n\t\tt.Fatalf(\"expected error but err was nil\")\n\t}\n\n\t// Test with the proxy url, this shouldn't return an error\n\tmodule.HTTPS.ProxyURL = config.URL{URL: proxyURL}\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TestTestTLSExtensionsVerifyServer(t *testing.T) {\n\textendVerify := map[string]interface{}{\n\t\t\"name\": \"client\",\n\t\t\"cn\": \"server\",\n\t}\n\tclientInfo := &certInfo{\n\t\tCommonName: extendVerify[\"name\"].(string),\n\t\tCurve: \"RSA\",\n\t}\n\n\ttestCases := []struct {\n\t\tInfo *certInfo\n\t\tPass func(resp *http.Response, err error) bool\n\t}{\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: extendVerify[\"cn\"].(string),\n\t\t\t\tCurve: clientInfo.Curve,\n\t\t\t\tDNS: \"www.pass.com\",\n\t\t\t},\n\t\t\tPass: pass,\n\t\t},\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: \"invalid server\",\n\t\t\t\tCurve: clientInfo.Curve,\n\t\t\t\tDNS: \"www.fail.com\",\n\t\t\t},\n\t\t\tPass: fail,\n\t\t},\n\t}\n\tvar filterChains []v2.FilterChain\n\tfor i, tc := range testCases {\n\t\tcfg, err := tc.Info.CreateCertConfig()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"#%d %v\", i, err)\n\t\t\treturn\n\t\t}\n\t\tfc := v2.FilterChain{\n\t\t\tTLSContexts: []v2.TLSConfig{\n\t\t\t\t*cfg,\n\t\t\t},\n\t\t}\n\t\tfilterChains = append(filterChains, fc)\n\t}\n\tlc := &v2.Listener{}\n\tlc.FilterChains = filterChains\n\tctxMng, err := NewTLSServerContextManager(lc)\n\tif err != nil {\n\t\tt.Errorf(\"create context manager failed %v\", err)\n\t\treturn\n\t}\n\tserver := MockServer{\n\t\tMng: ctxMng,\n\t\tt: t,\n\t}\n\tserver.GoListenAndServe(t)\n\tdefer server.Close()\n\ttime.Sleep(time.Second) //wait server start\n\tclientConfig, err := clientInfo.CreateCertConfig()\n\tif err != nil {\n\t\tt.Errorf(\"create client certificate error %v\", err)\n\t\treturn\n\t}\n\tclientConfig.Type = testType\n\tclientConfig.ExtendVerify = extendVerify\n\tfor i, tc := range testCases {\n\t\tclientConfig.ServerName = tc.Info.DNS\n\t\tcltMng, err := NewTLSClientContextManager(clientConfig)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"create client context manager failed %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tresp, err := MockClient(t, server.Addr, cltMng)\n\t\tif !tc.Pass(resp, err) {\n\t\t\tt.Errorf(\"#%d verify failed\", i)\n\t\t}\n\t}\n\t// insecure skip will skip even if it is registered\n\tskipConfig := &v2.TLSConfig{\n\t\tStatus: true,\n\t\tType: clientConfig.Type,\n\t\tCACert: clientConfig.CACert,\n\t\tCertChain: clientConfig.CertChain,\n\t\tPrivateKey: clientConfig.PrivateKey,\n\t\tInsecureSkip: true,\n\t}\n\tfor i, tc := range testCases {\n\t\tskipConfig.ServerName = tc.Info.DNS\n\t\tskipMng, err := NewTLSClientContextManager(skipConfig)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"create client context manager failed %v\", err)\n\t\t\treturn\n\t\t}\n\t\tresp, err := MockClient(t, server.Addr, skipMng)\n\t\t// ignore the case, must be pass\n\t\tif !pass(resp, err) {\n\t\t\tt.Errorf(\"#%d skip verify failed\", i)\n\t\t}\n\t}\n\n}", "func (gss *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {\n\tctx, cancel := context.WithCancel(context.Background())\n\tgo func() {\n\t\tif err := gss.server.ServeTLS(l, certFile, keyFile); err != nil {\n\t\t\tgss.startErr = err\n\t\t\tcancel()\n\t\t}\n\t}()\n\treturn gss.waitForInterrupt(ctx)\n}", "func ListenTLS(how, addr string, certFile, keyFile string) (*Server, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ListenTLSCustom(how, addr, &tls.Config{\n\t\tRootCAs: TLSCertPool(),\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n}", "func matchTLS(match *v1alpha3.TLSMatchAttributes, proxyLabels labels.Collection, gateways map[string]bool, port int, proxyNamespace string) bool {\n\tif match == nil {\n\t\treturn true\n\t}\n\n\tgatewayMatch := len(match.Gateways) == 0\n\tfor _, gateway := range match.Gateways {\n\t\tgatewayMatch = gatewayMatch || gateways[gateway]\n\t}\n\n\tlabelMatch := proxyLabels.IsSupersetOf(match.SourceLabels)\n\n\tportMatch := match.Port == 0 || match.Port == uint32(port)\n\n\tnsMatch := match.SourceNamespace == \"\" || match.SourceNamespace == proxyNamespace\n\n\treturn gatewayMatch && labelMatch && portMatch && nsMatch\n}", "func speedtest1_end_test(tls *libc.TLS) { /* speedtest1.c:399:6: */\n\tbp := tls.Alloc(24)\n\tdefer tls.Free(24)\n\n\tvar iElapseTime sqlite3_int64 = (speedtest1_timestamp(tls) - g.iStart)\n\tif g.doCheckpoint != 0 {\n\t\tspeedtest1_exec(tls, ts+2549 /* \"PRAGMA wal_check...\" */, 0)\n\t}\n\tif !(g.bSqlOnly != 0) {\n\t\t*(*sqlite3_int64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 16 /* &.iTotal */)) += (iElapseTime)\n\t\tlibc.Xprintf(tls, ts+2572 /* \"%4d.%03ds\\n\" */, libc.VaList(bp, (int32(iElapseTime/int64(1000))), (int32(iElapseTime%int64(1000)))))\n\t}\n\tif g.pStmt != 0 {\n\t\tsqlite3.Xsqlite3_finalize(tls, g.pStmt)\n\t\tg.pStmt = uintptr(0)\n\t}\n}", "func SMTPServerTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := tls.Listen(\"tcp\", addr, &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func networkThread(ctx context.Context, reqs int) {\n\tstartTime := time.Now()\n\tnewclient := http.Client{}\n\n\tfor i := 0; i < reqs; i++ {\n\n\t\tnewRequest, _ := http.NewRequest(\"GET\", URL, nil)\n\t\tnewRequest = newRequest.WithContext(ctx)\n\t\tresp, _ := newclient.Do(newRequest)\n\n\t\tbody := make([]byte, 0)\n\t\tbody, _ = ioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t\tfmt.Printf(\"Response %v : %v\\n\", i, string(body))\n\n\t\ttime.Sleep(time.Second * 1)\n\n\t}\n\n\tendTime := time.Now().Sub(startTime)\n\tfmt.Printf(\"Total running time for networkThread : %v\", endTime)\n\n}", "func TestTLSExtensionsVerifyClient(t *testing.T) {\n\t// Server\n\textendVerify := map[string]interface{}{\n\t\t\"name\": \"server\",\n\t\t\"cn\": \"client\",\n\t}\n\tserverInfo := &certInfo{\n\t\tCommonName: extendVerify[\"name\"].(string),\n\t\tCurve: \"RSA\",\n\t}\n\tserverConfig, err := serverInfo.CreateCertConfig()\n\tif err != nil {\n\t\tt.Errorf(\"create server certificate error %v\", err)\n\t\treturn\n\t}\n\tserverConfig.RequireClientCert = true\n\tserverConfig.VerifyClient = true\n\tserverConfig.Type = testType\n\tserverConfig.ExtendVerify = extendVerify\n\tfilterChains := []v2.FilterChain{\n\t\t{\n\t\t\tTLSContexts: []v2.TLSConfig{\n\t\t\t\t*serverConfig,\n\t\t\t},\n\t\t},\n\t}\n\tlc := &v2.Listener{}\n\tlc.FilterChains = filterChains\n\tctxMng, err := NewTLSServerContextManager(lc)\n\tif err != nil {\n\t\tt.Errorf(\"create context manager failed %v\", err)\n\t\treturn\n\t}\n\tserver := MockServer{\n\t\tMng: ctxMng,\n\t\tt: t,\n\t}\n\tserver.GoListenAndServe(t)\n\tdefer server.Close()\n\ttime.Sleep(time.Second) //wait server start\n\ttestCases := []struct {\n\t\tInfo *certInfo\n\t\tPass func(resp *http.Response, err error) bool\n\t}{\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: extendVerify[\"cn\"].(string),\n\t\t\t\tCurve: serverInfo.Curve,\n\t\t\t},\n\t\t\tPass: pass,\n\t\t},\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: \"invalid client\",\n\t\t\t\tCurve: serverInfo.Curve,\n\t\t\t},\n\t\t\tPass: fail,\n\t\t},\n\t}\n\tfor i, tc := range testCases {\n\t\tcfg, err := tc.Info.CreateCertConfig()\n\t\tcfg.ServerName = \"127.0.0.1\"\n\t\tif err != nil {\n\t\t\tt.Errorf(\"#%d create client certificate error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tcltMng, err := NewTLSClientContextManager(cfg)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"#%d create client context manager failed %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresp, err := MockClient(t, server.Addr, cltMng)\n\t\tif !tc.Pass(resp, err) {\n\t\t\tt.Errorf(\"#%d verify failed\", i)\n\t\t}\n\t}\n\n}", "func TestPubsubBulkPublishHttpPerformance(t *testing.T) {\n\tpublishTypes := []string{\"normal\", \"bulk\"}\n\tbulkSizes := []int{10, 100}\n\tmessageSizesKb := []int{1}\n\n\ttestcases := []testCase{}\n\tfor _, bulkSize := range bulkSizes {\n\t\tfor _, messageSizeKb := range messageSizesKb {\n\t\t\tfor _, broker := range brokers {\n\t\t\t\tfor _, publishType := range publishTypes {\n\t\t\t\t\ttestcases = append(testcases, testCase{\n\t\t\t\t\t\tbroker: broker.Name,\n\t\t\t\t\t\tpublishType: publishType,\n\t\t\t\t\t\ttopic: topicName,\n\t\t\t\t\t\tbulkSize: bulkSize,\n\t\t\t\t\t\tmessageSizeKb: messageSizeKb,\n\t\t\t\t\t\tdurationMs: 30 * 1000,\n\t\t\t\t\t\tnumVus: 50,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, tc := range testcases {\n\t\ttestName := fmt.Sprintf(\"%s_b%d_s%dKB_%s\", tc.broker, tc.bulkSize, tc.messageSizeKb, tc.publishType)\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\trunTest(t, tc)\n\t\t})\n\t}\n}", "func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, passCount, length int) ([]map[string]interface{}, error) {\n\tbenchmarks := make([]requestBenchmark, len(setups))\n\tfor i, setup := range setups {\n\t\tif t, ok := setup[\"type\"].(string); ok {\n\t\t\tgetInt := func(field string, def int) int {\n\t\t\t\tif value, ok := setup[field].(float64); ok {\n\t\t\t\t\treturn int(value)\n\t\t\t\t}\n\t\t\t\treturn def\n\t\t\t}\n\t\t\tgetBool := func(field string, def bool) bool {\n\t\t\t\tif value, ok := setup[field].(bool); ok {\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn def\n\t\t\t}\n\t\t\tswitch t {\n\t\t\tcase \"header\":\n\t\t\t\tbenchmarks[i] = &benchmarkBlockHeaders{\n\t\t\t\t\tamount: getInt(\"amount\", 1),\n\t\t\t\t\tskip: getInt(\"skip\", 1),\n\t\t\t\t\tbyHash: getBool(\"byHash\", false),\n\t\t\t\t\treverse: getBool(\"reverse\", false),\n\t\t\t\t}\n\t\t\tcase \"body\":\n\t\t\t\tbenchmarks[i] = &benchmarkBodiesOrReceipts{receipts: false}\n\t\t\tcase \"receipts\":\n\t\t\t\tbenchmarks[i] = &benchmarkBodiesOrReceipts{receipts: true}\n\t\t\tcase \"proof\":\n\t\t\t\tbenchmarks[i] = &benchmarkProofsOrCode{code: false}\n\t\t\tcase \"code\":\n\t\t\t\tbenchmarks[i] = &benchmarkProofsOrCode{code: true}\n\t\t\tcase \"cht\":\n\t\t\t\tbenchmarks[i] = &benchmarkHelperTrie{\n\t\t\t\t\tbloom: false,\n\t\t\t\t\treqCount: getInt(\"amount\", 1),\n\t\t\t\t}\n\t\t\tcase \"bloom\":\n\t\t\t\tbenchmarks[i] = &benchmarkHelperTrie{\n\t\t\t\t\tbloom: true,\n\t\t\t\t\treqCount: getInt(\"amount\", 1),\n\t\t\t\t}\n\t\t\tcase \"txSend\":\n\t\t\t\tbenchmarks[i] = &benchmarkTxSend{}\n\t\t\tcase \"txStatus\":\n\t\t\t\tbenchmarks[i] = &benchmarkTxStatus{}\n\t\t\tdefault:\n\t\t\t\treturn nil, ErrUnknownBenchmarkType\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, ErrUnknownBenchmarkType\n\t\t}\n\t}\n\trs := api.server.protocolManager.runBenchmark(benchmarks, passCount, time.Millisecond*time.Duration(length))\n\tresult := make([]map[string]interface{}, len(setups))\n\tfor i, r := range rs {\n\t\tres := make(map[string]interface{})\n\t\tif r.err == nil {\n\t\t\tres[\"totalCount\"] = r.totalCount\n\t\t\tres[\"avgTime\"] = r.avgTime\n\t\t\tres[\"maxInSize\"] = r.maxInSize\n\t\t\tres[\"maxOutSize\"] = r.maxOutSize\n\t\t} else {\n\t\t\tres[\"error\"] = r.err.Error()\n\t\t}\n\t\tresult[i] = res\n\t}\n\treturn result, nil\n}", "func (e *MyTest) Stream(ctx context.Context, req *myTest.StreamingRequest, stream myTest.MyTest_StreamStream) error {\n\tlog.Logf(\"Received MyTest.Stream request with count: %d\", req.Count)\n\n\tfor i := 0; i < int(req.Count); i++ {\n\t\tlog.Logf(\"Responding: %d\", i)\n\t\tif err := stream.Send(&myTest.StreamingResponse{\n\t\t\tCount: int64(i),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (aps *ApiServer) RunTLS() error {\n\treturn aps.Engine.RunTLS(aps.ipAddr+\":\"+strconv.Itoa(aps.port), aps.certFile, aps.keyFile)\n}", "func (s *MockServer) StartTLS() {\n\tcert, err := tls.X509KeyPair(localhostCert, localhostKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"NewTLSServer: %v\", err))\n\t}\n\n\t// init tls config and tls listener\n\tif s.TLS == nil {\n\t\ts.TLS = new(tls.Config)\n\t}\n\tif len(s.TLS.Certificates) == 0 {\n\t\ts.TLS.Certificates = []tls.Certificate{cert}\n\t}\n\ttlsListener := tls.NewListener(s.Listener, s.TLS)\n\ts.Listener = &historyListener{Listener: tlsListener}\n\n\t// start tls server\n\tgo s.Serve(s.Listener)\n}", "func HTTPAPIServerStreamHLSM3U8(c *gin.Context) {\n\trequestLogger := log.WithFields(logrus.Fields{\n\t\t\"module\": \"http_hls\",\n\t\t\"stream\": c.Param(\"uuid\"),\n\t\t\"channel\": c.Param(\"channel\"),\n\t\t\"func\": \"HTTPAPIServerStreamHLSM3U8\",\n\t})\n\n\tif !Storage.StreamChannelExist(c.Param(\"uuid\"), c.Param(\"channel\")) {\n\t\tc.IndentedJSON(500, Message{Status: 0, Payload: ErrorStreamNotFound.Error()})\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"StreamChannelExist\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\n\tif !RemoteAuthorization(\"HLS\", c.Param(\"uuid\"), c.Param(\"channel\"), c.Param(\"token\"), c.ClientIP()) {\n\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\"call\": \"RemoteAuthorization\",\n\t\t}).Errorln(ErrorStreamNotFound.Error())\n\t\treturn\n\t}\n\n\tc.Header(\"Content-Type\", \"application/x-mpegURL\")\n\tStorage.StreamChannelRun(c.Param(\"uuid\"), c.Param(\"channel\"))\n\t//If stream mode on_demand need wait ready segment's\n\tfor i := 0; i < 40; i++ {\n\t\tindex, seq, err := Storage.StreamHLSm3u8(c.Param(\"uuid\"), c.Param(\"channel\"))\n\t\tif err != nil {\n\t\t\tc.IndentedJSON(500, Message{Status: 0, Payload: err.Error()})\n\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\"call\": \"StreamHLSm3u8\",\n\t\t\t}).Errorln(err.Error())\n\t\t\treturn\n\t\t}\n\t\tif seq >= 6 {\n\t\t\t_, err := c.Writer.Write([]byte(index))\n\t\t\tif err != nil {\n\t\t\t\tc.IndentedJSON(400, Message{Status: 0, Payload: err.Error()})\n\t\t\t\trequestLogger.WithFields(logrus.Fields{\n\t\t\t\t\t\"call\": \"Write\",\n\t\t\t\t}).Errorln(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func SMTPServerSTARTTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\ts.AllowInsecureAuth = true\n\ts.TLSConfig = &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func supportsTLS(ip string) {\n\tabbaPattern := regexp.MustCompile(`(\\w)(\\w)\\2\\1`)\n\tmatches := abbaPattern.FindAllStringSubmatch(ip, -1)\n\tfmt.Println(matches)\n}" ]
[ "0.5666192", "0.56132615", "0.5609014", "0.5520278", "0.55186117", "0.5431673", "0.5428695", "0.5428514", "0.5409775", "0.54090416", "0.53798795", "0.5378907", "0.53322715", "0.53278494", "0.5304138", "0.52890885", "0.52853626", "0.52447397", "0.5224275", "0.52030945", "0.5197189", "0.5182121", "0.5159526", "0.51385653", "0.5111507", "0.5111347", "0.50953436", "0.5086588", "0.5076755", "0.50696504", "0.5062874", "0.5062422", "0.5051744", "0.50323796", "0.50287783", "0.5009796", "0.50060415", "0.49897063", "0.49814054", "0.4978262", "0.49763003", "0.49696022", "0.49684426", "0.49566427", "0.4954396", "0.49528196", "0.4948189", "0.49472007", "0.4943939", "0.49292445", "0.49249828", "0.49190605", "0.49164787", "0.49077693", "0.48997408", "0.48943534", "0.48942816", "0.4892816", "0.48886138", "0.4883893", "0.48686856", "0.48639238", "0.48565012", "0.4842198", "0.48416013", "0.4837114", "0.48275504", "0.48230866", "0.48217383", "0.48171163", "0.48123068", "0.4803571", "0.48028573", "0.4786727", "0.47864377", "0.47844896", "0.47816312", "0.47781816", "0.47749403", "0.4771211", "0.4762976", "0.4760292", "0.47600654", "0.4757002", "0.47548497", "0.47473904", "0.4747035", "0.4743545", "0.47291425", "0.47234747", "0.47168118", "0.47137615", "0.47107354", "0.47095135", "0.47094357", "0.4708463", "0.47071716", "0.4706628", "0.47035673", "0.47029287" ]
0.82453495
0
BenchmarkTLSHandshake measures endtoend TLS handshake performance for fasthttp client and server. It reestablishes new TLS connection per each http request.
func BenchmarkTLSHandshakeRSAWithClientSessionCache(b *testing.B) { bc := &benchConfig{ IsTLS: true, DisableClientSessionCache: false, } benchmarkExt(b, handshakeHandler, bc) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func BenchmarkTLSStreaming(b *testing.B) {\n\tbenchmark(b, streamingHandler, true)\n}", "func BenchmarkPlainHandshake(b *testing.B) {\n\tbenchmark(b, handshakeHandler, false)\n}", "func tcpTLSDo(ctx context.Context, config *tcpTLSConfig) {\n\tconst timeout = 15 * time.Second\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\tdefer config.Wg.Done()\n\tout := &tcpResultPair{\n\t\tAddress: config.Address,\n\t\tEndpoint: config.Endpoint,\n\t\tTCP: model.THTCPConnectResult{},\n\t\tTLS: nil, // means: not measured\n\t}\n\tdefer func() {\n\t\tconfig.Out <- out\n\t}()\n\tol := measurexlite.NewOperationLogger(\n\t\tconfig.Logger,\n\t\t\"TCPConnect %s EnableTLS=%v SNI=%s\",\n\t\tconfig.Endpoint,\n\t\tconfig.EnableTLS,\n\t\tconfig.URLHostname,\n\t)\n\tdialer := config.NewDialer(config.Logger)\n\tdefer dialer.CloseIdleConnections()\n\tconn, err := dialer.DialContext(ctx, \"tcp\", config.Endpoint)\n\tout.TCP.Failure = tcpMapFailure(newfailure(err))\n\tout.TCP.Status = err == nil\n\tdefer measurexlite.MaybeClose(conn)\n\tif err != nil || !config.EnableTLS {\n\t\tol.Stop(err)\n\t\treturn\n\t}\n\t// See https://github.com/ooni/probe/issues/2413 to understand\n\t// why we're using a cached cert pool.\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{\"h2\", \"http/1.1\"},\n\t\tRootCAs: certpool,\n\t\tServerName: config.URLHostname,\n\t}\n\tthx := config.NewTSLHandshaker(config.Logger)\n\ttlsConn, _, err := thx.Handshake(ctx, conn, tlsConfig)\n\tol.Stop(err)\n\tout.TLS = &ctrlTLSResult{\n\t\tServerName: config.URLHostname,\n\t\tStatus: err == nil,\n\t\tFailure: newfailure(err),\n\t}\n\tmeasurexlite.MaybeClose(tlsConn)\n}", "func BenchmarkNewFetchHTTP_Parallel(b *testing.B) {\n\t// This parent benchmark function runs only once as soon as there is another\n\t// sub-benchmark.\n\n\t// Full integration benchmark test which starts a HTTP file server and uses\n\t// TCP to query it on the localhost.\n\tconst backendURL = \"http://127.0.0.1:8283/cart_example.html\"\n\tconst lenCartExampleHTML = 21601\n\n\t// grpc_server_main also reads the file from the disk so stay conistent when\n\t// running benchmarks.\n\tcmd := esitesting.StartProcess(\"go\", \"run\", \"http_server_main.go\")\n\tgo cmd.Wait() // waits forever until killed\n\tdefer cmd.Process.Kill() // kills the go process but not the main startet server\n\tdefer esitesting.KillZombieProcess(\"http_server_main\")\n\n\t// Wait until http server has been started\n\tfor i := 300; ; i = i + 100 {\n\t\td := time.Duration(i) * time.Millisecond\n\t\ttime.Sleep(d)\n\t\t_, err := http.Get(backendURL)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"BenchmarkNewFetchHTTP_Parallel: %s => Sleept %s\\n\", err, d)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\tb.Run(\"Insecure\", func(b *testing.B) {\n\n\t\tfh := backend.NewFetchHTTP(backend.DefaultHTTPTransport)\n\t\trfa := &esitag.ResourceArgs{\n\t\t\tExternalReq: getExternalReqWithExtendedHeaders(),\n\t\t\tURL: backendURL,\n\t\t\tTag: esitag.Config{\n\t\t\t\tTimeout: time.Second,\n\t\t\t\tMaxBodySize: 22001,\n\t\t\t},\n\t\t}\n\n\t\tb.ResetTimer()\n\t\tb.ReportAllocs()\n\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\tvar content []byte\n\t\t\tvar hdr http.Header\n\t\t\tvar err error\n\n\t\t\tfor pb.Next() {\n\t\t\t\thdr, content, err = fh.DoRequest(rfa)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"%+v\", err)\n\t\t\t\t}\n\t\t\t\tif hdr != nil {\n\t\t\t\t\tb.Fatal(\"Header should be nil\")\n\t\t\t\t}\n\t\t\t\tif len(content) != lenCartExampleHTML {\n\t\t\t\t\tb.Fatalf(\"Want %d\\nHave %d\", lenCartExampleHTML, len(content))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "func TestConnectOK(t *testing.T) {\n\tconnectReq := \"CONNECT %s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n\"\n\n\ttestHTTP := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t_, err = conn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestTLS := func(conn net.Conn, originURL *url.URL) {\n\t\treq := fmt.Sprintf(connectReq, originURL.Host, originURL.Host)\n\t\tt.Log(\"\\n\" + req)\n\t\t_, err := conn.Write([]byte(req))\n\t\tif !assert.NoError(t, err, \"should write CONNECT request\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ := http.ReadResponse(bufio.NewReader(conn), nil)\n\t\tioutil.ReadAll(resp.Body)\n\t\tif !assert.Equal(t, 200, resp.StatusCode) {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t// HTTPS-Tunneled HTTPS\n\t\ttunnConn := tls.Client(conn, &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t})\n\t\ttunnConn.Handshake()\n\n\t\t_, err = tunnConn.Write([]byte(tunneledReq))\n\t\tif !assert.NoError(t, err, \"should write tunneled data\") {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tresp, _ = http.ReadResponse(bufio.NewReader(tunnConn), nil)\n\t\tbuf, _ := ioutil.ReadAll(resp.Body)\n\t\tassert.Contains(t, string(buf[:]), originResponse, \"should read tunneled response\")\n\t}\n\n\ttestRoundTrip(t, httpProxyAddr, false, httpOriginServer, testHTTP)\n\ttestRoundTrip(t, tlsProxyAddr, true, httpOriginServer, testHTTP)\n\n\ttestRoundTrip(t, httpProxyAddr, false, tlsOriginServer, testTLS)\n\ttestRoundTrip(t, tlsProxyAddr, true, tlsOriginServer, testTLS)\n}", "func fastBenchmarkHTTP(ctx *fasthttp.RequestCtx) {\n\t_, err := ctx.Write([]byte(\"Retry !\"))\n\tcommonutils.Check(err, \"fastBenchmarkHTTP\")\n}", "func benchmarkConnectionEstablishment(b *testing.B, ctx *context.T, server string) {\n\tvar buf [1]byte\n\tfor i := 0; i < b.N; i++ {\n\t\t// The client and server are running with the same principal\n\t\t// here (since they are both keyed off the same 'ctx').\n\t\tcctx, cancel := context.WithCancel(ctx)\n\t\tcctx, _, err := v23.WithNewClient(cctx)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"Iteration %d/%d: %v\", i, b.N, err)\n\t\t}\n\t\t// Execute an RPC to ensure that the connection is established\n\t\t// by both ends.\n\t\tif _, err := bm.BenchmarkClient(server).Echo(cctx, buf[:]); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tcancel()\n\t}\n}", "func TestHTTPSServer(t *testing.T) {\n\n\tcaCert := path.Join(assetsDir, \"rootCA.crt\")\n\tserverCert := path.Join(assetsDir, \"server.crt\")\n\tserverKey := path.Join(assetsDir, \"server.key\")\n\tclientCert := path.Join(assetsDir, \"client.crt\")\n\tclientKey := path.Join(assetsDir, \"client.key\")\n\tuntrustedClientCert := path.Join(assetsDir, \"other_client.crt\")\n\tuntrustedClientKey := path.Join(assetsDir, \"other_client.key\")\n\n\tauthServer := AuthServer{\n\t\tAddr: \":3457\",\n\t\tSpiffeID: \"spiffe://example.com/service\",\n\t\tCertFile: serverCert,\n\t\tKeyFile: serverKey,\n\t\tCaCert: caCert,\n\t\tCertValidator: validator.SvidValidator{},\n\t}\n\n\t// Run the HTTPS server\n\tgo func() {\n\t\tauthServer.Start()\n\t}()\n\n\t// Create a client with a trusted SpiffeID\n\tclient := createClient(clientCert, clientKey, caCert)\n\n\t// Perform a the authentication request\n\tres, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Errorf(\"Response code was %v; want 200\", res.StatusCode)\n\t}\n\n\t// Create a client with an untrusted SpiffeID\n\tclient = createClient(untrustedClientCert, untrustedClientKey, caCert)\n\n\t// Perform a the authentication request\n\tres2, err := client.Get(\"https://localhost:3457/auth\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res2.Body.Close()\n\n\tif res2.StatusCode != 401 {\n\t\tt.Errorf(\"Response code was %v; want 401\", res.StatusCode)\n\t}\n\n\t// Send signal to shutdown the server\n\tshutdown <- 1\n}", "func doTLS(address string, port string, tcpDialTimeout time.Duration, tlsHandshakeTimeout time.Duration,\n) (*TLSInfo, error) {\n\tvar tlsInfo TLSInfo\n\n\tcfg := constructTLSConfig()\n\n\t// Create a TCP connection to the target address\n\tdailAddress := address\n\tif port != \"\" {\n\t\tdailAddress += \":\" + port\n\t} else {\n\t\tdailAddress += \":443\"\n\t}\n\tconn, err := net.DialTimeout(\"tcp\", dailAddress, tcpDialTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsClient := tls.Client(conn, cfg)\n\n\t// Taken from http.transport.go:persistConn.addTLS\n\terrChannel := make(chan error, 2)\n\tvar timer *time.Timer // for canceling TLS handshake\n\n\t// Create a timer to allow the tls handshake to timeout if tlsHandshakeTimeout is greater than 0\n\tif tlsHandshakeTimeout != 0 {\n\t\ttimer = time.AfterFunc(tlsHandshakeTimeout, func() {\n\t\t\terrChannel <- tlsHandshakeTimeoutError{}\n\t\t})\n\t}\n\n\t// Use the timer to enforce a timeout if tlsHandshakeTimeout is greater than 0\n\tgo func() {\n\t\terr := tlsClient.Handshake()\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t\terrChannel <- err\n\t}()\n\n\t// A TLS error occurred\n\tif tlsHandshakeErr := <-errChannel; tlsHandshakeErr != nil {\n\t\treturn nil, tlsHandshakeErr\n\t}\n\tdefer func(tlsClient *tls.Conn) {\n\t\terr := tlsClient.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error closing TLS connection for address \" + address + \": \" + err.Error())\n\t\t}\n\t}(tlsClient)\n\tconnState := tlsClient.ConnectionState()\n\n\t// Populate a TLSInfo and return it\n\ttlsInfo = TLSInfo{\n\t\tServerName: cfg.ServerName,\n\t\tAddress: address,\n\t\tVersion: connState.Version,\n\t\tCipherSuite: connState.CipherSuite,\n\t\tNegotiatedProtocol: connState.NegotiatedProtocol,\n\t\tPeerCertificates: connState.PeerCertificates,\n\t\tOCSPResponse: connState.OCSPResponse,\n\t}\n\treturn &tlsInfo, nil\n}", "func (t *Tracer) TLSHandshakeStart() {\n\tatomic.CompareAndSwapInt64(&t.tlsHandshakeStart, 0, now())\n}", "func newTLSServer(handler http.Handler) *httptest.Server {\n\tts := httptest.NewUnstartedServer(handler)\n\tts.TLS = new(tls.Config)\n\tts.TLS.NextProtos = []string{\"h2\"}\n\tts.StartTLS()\n\treturn ts\n}", "func TestServerTLS(t *testing.T) {\n\tca1 := newSelfSignedCA(t)\n\tca2 := newSelfSignedCA(t)\n\n\t// trusted certificates with proxy roles.\n\tclient1 := setupClient(t, ca1, ca1, types.RoleProxy)\n\t_, serverDef1 := setupServer(t, \"s1\", ca1, ca1, types.RoleProxy)\n\terr := client1.updateConnections([]types.Server{serverDef1})\n\trequire.NoError(t, err)\n\tstream, _, err := client1.dial([]string{\"s1\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n\n\t// trusted certificates with incorrect server role.\n\tclient2 := setupClient(t, ca1, ca1, types.RoleNode)\n\t_, serverDef2 := setupServer(t, \"s2\", ca1, ca1, types.RoleProxy)\n\terr = client2.updateConnections([]types.Server{serverDef2})\n\trequire.NoError(t, err) // connection succeeds but is in transient failure state\n\t_, _, err = client2.dial([]string{\"s2\"}, &proto.DialRequest{})\n\trequire.Error(t, err)\n\n\t// certificates with correct role from different CAs\n\tclient3 := setupClient(t, ca1, ca2, types.RoleProxy)\n\t_, serverDef3 := setupServer(t, \"s3\", ca2, ca1, types.RoleProxy)\n\terr = client3.updateConnections([]types.Server{serverDef3})\n\trequire.NoError(t, err)\n\tstream, _, err = client3.dial([]string{\"s3\"}, &proto.DialRequest{})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, stream)\n\tstream.CloseSend()\n}", "func TestPlainHTTPServer(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{\n\t\t// The default context uses embedded certs.\n\t\tInsecure: true,\n\t})\n\tdefer s.Stopper().Stop()\n\tts := s.(*TestServer)\n\n\thttpClient, err := s.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thttpURL := \"http://\" + ts.Ctx.HTTPAddr + healthPath\n\tif resp, err := httpClient.Get(httpURL); err != nil {\n\t\tt.Fatalf(\"error requesting health at %s: %s\", httpURL, err)\n\t} else {\n\t\tdefer resp.Body.Close()\n\t\tvar data serverpb.HealthResponse\n\t\tif err := jsonpb.Unmarshal(resp.Body, &data); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\thttpsURL := \"https://\" + ts.Ctx.HTTPAddr + healthPath\n\tif _, err := httpClient.Get(httpsURL); err == nil {\n\t\tt.Fatalf(\"unexpected success fetching %s\", httpsURL)\n\t}\n}", "func tls() {\n\t// init server w/ ctrl+c support\n\tvar s = webfmwk.InitServer(webfmwk.WithCtrlC())\n\n\t// expose /test\n\ts.GET(\"/test\", func(c webfmwk.Context) error {\n\t\treturn c.JSONOk(\"ok\")\n\t})\n\n\t// start asynchronously on :4242\n\ts.StartTLS(\":4242\", webfmwk.TLSConfig{\n\t\tCert: \"/path/to/cert\",\n\t\tKey: \"/path/to/key\",\n\t\tInsecure: false,\n\t})\n\n\t// ctrl+c is handled internaly\n\tdefer s.WaitAndStop()\n}", "func main() {\n\tkvURL, kvCert := mustArgs()\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create credentials\", zap.Error(err))\n\t}\n\n\tkvs, err := keyvault.NewShim(kvURL, cred)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create keyvault client\", zap.Error(err))\n\t}\n\n\ttlsCert, err := kvs.GetLatestTLSCertificate(context.TODO(), kvCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get tls cert from keyvault\", zap.Error(err))\n\t}\n\n\tclientTLSConfig, err := createClientTLSConfig(tlsCert)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not create client tls config\", zap.Error(err))\n\t}\n\n\tserver := http.Server{\n\t\tAddr: serverAddr,\n\t\tHandler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t_, _ = writer.Write([]byte(\"hello\"))\n\t\t}),\n\t\tTLSConfig: &tls.Config{\n\t\t\tCertificates: []tls.Certificate{tlsCert},\n\t\t\tClientCAs: clientTLSConfig.RootCAs,\n\t\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\t},\n\t}\n\n\tgo func() {\n\t\tif err := server.ListenAndServeTLS(\"\", \"\"); err != nil {\n\t\t\tlogger.Fatal(\"could not serve tls\", zap.Error(err))\n\t\t}\n\t}()\n\n\t// wait for a short time to allow server to start\n\ttime.Sleep(time.Second)\n\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: clientTLSConfig,\n\t\t},\n\t}\n\n\taddr := fmt.Sprintf(\"https://%s\", serverAddr)\n\tresp, err := client.Get(addr)\n\tif err != nil {\n\t\tlogger.Fatal(\"could not get response\", zap.String(\"host\", addr), zap.Error(err))\n\t}\n\n\tprintTLSConnState(resp.TLS)\n\n\tbs, _ := io.ReadAll(resp.Body)\n\tlogger.Info(\"response from tls server\", zap.String(\"body bytes\", string(bs)))\n}", "func (ts *TcpServer) StartTlsServer(port string) (err error) {\n\n\tbelogs.Debug(\"StartTlsServer(): tlsserver port:\", port)\n\tcert, err := tls.LoadX509KeyPair(ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver LoadX509KeyPair fail: port:\", port,\n\t\t\t\" tlsPublicCrtFileName, tlsPrivateKeyFileName:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver cert:\", ts.tlsPublicCrtFileName, ts.tlsPrivateKeyFileName)\n\n\trootCrtBytes, err := ioutil.ReadFile(ts.tlsRootCrtFileName)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver ReadFile tlsRootCrtFileName fail, port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\trootCertPool := x509.NewCertPool()\n\tok := rootCertPool.AppendCertsFromPEM(rootCrtBytes)\n\tif !ok {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver AppendCertsFromPEM tlsRootCrtFileName fail,port:\", port,\n\t\t\t\" tlsRootCrtFileName:\", ts.tlsRootCrtFileName, \" len(rootCrtBytes):\", len(rootCrtBytes), err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver AppendCertsFromPEM len(rootCrtBytes):\", len(rootCrtBytes), \" tlsRootCrtFileName:\", ts.tlsRootCrtFileName)\n\n\tclientAuthType := tls.NoClientCert\n\tif ts.tlsVerifyClient {\n\t\tclientAuthType = tls.RequireAndVerifyClientCert\n\t}\n\tbelogs.Debug(\"StartTlsServer(): tlsserver clientAuthType:\", clientAuthType)\n\n\t// https://stackoverflow.com/questions/63676241/how-to-set-setkeepaliveperiod-on-a-tls-conn\n\tsetTCPKeepAlive := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\t// Check that the underlying connection really is TCP.\n\t\tif tcpConn, ok := clientHello.Conn.(*net.TCPConn); ok {\n\t\t\ttcpConn.SetKeepAlive(true)\n\t\t\ttcpConn.SetKeepAlivePeriod(time.Second * 300)\n\t\t\tbelogs.Debug(\"StartTlsServer(): tlsserver SetKeepAlive:\")\n\t\t}\n\t\t// Make sure to return nil, nil to let the caller fall back on the default behavior.\n\t\treturn nil, nil\n\t}\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tClientAuth: clientAuthType,\n\t\tRootCAs: rootCertPool,\n\t\tInsecureSkipVerify: false,\n\t\tGetConfigForClient: setTCPKeepAlive,\n\t}\n\tlistener, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver Listen fail, port:\", port, err)\n\t\treturn err\n\t}\n\tbelogs.Debug(\"StartTlsServer(): Listen ok, port:\", port)\n\n\t// get tcpListener\n\tts.tcpListener, err = NewFromTlsListener(listener)\n\tif err != nil {\n\t\tbelogs.Error(\"StartTlsServer(): tlsserver NewFromTlsListener fail, port: \", port, err)\n\t\treturn err\n\t}\n\tbelogs.Info(\"StartTlsServer(): tlsserver create server ok, port:\", port, \" will accept client\")\n\n\tgo ts.waitBusinessToConnMsg()\n\n\t// wait new conn\n\tts.acceptNewConn()\n\treturn nil\n}", "func TestProbeHTTPSTimeout(t *testing.T) {\n\tserver, _, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Fprintln(w, \"Hello world\")\n\t})\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err == nil {\n\t\tt.Fatalf(\"Expected error but returned error was nil\")\n\t}\n}", "func BenchmarkDialTCP(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tDialTCP(TEST_HOST, TEST_USER, TEST_PASSWD, TEST_DBNAME)\n\t}\n}", "func TestProbeHTTPS(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func HTTP2ALPNTLSWrap(conn *net.TCPConn, cfg *tls.Config, tFunc TLSWrapperFunc) (*tls.Conn, error) {\n\tprotoCfg := cfg.Clone()\n\t// TODO: append here\n\tprotoCfg.NextProtos = []string{http2.NextProtoTLS}\n\tprotoCfg.MinVersion = tls.VersionTLS12\n\n\tvar tlsConn *tls.Conn\n\tfor {\n\t\tif err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConn = tFunc(conn, protoCfg)\n\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\t\tif netErr.Timeout() || netErr.Temporary() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := conn.SetDeadline(time.Time{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\t}\n\n\t// Check if we're creating a client conn before checking verification\n\tif isTLSClient(tFunc) {\n\t\tif !protoCfg.InsecureSkipVerify {\n\t\t\tif err := tlsConn.VerifyHostname(protoCfg.ServerName); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tstate := tlsConn.ConnectionState()\n\tif p := state.NegotiatedProtocol; p != http2.NextProtoTLS {\n\t\treturn nil, fmt.Errorf(\"http2: unexpected ALPN protocol %q; want %q\", p, http2.NextProtoTLS)\n\t}\n\n\tif !state.NegotiatedProtocolIsMutual {\n\t\treturn nil, fmt.Errorf(\"http2: could not negotiate protocol mutually\")\n\t}\n\n\treturn tlsConn, nil\n}", "func Benchmark_Ctx_Protocol(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar res string\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tres = c.Protocol()\n\t}\n\tutils.AssertEqual(b, \"http\", res)\n}", "func ServerHandshake(c net.Conn, hashes []hash.HashPair, cryptoOptions *crypto.Options) (conn net.Conn, result HandshakeResult, init []byte, err error) {\n\tconn = c\n\terr = conn.SetDeadline(time.Now().Add(90 * time.Second))\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := make([]byte, 20+8+20+20)\n\tvar n int\n\tn, err = io.ReadAtLeast(conn, buf, len(header))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuf = buf[:n]\n\n\tok := checkHeader(buf)\n\tif ok && cryptoOptions.ForceCryptoHandshake {\n\t\terr = errors.New(\"plaintext handshake forbidden\")\n\t\treturn\n\t}\n\n\tvar skey hash.Hash\n\tif !ok && cryptoOptions.AllowCryptoHandshake {\n\t\tskeys := make([][]byte, len(hashes))\n\t\tfor i := range hashes {\n\t\t\tskeys[i] = hashes[i].First\n\t\t}\n\t\tvar ia []byte\n\t\tconn, skey, ia, err =\n\t\t\tcrypto.ServerHandshake(conn, buf, skeys, cryptoOptions)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbuf = ia\n\t\tbuf, err = readMore(conn, buf, 20, 20+8+20+20)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tok = checkHeader(buf)\n\t}\n\n\tif !ok {\n\t\terr = ErrBadHandshake\n\t\treturn\n\t}\n\n\tbuf = buf[20:]\n\tbuf, err = readMore(conn, buf, 8+20, 8+20+20)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif buf[7]&0x01 != 0 {\n\t\tresult.Dht = true\n\t}\n\tif buf[7]&0x04 != 0 {\n\t\tresult.Fast = true\n\t}\n\tif buf[5]&0x10 != 0 {\n\t\tresult.Extended = true\n\t}\n\tbuf = buf[8:]\n\n\thsh := hash.Hash(make([]byte, 20))\n\tcopy(hsh, buf)\n\tbuf = buf[20:]\n\n\tif skey != nil && !skey.Equal(hsh) {\n\t\terr = errors.New(\"crypto hash mismatch\")\n\t\treturn\n\t}\n\n\tfound := false\n\tvar h hash.HashPair\n\tfor _, h = range hashes {\n\t\tif hsh.Equal(h.First) {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\terr = ErrUnknownTorrent\n\t\treturn\n\t}\n\n\tresult.Hash = hsh\n\n\thndshk := handshake(result.Hash, h.Second)\n\t_, err = conn.Write(hndshk)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuf, err = readMore(conn, buf, 20, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult.Id = make([]byte, 20)\n\tcopy(result.Id, buf)\n\tbuf = buf[20:]\n\n\tif len(buf) > 0 {\n\t\tinit = make([]byte, len(buf))\n\t\tcopy(init, buf)\n\t}\n\n\treturn\n}", "func httpsServer(\n\tserverUsername string,\n\tserverPassword string,\n\ttlsCert string,\n\ttlsKey string,\n) (*httptest.Server, error) {\n\ts, err := testServer(serverUsername, serverPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tMinVersion: tls.VersionTLS12,\n\t}\n\ts.TLS = config\n\n\ts.StartTLS()\n\treturn s, nil\n}", "func TestProbeHTTPSServerName(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tu, err := url.Parse(server.URL)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t\tServerName: u.Hostname(),\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), \"https://localhost:\"+u.Port(), module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TestUpdateTLS_TLSToNone(t *testing.T) {\n\ttestCases := []*TLSUpdateCase{\n\t\tNewTLSUpdateCase(t, protocol.HTTP1, util.NewHTTPServer(t, nil)),\n\t\t// NewTLSUpdateCase(t, protocol.HTTP2, util.NewUpstreamHTTP2(t, appaddr, nil)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(true)\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tverify()\n\t\t// update to non-tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{v2.TLSConfig{}}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tverify()\n\t\t// finish\n\t\ttc.FinishCase()\n\t}\n\n}", "func TestPreservesTLS(t *testing.T) {\n\tsrv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"ok\"))\n\t})\n\tdefer srv.Close()\n\n\t// forwarder will proxy the request to whatever destination\n\tfwd, err := forward.New()\n\trequire.NoError(t, err)\n\n\tvar cs *tls.ConnectionState\n\t// this is our redirect to server\n\trdr := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tcs = req.TLS\n\t\treq.URL = testutils.ParseURI(srv.URL)\n\t\tfwd.ServeHTTP(w, req)\n\t})\n\n\t// stream handler will forward requests to redirect\n\tst, err := New(rdr)\n\trequire.NoError(t, err)\n\n\tproxy := httptest.NewUnstartedServer(st)\n\tproxy.StartTLS()\n\tdefer proxy.Close()\n\n\tre, _, err := testutils.Get(proxy.URL)\n\trequire.NoError(t, err)\n\tassert.Equal(t, http.StatusOK, re.StatusCode)\n\tassert.NotNil(t, cs)\n}", "func TestProbeHTTPSClientAuth(t *testing.T) {\n\tserver, certPEM, keyPEM, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\t// Configure client auth on the server\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(certPEM)\n\n\tserver.TLS.ClientAuth = tls.RequireAndVerifyClientCert\n\tserver.TLS.RootCAs = certPool\n\tserver.TLS.ClientCAs = certPool\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\t// Create cert file\n\tcertFile, err := test.WriteFile(\"cert.pem\", certPEM)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer os.Remove(certFile)\n\n\t// Create key file\n\tkeyFile, err := test.WriteFile(\"key.pem\", keyPEM)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer os.Remove(keyFile)\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tCertFile: certFile,\n\t\t\tKeyFile: keyFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TestSSLEnforcement(t *testing.T) {\n\ts := StartTestServer(t)\n\tdefer s.Stop()\n\ttestCases := []struct {\n\t\tmethod, key string\n\t\tcertsStatus int // Status code for https with client certs.\n\t\tnoCertsStatus int // Status code for https without client certs.\n\t}{\n\t\t// /ui/: basic file server: no auth.\n\t\t{\"GET\", \"/index.html\", http.StatusOK, http.StatusOK},\n\n\t\t// /_admin/: server.adminServer: no auth.\n\t\t{\"GET\", healthPath, http.StatusOK, http.StatusOK},\n\n\t\t// /debug/: server.adminServer: no auth.\n\t\t{\"GET\", debugEndpoint + \"vars\", http.StatusOK, http.StatusOK},\n\n\t\t// /_status/: server.statusServer: no auth.\n\t\t{\"GET\", statusKeyPrefix, http.StatusOK, http.StatusOK},\n\n\t\t// /kv/db/: kv.DBServer. These are proto reqs, but we can at least get past auth.\n\t\t{\"GET\", kv.DBPrefix + \"Get\", http.StatusBadRequest, http.StatusUnauthorized},\n\n\t\t// /ts/: ts.Server.\n\t\t{\"GET\", ts.URLPrefix, http.StatusNotFound, http.StatusUnauthorized},\n\t}\n\n\t// HTTPS with client certs.\n\tcertsContext := testutils.NewTestBaseContext()\n\tclient, err := certsContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", certsContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"[%d]: error issuing request: %s\", tcNum, err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != tc.certsStatus {\n\t\t\tt.Errorf(\"[%d]: expected status code %d, got %d\", tcNum, tc.certsStatus, resp.StatusCode)\n\t\t}\n\t}\n\n\t// HTTPS without client certs.\n\tnoCertsContext := testutils.NewTestBaseContext()\n\tnoCertsContext.Certs = \"\"\n\tclient, err = noCertsContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", noCertsContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"[%d]: error issuing request: %s\", tcNum, err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != tc.noCertsStatus {\n\t\t\tt.Errorf(\"[%d]: expected status code %d, got %d\", tcNum, tc.noCertsStatus, resp.StatusCode)\n\t\t}\n\t}\n\n\t// Plain http.\n\tinsecureContext := testutils.NewTestBaseContext()\n\tinsecureContext.Insecure = true\n\tclient, err = insecureContext.GetHTTPClient()\n\tif err != nil {\n\t\tt.Fatalf(\"error initializing http client: %s\", err)\n\t}\n\tfor tcNum, tc := range testCases {\n\t\tresp, err := doHTTPReq(t, client, tc.method,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", insecureContext.RequestScheme(), s.ServingAddr(), tc.key))\n\t\t// We're talking http to a https server. We don't even make it to a response.\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tt.Errorf(\"[%d]: unexpected success\", tcNum)\n\t\t}\n\t}\n}", "func TestDynamicGrpcBackendTLS(t *testing.T) {\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tdesc string\n\t\tclientProtocol string\n\t\tmethodOrUrl string\n\t\tmtlsCertFile string\n\t\tuseWrongBackendCert bool\n\t\theader http.Header\n\t\twantResp string\n\t\twantError string\n\t}{\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http client calling gRPCs remote backend succeed\",\n\t\t\tclientProtocol: \"http\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantResp: `{\"id\":\"200\",\"theme\":\"Classic\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"Http2 client calling gRPCs remote backend fail with incorrect cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tuseWrongBackendCert: true,\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"gRPC client calling gRPCs remote backend with mTLS succeed\",\n\t\t\tclientProtocol: \"grpc\",\n\t\t\tmethodOrUrl: \"GetShelf\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ServerCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantResp: `{\"id\":\"100\",\"theme\":\"Kids\"}`,\n\t\t},\n\t\t{\n\t\t\tdesc: \"HTTP2 client calling gRPCs remote backend through mTLS failed with incorrect client root cert\",\n\t\t\tclientProtocol: \"http2\",\n\t\t\tmethodOrUrl: \"/v1/shelves/200?key=api-key\",\n\t\t\tmtlsCertFile: platform.GetFilePath(platform.ProxyCert),\n\t\t\theader: http.Header{\"x-api-key\": []string{\"api-key\"}},\n\t\t\twantError: \"503 Service Unavailable\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\targs := utils.CommonArgs()\n\t\tt.Run(tc.desc, func(t *testing.T) {\n\t\t\ts := env.NewTestEnv(platform.TestDynamicGrpcBackendTLS, platform.GrpcBookstoreRemote)\n\t\t\tdefer s.TearDown(t)\n\t\t\ts.UseWrongBackendCertForDR(tc.useWrongBackendCert)\n\t\t\tif tc.mtlsCertFile != \"\" {\n\t\t\t\ts.SetBackendMTLSCert(tc.mtlsCertFile)\n\t\t\t\targs = append(args, fmt.Sprintf(\"--ssl_backend_client_cert_path=%v\", platform.GetFilePath(platform.TestDataFolder)))\n\t\t\t}\n\n\t\t\tif err := s.Setup(args); err != nil {\n\t\t\t\tt.Fatalf(\"fail to setup test env, %v\", err)\n\t\t\t}\n\t\t\taddr := fmt.Sprintf(\"%v:%v\", platform.GetLoopbackAddress(), s.Ports().ListenerPort)\n\t\t\tresp, err := bsclient.MakeCall(tc.clientProtocol, addr, \"GET\", tc.methodOrUrl, \"\", tc.header)\n\t\t\tif tc.wantError != \"\" && (err == nil || !strings.Contains(err.Error(), tc.wantError)) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %v\", tc.desc, tc.wantError, err)\n\t\t\t}\n\n\t\t\tif tc.wantError == \"\" && err != nil {\n\t\t\t\tt.Errorf(\"Test (%s): got unexpected error: %s\", tc.desc, resp)\n\t\t\t}\n\n\t\t\tif !strings.Contains(resp, tc.wantResp) {\n\t\t\t\tt.Errorf(\"Test (%s): failed, expected: %s, got: %s\", tc.desc, tc.wantResp, resp)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestUpdateTLS_NoneToTLS(t *testing.T) {\n\ttestCases := []*TLSUpdateCase{\n\t\tNewTLSUpdateCase(t, protocol.HTTP1, util.NewHTTPServer(t, nil)),\n\t\t// NewTLSUpdateCase(t, protocol.HTTP2, util.NewUpstreamHTTP2(t, appaddr, nil)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(false)\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tt.Logf(\"verify non-tls\")\n\t\tverify()\n\t\t// update to tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{DefaultTLSConfig}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tt.Logf(\"verify tls\")\n\t\tverify()\n\t\ttc.FinishCase()\n\n\t}\n}", "func TestClientServer(t *testing.T) {\n\t// Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t// Create the certs and configs.\n\tCreateCA(root)\n\n\tCreateSignedCert(root, CA, \"01\", \"servers\", \"Servers CA\")\n\tCreateSignedCert(root, \"servers\", \"01\", \"server-instance\", \"server.example.com\")\n\n\tCreateSignedCert(root, CA, \"02\", \"clients\", \"Clients CA\")\n\tCreateSignedCert(root, \"clients\", \"01\", \"client-instance\", \"Client Instance\")\n\tserverConfig, err := vttls.ServerConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"clients-cert.pem\"))\n\tif err != nil {\n\t\tt.Fatalf(\"TLSServerConfig failed: %v\", err)\n\t}\n\tclientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"client-instance-cert.pem\"),\n\t\tpath.Join(root, \"client-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\t// Create a TLS server listener.\n\tlistener, err := tls.Listen(\"tcp\", \":0\", serverConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"Listen failed: %v\", err)\n\t}\n\taddr := listener.Addr().String()\n\tdefer listener.Close()\n\n\twg := sync.WaitGroup{}\n\n\t//\n\t// Positive case: accept on server side, connect a client, send data.\n\t//\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tclientConn, err := tls.Dial(\"tcp\", addr, clientConfig)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Dial failed: %v\", err)\n\t\t}\n\n\t\tclientConn.Write([]byte{42})\n\t\tclientConn.Close()\n\t}()\n\n\tserverConn, err := listener.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"Accept failed: %v\", err)\n\t}\n\n\tresult := make([]byte, 1)\n\tif n, err := serverConn.Read(result); (err != nil && err != io.EOF) || n != 1 {\n\t\tt.Fatalf(\"Read failed: %v %v\", n, err)\n\t}\n\tif result[0] != 42 {\n\t\tt.Fatalf(\"Read returned wrong result: %v\", result)\n\t}\n\tserverConn.Close()\n\n\twg.Wait()\n\n\t//\n\t// Negative case: connect a client with wrong cert (using the\n\t// server cert on the client side).\n\t//\n\n\tbadClientConfig, err := vttls.ClientConfig(\n\t\tpath.Join(root, \"server-instance-cert.pem\"),\n\t\tpath.Join(root, \"server-instance-key.pem\"),\n\t\tpath.Join(root, \"servers-cert.pem\"),\n\t\t\"server.example.com\")\n\tif err != nil {\n\t\tt.Fatalf(\"TLSClientConfig failed: %v\", err)\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\t// We expect the Accept to work, but the first read to fail.\n\t\tdefer wg.Done()\n\t\tserverConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Connection failed: %v\", err)\n\t\t}\n\n\t\t// This will fail.\n\t\tresult := make([]byte, 1)\n\t\tif n, err := serverConn.Read(result); err == nil {\n\t\t\tfmt.Printf(\"Was able to read from server: %v\\n\", n)\n\t\t}\n\t\tserverConn.Close()\n\t}()\n\n\t// When using TLS 1.2, the Dial will fail.\n\t// With TLS 1.3, the Dial will succeed and the first Read will fail.\n\tclientConn, err := tls.Dial(\"tcp\", addr, badClientConfig)\n\tif err != nil {\n\t\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t\t}\n\t\treturn\n\t}\n\tdata := make([]byte, 1)\n\t_, err = clientConn.Read(data)\n\tif err == nil {\n\t\tt.Fatalf(\"Dial or first Read was expected to fail\")\n\t}\n\tif !strings.Contains(err.Error(), \"bad certificate\") {\n\t\tt.Errorf(\"Wrong error returned: %v\", err)\n\t}\n}", "func TestProbeHTTPSHTTP(t *testing.T) {\n\tserver := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"Hello world\")\n\t}))\n\tserver.Start()\n\tdefer server.Close()\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, config.Module{}, registry); err == nil {\n\t\tt.Fatalf(\"expected error, but err was nil\")\n\t}\n}", "func handshake(conn net.Conn, validUri string) (res http.Response, retErr error) {\n var b64ConnKey string\n\n // Properly set the status code text on exit\n defer func() {\n res.Status = http.StatusText(res.StatusCode)\n }()\n\n // Set initial response, just in case...\n res.StatusCode = http.StatusForbidden\n res.Proto = \"HTTP/1.0\"\n res.ProtoMajor = 1\n res.ProtoMinor = 0\n\n req, err := http.ReadRequest(bufio.NewReader(conn))\n if err != nil {\n retErr = errors.Wrap(err, \"Failed to receive client handshake\")\n return\n }\n\n res.Proto = req.Proto\n res.ProtoMajor = req.ProtoMajor\n res.ProtoMinor = req.ProtoMinor\n\n // 4.2.1 Reading the Client's Opening Handshake\n\n // 1. Check that it's a HTTP/1.1 or higher GET\n // (ignore \"Request-URI\" but check its presence)\n if !strings.HasPrefix(req.Proto, \"HTTP/\") {\n retErr = errors.New(fmt.Sprintf(\"Non HTTP request: '%s'\", req.Proto))\n return\n } else if req.ProtoMajor == 1 && req.ProtoMinor < 1 ||\n req.ProtoMajor < 1 {\n\n retErr = errors.New(\"Non HTTP/1.1 or higher\")\n return\n } else if req.Method != \"GET\" {\n retErr = errors.New(\"Non GET request\")\n return\n } else if req.RequestURI == \"\" {\n retErr = errors.New(\"Missing RequestURI in request\")\n return\n } else if req.RequestURI != validUri {\n retErr = errors.New(\"Invalid RequestURI\")\n return\n }\n\n // 2. Check for a |Host| header with server's authority\n if host := req.Header.Get(\"Host\"); len(host) == 0 {\n retErr = errors.New(\"Missing |Host| header field\")\n if Strict {\n return\n } else {\n fmt.Printf(\" Ignoring: %s\\n\", retErr.Error())\n retErr = nil\n }\n }\n\n // 3. Check for an |Upgrade| header == \"websocket\"\n if want, got := \"websocket\", req.Header.Get(\"Upgrade\"); want != got {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Upgrade| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 4. Check for a |Connection| header == \"Upgrade\"\n if want, got := \"Upgrade\", req.Header.Get(\"Connection\"); !strings.Contains(got, want) {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Connection| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 5. Check for a |Sec-WebSocket-Key| with the base-64 key\n if b64ConnKey = req.Header.Get(\"Sec-WebSocket-Key\"); len(b64ConnKey) == 0{\n retErr = errors.New(\"Missing |Sec-WebSocket-Key| header field\")\n return\n }\n\n // 6..10 are optional (and, therefore, ignored)\n\n // 4.2.2 Sending the Server's Opening Handshake\n\n res.Header = make (http.Header)\n\n // 1. Connection isn't HTTPS, so ignore it\n // 2. Stuff that the server can do... ignore (as it isn't a MUST)\n // 3. \"The server MAY...\": NOPE\n // 4. Maybe later\n\n // 5. Set fields required to accept the connection\n\n // 5.1 Set status as Switching Protocols\n res.StatusCode = http.StatusSwitchingProtocols\n\n // 5.2 Set |Upgrade| = \"websocket\"\n res.Header.Set(\"Upgrade\", \"websocket\")\n\n // 5.3 Set |Connection| = \"Upgrade\"\n res.Header.Set(\"Connection\", \"Upgrade\")\n\n // 5.4 Set |Sec-WebSocket-Accept| with the base_64(SHA_1(key+UIGD))\n serverKey := calculateServerResponseKey(b64ConnKey)\n res.Header.Set(\"Sec-WebSocket-Accept\", serverKey)\n\n // 5.5 Later\n // 5.6 Later\n\n return\n}", "func tlsConnect() (httpDoer, error) {\n\treturn fetcher.TLSClient(nil, nil)\n}", "func (s *ServerSuite) TestServerHTTPSAutoCert(c *C) {\n\tvar req *http.Request\n\te := testutils.NewHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\treq = r\n\t\tw.Write([]byte(\"hi https\"))\n\t})\n\tdefer e.Close()\n\n\t// Start an ACME Stub server locally that serves certificates for \"example.org\"\n\tman := &autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t}\n\turl, finish := startACMEServerStub(c, man, \"example.org\", \"\")\n\tdefer finish()\n\n\t// Create a Host definition for example.org, with an AutoCert setting that points to local stub URL\n\t// (obtained from the stub start above)\n\tb := MakeBatch(Batch{\n\t\tHost: \"example.org\",\n\t\tAddr: \"localhost:41000\",\n\t\tRoute: `Path(\"/\")`,\n\t\tURL: e.URL,\n\t\tProtocol: engine.HTTPS,\n\t\tAutoCert: &engine.AutoCertSettings{\n\t\t\tDirectoryURL: url,\n\t\t},\n\t})\n\n\tc.Assert(s.mux.UpsertHost(b.H), IsNil)\n\tc.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)\n\tc.Assert(s.mux.UpsertFrontend(b.F), IsNil)\n\tc.Assert(s.mux.UpsertListener(b.L), IsNil)\n\n\tc.Assert(s.mux.Start(), IsNil)\n\n\t// Attempt to connect to the Host over HTTPS which will validate that it was able to generate a cert\n\t// over ACME against our local stub. This is an SNI-based host-name.\n\tc.Assert(GETResponse(c, b.FrontendURL(\"/\"), testutils.Host(\"example.org\")), Equals, \"hi https\")\n\t// Make sure that we see right proto\n\tc.Assert(req.Header.Get(\"X-Forwarded-Proto\"), Equals, \"https\")\n}", "func (self *Proxy) StartTLS(cert string, key string) error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTPs client request at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServeTLS(cert, key)\n}", "func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) (err error) {\n\n\ttlsConfig := &tls.Config{\n\t\tNextProtos: []string{http2NextProtoTLS, http2Rev14, http11},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\n\ttlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\tl, err := kmsnet.NewTCPListenerNoShutdown(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsListener := tls.NewListener(l, tlsConfig)\n\n\ts := &http.Server{Addr: tlsListener.Addr().String(), Handler: handler, TLSConfig: tlsConfig}\n\n\tserver := &serverConnState{\n\t\tServer: s,\n\t\tl: tlsListener,\n\t\tidleConns: make(map[net.Conn]struct{}),\n\t\tactive: make(chan net.Conn),\n\t\tidle: make(chan net.Conn),\n\t\tclosed: make(chan net.Conn),\n\t\tshutdown: make(chan struct{}),\n\t}\n\n\tserver.handleConnState()\n\n\terr = server.Serve(server.l)\n\n\t// wait for process shutdown to complete or timeout.\n\t<-kms.ShutdownComplete()\n\n\treturn err\n}", "func handshakeConnect(u *url.URL, c net.Conn) error {\r\n\th := u.Host\r\n\tif hasPort(h) {\r\n\t\th = h[:strings.LastIndex(h, \":\")]\r\n\t}\r\n\tcfg := &tls.Config{ServerName: h}\r\n\ttlsConn := tls.Client(c, cfg)\r\n\treturn tlsConn.Handshake()\r\n}", "func getServer(mux *http.ServeMux) (server *http.Server) {\n\tvar certdir string\n\tif config.CertDir != \"\" {\n\t\tcertdir = config.CertDir\n\t} else {\n\t\tcertdir = config.BaseDir\n\t}\n\n\tm := autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tCache: autocert.DirCache(certdir),\n\t\tHostPolicy: autocert.HostWhitelist(config.DomainNames...),\n\t\tEmail: config.Email,\n\t}\n\ttlsConf := &tls.Config{\n\t\tRand: rand.Reader,\n\t\tTime: time.Now,\n\t\tNextProtos: []string{acme.ALPNProto, \"http/1.1\"}, // add http2.NextProtoTLS?\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tGetCertificate: m.GetCertificate,\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t},\n\t}\n\tserver = &http.Server{\n\t\tAddr: config.TLSAddressPort,\n\t\tHandler: mux,\n\t\tTLSConfig: tlsConf,\n\t\t// https://blog.bracebin.com/achieving-perfect-ssl-labs-score-with-go\n\t\tTLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),\n\t}\n\t// Handle ACME \"http-01\" challenge responses on external port 80.\n\tgo http.ListenAndServe(config.AddressPort, m.HTTPHandler(nil))\n\treturn\n}", "func ListenAndServeTLS(opt *Options, httpHandler http.Handler, grpcHandler *grpc.Server) error {\n\tif opt == nil {\n\t\topt = defaultOptions\n\t} else {\n\t\topt.applyDefaults()\n\t}\n\tvar cert *tls.Certificate\n\tvar err error\n\tif opt.Cert != \"\" && opt.Key != \"\" {\n\t\tcert, err = decodeCertificate(opt.Cert, opt.Key)\n\t} else {\n\t\tcert, err = readCertificateFile(opt.CertFile, opt.KeyFile)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: failed loading x509 certificate: %v\", err)\n\t}\n\tconfig, err := newDefaultTLSConfig(cert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\tln, err := net.Listen(\"tcp\", opt.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tln = tls.NewListener(ln, config)\n\n\tvar h http.Handler\n\tif grpcHandler == nil {\n\t\th = httpHandler\n\t} else {\n\t\th = grpcHandlerFunc(grpcHandler, httpHandler)\n\t}\n\tsublogger := log.With().Str(\"addr\", opt.Addr).Logger()\n\n\t// Set up the main server.\n\tserver := &http.Server{\n\t\tReadHeaderTimeout: 10 * time.Second,\n\t\tReadTimeout: 30 * time.Second,\n\t\t// WriteTimeout is set to 0 for streaming replies\n\t\tWriteTimeout: 0,\n\t\tIdleTimeout: 5 * time.Minute,\n\t\tTLSConfig: config,\n\t\tHandler: h,\n\t\tErrorLog: stdlog.New(&log.StdLogWrapper{Logger: &sublogger}, \"\", 0),\n\t}\n\n\treturn server.Serve(ln)\n}", "func OptTLSHandshakeTimeout(d time.Duration) Option {\n\treturn func(r *Request) error {\n\t\tif r.Client == nil {\n\t\t\tr.Client = &http.Client{}\n\t\t}\n\t\tif r.Client.Transport == nil {\n\t\t\tr.Client.Transport = &http.Transport{}\n\t\t}\n\t\tif typed, ok := r.Client.Transport.(*http.Transport); ok {\n\t\t\ttyped.TLSHandshakeTimeout = d\n\t\t}\n\t\treturn nil\n\t}\n}", "func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, passCount, length int) ([]map[string]interface{}, error) {\n\tbenchmarks := make([]requestBenchmark, len(setups))\n\tfor i, setup := range setups {\n\t\tif t, ok := setup[\"type\"].(string); ok {\n\t\t\tgetInt := func(field string, def int) int {\n\t\t\t\tif value, ok := setup[field].(float64); ok {\n\t\t\t\t\treturn int(value)\n\t\t\t\t}\n\t\t\t\treturn def\n\t\t\t}\n\t\t\tgetBool := func(field string, def bool) bool {\n\t\t\t\tif value, ok := setup[field].(bool); ok {\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn def\n\t\t\t}\n\t\t\tswitch t {\n\t\t\tcase \"header\":\n\t\t\t\tbenchmarks[i] = &benchmarkBlockHeaders{\n\t\t\t\t\tamount: getInt(\"amount\", 1),\n\t\t\t\t\tskip: getInt(\"skip\", 1),\n\t\t\t\t\tbyHash: getBool(\"byHash\", false),\n\t\t\t\t\treverse: getBool(\"reverse\", false),\n\t\t\t\t}\n\t\t\tcase \"body\":\n\t\t\t\tbenchmarks[i] = &benchmarkBodiesOrReceipts{receipts: false}\n\t\t\tcase \"receipts\":\n\t\t\t\tbenchmarks[i] = &benchmarkBodiesOrReceipts{receipts: true}\n\t\t\tcase \"proof\":\n\t\t\t\tbenchmarks[i] = &benchmarkProofsOrCode{code: false}\n\t\t\tcase \"code\":\n\t\t\t\tbenchmarks[i] = &benchmarkProofsOrCode{code: true}\n\t\t\tcase \"cht\":\n\t\t\t\tbenchmarks[i] = &benchmarkHelperTrie{\n\t\t\t\t\tbloom: false,\n\t\t\t\t\treqCount: getInt(\"amount\", 1),\n\t\t\t\t}\n\t\t\tcase \"bloom\":\n\t\t\t\tbenchmarks[i] = &benchmarkHelperTrie{\n\t\t\t\t\tbloom: true,\n\t\t\t\t\treqCount: getInt(\"amount\", 1),\n\t\t\t\t}\n\t\t\tcase \"txSend\":\n\t\t\t\tbenchmarks[i] = &benchmarkTxSend{}\n\t\t\tcase \"txStatus\":\n\t\t\t\tbenchmarks[i] = &benchmarkTxStatus{}\n\t\t\tdefault:\n\t\t\t\treturn nil, ErrUnknownBenchmarkType\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, ErrUnknownBenchmarkType\n\t\t}\n\t}\n\trs := api.server.protocolManager.runBenchmark(benchmarks, passCount, time.Millisecond*time.Duration(length))\n\tresult := make([]map[string]interface{}, len(setups))\n\tfor i, r := range rs {\n\t\tres := make(map[string]interface{})\n\t\tif r.err == nil {\n\t\t\tres[\"totalCount\"] = r.totalCount\n\t\t\tres[\"avgTime\"] = r.avgTime\n\t\t\tres[\"maxInSize\"] = r.maxInSize\n\t\t\tres[\"maxOutSize\"] = r.maxOutSize\n\t\t} else {\n\t\t\tres[\"error\"] = r.err.Error()\n\t\t}\n\t\tresult[i] = res\n\t}\n\treturn result, nil\n}", "func TestProbeHTTPSProxy(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tproxyServer, err := test.SetupHTTPProxyServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tproxyServer.Start()\n\tdefer proxyServer.Close()\n\n\tproxyURL, err := url.Parse(proxyServer.URL)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tbadProxyURL, err := url.Parse(\"http://localhost:6666\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t\tHTTPS: config.HTTPSProbe{\n\t\t\t// Test with a bad proxy url first\n\t\t\tProxyURL: config.URL{URL: badProxyURL},\n\t\t},\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err == nil {\n\t\tt.Fatalf(\"expected error but err was nil\")\n\t}\n\n\t// Test with the proxy url, this shouldn't return an error\n\tmodule.HTTPS.ProxyURL = config.URL{URL: proxyURL}\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), server.URL, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TLS(hostname string) ProbeFunc {\n\treturn func(ctx context.Context) error {\n\t\treturn probeTLS(ctx, hostname)\n\t}\n}", "func httpsIncus(ctx context.Context, requestURL string, args *ConnectionArgs) (InstanceServer, error) {\n\t// Use empty args if not specified\n\tif args == nil {\n\t\targs = &ConnectionArgs{}\n\t}\n\n\thttpBaseURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctxConnected, ctxConnectedCancel := context.WithCancel(context.Background())\n\n\t// Initialize the client struct\n\tserver := ProtocolIncus{\n\t\tctx: ctx,\n\t\thttpCertificate: args.TLSServerCert,\n\t\thttpBaseURL: *httpBaseURL,\n\t\thttpProtocol: \"https\",\n\t\thttpUserAgent: args.UserAgent,\n\t\tctxConnected: ctxConnected,\n\t\tctxConnectedCancel: ctxConnectedCancel,\n\t\teventConns: make(map[string]*websocket.Conn),\n\t\teventListeners: make(map[string][]*EventListener),\n\t}\n\n\tif shared.StringInSlice(args.AuthType, []string{\"oidc\"}) {\n\t\tserver.RequireAuthenticated(true)\n\t}\n\n\t// Setup the HTTP client\n\thttpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy, args.TransportWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args.CookieJar != nil {\n\t\thttpClient.Jar = args.CookieJar\n\t}\n\n\tserver.http = httpClient\n\tif args.AuthType == \"oidc\" {\n\t\tserver.setupOIDCClient(args.OIDCTokens)\n\t}\n\n\t// Test the connection and seed the server information\n\tif !args.SkipGetServer {\n\t\t_, _, err := server.GetServer()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &server, nil\n}", "func (c *TLSUpdateCase) RequestTLS(isTLS bool, n int, interval int) {\n\tvar call func() error\n\tswitch c.Protocol {\n\tcase protocol.HTTP1:\n\t\ttr := http.DefaultTransport.(*http.Transport)\n\t\tpool := x509.NewCertPool()\n\t\tpool.AppendCertsFromPEM([]byte(caPEM))\n\t\ttr.TLSClientConfig = &tls.Config{\n\t\t\tRootCAs: pool,\n\t\t}\n\t\thttpClient := http.Client{\n\t\t\tTransport: tr,\n\t\t}\n\t\tcall = func() error {\n\t\t\tscheme := \"http://\"\n\t\t\tif isTLS {\n\t\t\t\tscheme = \"https://\"\n\t\t\t}\n\t\t\tresp, err := httpClient.Get(fmt.Sprintf(\"%s%s/\", scheme, c.MeshAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"response status: %d\", resp.StatusCode)\n\t\t\t}\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.T.Logf(\"HTTP client receive data: %s\\n\", string(b))\n\t\t\treturn nil\n\t\t}\n\tcase protocol.HTTP2:\n\t\tvar httpClient http.Client\n\t\tif !isTLS {\n\t\t\ttr := &http2.Transport{\n\t\t\t\tAllowHTTP: true,\n\t\t\t\tDialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {\n\t\t\t\t\treturn net.Dial(netw, addr)\n\t\t\t\t},\n\t\t\t}\n\t\t\thttpClient = http.Client{Transport: tr}\n\n\t\t} else {\n\t\t\tpool := x509.NewCertPool()\n\t\t\tpool.AppendCertsFromPEM([]byte(caPEM))\n\t\t\thttpClient = http.Client{\n\t\t\t\tTransport: &http2.Transport{\n\t\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\t\tRootCAs: pool,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tcall = func() error {\n\t\t\tscheme := \"http://\"\n\t\t\tif isTLS {\n\t\t\t\tscheme = \"https://\"\n\t\t\t}\n\t\t\tresp, err := httpClient.Get(fmt.Sprintf(\"%s%s/\", scheme, c.MeshAddr))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\treturn fmt.Errorf(\"response status: %d\", resp.StatusCode)\n\n\t\t\t}\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.T.Logf(\"HTTP2 client receive data: %s\\n\", string(b))\n\t\t\treturn nil\n\t\t}\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tif err := call(); err != nil {\n\t\t\tc.C <- err\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Duration(interval) * time.Millisecond)\n\t}\n\tc.C <- nil\n}", "func TLSConnect(\n\tctx context.Context, config TLSConnectConfig,\n) *TLSConnectResults {\n\tvar (\n\t\tmu sync.Mutex\n\t\tresults = new(TLSConnectResults)\n\t)\n\tchannel := make(chan modelx.Measurement)\n\troot := &modelx.MeasurementRoot{\n\t\tBeginning: time.Now(),\n\t\tHandler: &channelHandler{\n\t\t\tch: channel,\n\t\t},\n\t}\n\tctx = modelx.WithMeasurementRoot(ctx, root)\n\tdialer := netx.NewDialer(handlers.NoHandler)\n\t// TODO(bassosimone): tell dialer to use specific CA bundle?\n\tresolver, err := configureDNS(\n\t\ttime.Now().UnixNano(),\n\t\tconfig.DNSServerNetwork,\n\t\tconfig.DNSServerAddress,\n\t)\n\tif err != nil {\n\t\tresults.Error = err\n\t\treturn results\n\t}\n\tdialer.SetResolver(resolver)\n\t// TODO(bassosimone): can this call really fail?\n\tdialer.ForceSpecificSNI(config.SNI)\n\tresults.TestKeys.collect(channel, config.Handler, func() {\n\t\tconn, err := dialer.DialTLSContext(ctx, \"tcp\", config.Address)\n\t\tif conn != nil {\n\t\t\tdefer conn.Close()\n\t\t}\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tresults.Error = err\n\t})\n\treturn results\n}", "func main() {\n\n\tst := time.Now()\n\n\tll.Printf(\"%stag:%s connsess:%s starts\\n\",\n\t\texampid, tag, sngecomm.Lcs)\n\n\t// TLS Configuration.\n\ttc = new(tls.Config)\n\ttc.InsecureSkipVerify = true // Do *not* check the server's certificate\n\n\t// Usually one will use the default cipher suites that go provides.\n\t// However, if a custom cipher squite list is needed/required this\n\t// is how it is accomplished.\n\tif sngecomm.UseCustomCiphers() { // Set custom cipher suite list\n\t\ttc.CipherSuites = append(tc.CipherSuites, sngecomm.CustomCiphers()...)\n\t}\n\n\t// Standard example TLS connect sequence\n\tn, conn, e := sngecomm.CommonTLSConnect(exampid, tag, ll, tc)\n\tif e != nil {\n\t\tll.Fatalf(\"%stag:%s connsess:%s main_on_connect error:%v\",\n\t\t\texampid, tag, sngecomm.Lcs,\n\t\t\te.Error()) // Handle this ......\n\t}\n\n\tnc := n.(*tls.Conn)\n\tsngecomm.DumpTLSConfig(exampid, tc, nc)\n\n\t// *NOTE* application specific functionaltiy starts here!\n\t// For you to add.\n\t// *NOTE* application specific functionaltiy ends here!\n\n\t// Standard example disconnect sequence\n\te = sngecomm.CommonDisconnect(n, conn, exampid, tag, ll)\n\tif e != nil {\n\t\tll.Fatalf(\"%s %s\\n\", exampid, e.Error()) // Handle this ......\n\t}\n\n\tll.Printf(\"%stag:%s connsess:%s main_elapsed:%v\\n\",\n\t\texampid, tag, conn.Session(),\n\t\ttime.Now().Sub(st))\n\n}", "func BenchmarkTCPFindCipherFail(b *testing.B) {\n\tb.StopTimer()\n\tb.ResetTimer()\n\n\tlistener, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 0})\n\tif err != nil {\n\t\tb.Fatalf(\"ListenTCP failed: %v\", err)\n\t}\n\n\tcipherList, err := MakeTestCiphers(ss.MakeTestSecrets(100))\n\tif err != nil {\n\t\tb.Fatal(err)\n\t}\n\ttestPayload := ss.MakeTestPayload(50)\n\tfor n := 0; n < b.N; n++ {\n\t\tgo func() {\n\t\t\tconn, err := net.Dial(\"tcp\", listener.Addr().String())\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"Failed to dial %v: %v\", listener.Addr(), err)\n\t\t\t}\n\t\t\tconn.Write(testPayload)\n\t\t\tconn.Close()\n\t\t}()\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"AcceptTCP failed: %v\", err)\n\t\t}\n\t\tclientIP := clientConn.RemoteAddr().(*net.TCPAddr).IP\n\t\tb.StartTimer()\n\t\tfindAccessKey(clientConn, clientIP, cipherList)\n\t\tb.StopTimer()\n\t}\n}", "func (writer *connectivityHooks) getTLSHandshakeHints(err error) {\n\tif strings.Contains(err.Error(), \"first record does not look like a TLS handshake\") {\n\t\tfmt.Fprintln(writer.w, hintColorFunc(\"Hint: you are trying to communicate using HTTPS with an endpoint that does not seem to be configured for HTTPS.\"+\n\t\t\t\" If you are using a proxy, please verify that it is configured for HTTPS connections.\"))\n\t}\n}", "func TestSmoke(t *testing.T) {\n\ta := assert.New(t)\n\tconst backendCount = 4\n\tconst payloadSize = 4096\n\tconst requestCount = 64\n\tconst requestWorkers = 8\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tbackends := make([]*CharGenServer, backendCount)\n\ttier := config.Tier{\n\t\tDialFailureTimeout: 10 * time.Second,\n\t}\n\tfor i := range backends {\n\t\tvar err error\n\t\tbackends[i], err = startChargen(ctx, payloadSize)\n\t\tif !a.NoError(err) {\n\t\t\treturn\n\t\t}\n\t\ttier.Targets = append(tier.Targets, config.Target{\n\t\t\tHosts: []string{backends[i].Addr.IP.String()},\n\t\t\tPort: backends[i].Addr.Port,\n\t\t\tProto: config.TCP,\n\t\t})\n\t}\n\n\tcfg := &config.Config{\n\t\tFrontends: []config.Frontend{\n\t\t\t{\n\t\t\t\tRebalanceDuration: time.Millisecond,\n\t\t\t\tBackendPool: config.BackendPool{\n\t\t\t\t\t// Disable extra pings so our request counts are correct.\n\t\t\t\t\tLatencyBucket: -1,\n\t\t\t\t\tTiers: []config.Tier{tier},\n\t\t\t\t},\n\t\t\t\tBindAddress: \":13013\",\n\t\t\t\tIdleDuration: time.Minute,\n\t\t\t},\n\t\t},\n\t}\n\tif !a.NoError(cfg.Validate()) {\n\t\treturn\n\t}\n\n\tfe := frontend.Frontend{}\n\tif !a.NoError(fe.Ensure(ctx, cfg)) {\n\t\treturn\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(requestWorkers)\n\tvar remainingRequests = int32(requestCount)\n\tfor i := 0; i < requestWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tif atomic.AddInt32(&remainingRequests, -1) < 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\t\t\t\tif !a.NoError(err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcount, err := io.Copy(ioutil.Discard, conn)\n\t\t\t\t_ = conn.Close()\n\t\t\t\ta.NoError(err)\n\t\t\t\ta.Equal(payloadSize, int(count))\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\tfe.Wait()\n\n\t// Ensure that the total number of requests was made.\n\tcount := uint64(0)\n\tfor _, cg := range backends {\n\t\tcount += cg.ConnectionCount()\n\t}\n\ta.Equal(requestCount, int(count))\n\n\tdata, err := yaml.Marshal(&fe)\n\ta.NoError(err)\n\tlog.Print(string(data))\n\n\t// Test tearing down a frontend.\n\tcfg.Frontends = []config.Frontend{}\n\ta.NoError(fe.Ensure(ctx, cfg))\n\t_, err = net.Dial(\"tcp\", \"127.0.0.1:13013\")\n\ta.Errorf(err, \"connection refused\")\n}", "func TestNATSServer_Cluster_TLS(t *testing.T) {\n\tconst CONN_COUNT = 3\n\tconfigs := createNATSServerConfigsWithTLS(CONN_COUNT)\n\tservers := createNATSServers(t, configs)\n\tstartServers(servers)\n\tdefer shutdownServers(servers)\n\tlogNATServerInfo(servers, \"Servers have been started\")\n\tif err := waitforClusterMeshToForm(servers); err != nil {\n\t\tt.Fatalf(\"Full mesh did not form : %v\", err)\n\t}\n\n\tfor i, server := range servers {\n\t\tif server.Cluster() != configs[i].Cluster {\n\t\t\tt.Errorf(\"Cluster name does not match : %s != %s\", server.Cluster(), configs[i].Cluster)\n\t\t}\n\t}\n\n\t// connect to each server\n\t// create a subscription on each server\n\t// create a queue subscription on each server\n\tconst TOPIC = \"TestNewNATSServer\"\n\tconst QUEUE = \"TestNewNATSServer\"\n\tvar subscriptions []messaging.Subscription\n\tvar qsubscriptions []messaging.QueueSubscription\n\tvar conns []*opnats.ManagedConn\n\tfor _, config := range configs {\n\t\tconn, err := nats.Connect(fmt.Sprintf(\"tls://localhost:%d\", config.ServerPort), nats.Secure(clientTLSConfig()))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to connect : %v\", err)\n\t\t}\n\n\t\tmanagedConn := opnats.NewManagedConn(config.Cluster, fmt.Sprintf(\"%s:%d\", config.Cluster, config.ServerPort), conn, nil)\n\t\tconns = append(conns, managedConn)\n\t\tsub, err := managedConn.TopicSubscribe(TOPIC, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tsubscriptions = append(subscriptions, sub)\n\n\t\tqsub, err := managedConn.TopicQueueSubscribe(TOPIC, QUEUE, nil)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to create queue subscription on : %v\", config.ServerPort)\n\t\t}\n\t\tqsubscriptions = append(qsubscriptions, qsub)\n\n\t\tlogNATServerInfo(servers, fmt.Sprintf(\"created subscription on %d\", config.ServerPort))\n\t}\n\tlogNATServerInfo(servers, \"Connected to each server and created a subsription on each server\")\n\tif err := checkClientConnectionCounts(servers, 1); err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\twaitForClusterToBecomeAwareOfAllSubscriptions(servers, len(qsubscriptions)+len(qsubscriptions))\n\n\t// publish a message on each connection\n\ti := 0\n\tfor _, conn := range conns {\n\t\ti++\n\t\tconn.Publish(TOPIC, []byte(fmt.Sprintf(\"MSG #%d\", i)))\n\t}\n\tlog.Logger.Info().Msg(\"Published messages\")\n\n\tvar (\n\t\tSUBSCRIBER_EXPECTED_MSG_COUNT = (CONN_COUNT * len(subscriptions))\n\t\tQSUBSCRIBER_EXPECTED_MSG_COUNT = len(conns)\n\t)\n\tsubscriberMsgCount := receiveMessagesOnSubscriptions(subscriptions, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\tqsubscriberMsgCount := receiveMessagesOnQueueSubscriptions(qsubscriptions, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\tif subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"subscriberMsgCount != SUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", subscriberMsgCount, SUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n\tif qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT {\n\t\tt.Errorf(\"qsubscriberMsgCount != QSUBSCRIBER_EXPECTED_MSG_COUNT : %d ! %d\", qsubscriberMsgCount, QSUBSCRIBER_EXPECTED_MSG_COUNT)\n\t}\n}", "func (s *MockServer) StartTLS() {\n\tcert, err := tls.X509KeyPair(localhostCert, localhostKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"NewTLSServer: %v\", err))\n\t}\n\n\t// init tls config and tls listener\n\tif s.TLS == nil {\n\t\ts.TLS = new(tls.Config)\n\t}\n\tif len(s.TLS.Certificates) == 0 {\n\t\ts.TLS.Certificates = []tls.Certificate{cert}\n\t}\n\ttlsListener := tls.NewListener(s.Listener, s.TLS)\n\ts.Listener = &historyListener{Listener: tlsListener}\n\n\t// start tls server\n\tgo s.Serve(s.Listener)\n}", "func (m *Mock) StartTLS() *httptest.Server {\n\tm.Ts.StartTLS()\n\treturn m.Ts\n}", "func start_HTTPS(handler http.Handler, server Server) {\n\tfmt.Println(time.Now().Format(\"2006-01-02 03:04:05 PM\"), \"Running HTTPS \"+get_https_address(server))\n\n\t// Start the HTTPS listener\n\tlog.Fatal(http.ListenAndServeTLS(get_https_address(server), server.CertFile, server.KeyFile, handler))\n}", "func RunSSL(apps map[string]interface{}, port, cert, key string) {\n\trouter := mux.NewRouter()\n\tinitialize(apps, router)\n\n\t// This is very limited TLS configuration which is required to connect alexa to our webservice.\n\t// The curve preferences are used by ECDSA/ECDHE algorithms for figuring out the matching algorithm\n\t// from alexa side starting from the strongest to the weakest.\n\tcfg := &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\t// If the connection throws errors related to crypt algorithm mismatch between server and client,\n\t\t\t// this line must be replaced by constants present in crypt/tls package for the value that works.\n\t\t\ttls.TLS_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_CHACHA20_POLY1305_SHA256,\n\t\t\ttls.TLS_RSA_WITH_RC4_128_SHA,\n\t\t\ttls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t},\n\t}\n\tsrv := &http.Server{\n\t\tAddr: \":\" + port,\n\t\tHandler: router,\n\t\tTLSConfig: cfg,\n\t\tTLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),\n\t}\n\tlog.Fatal(srv.ListenAndServeTLS(cert, key))\n}", "func TestTLSExtensionsVerifyClient(t *testing.T) {\n\t// Server\n\textendVerify := map[string]interface{}{\n\t\t\"name\": \"server\",\n\t\t\"cn\": \"client\",\n\t}\n\tserverInfo := &certInfo{\n\t\tCommonName: extendVerify[\"name\"].(string),\n\t\tCurve: \"RSA\",\n\t}\n\tserverConfig, err := serverInfo.CreateCertConfig()\n\tif err != nil {\n\t\tt.Errorf(\"create server certificate error %v\", err)\n\t\treturn\n\t}\n\tserverConfig.RequireClientCert = true\n\tserverConfig.VerifyClient = true\n\tserverConfig.Type = testType\n\tserverConfig.ExtendVerify = extendVerify\n\tfilterChains := []v2.FilterChain{\n\t\t{\n\t\t\tTLSContexts: []v2.TLSConfig{\n\t\t\t\t*serverConfig,\n\t\t\t},\n\t\t},\n\t}\n\tlc := &v2.Listener{}\n\tlc.FilterChains = filterChains\n\tctxMng, err := NewTLSServerContextManager(lc)\n\tif err != nil {\n\t\tt.Errorf(\"create context manager failed %v\", err)\n\t\treturn\n\t}\n\tserver := MockServer{\n\t\tMng: ctxMng,\n\t\tt: t,\n\t}\n\tserver.GoListenAndServe(t)\n\tdefer server.Close()\n\ttime.Sleep(time.Second) //wait server start\n\ttestCases := []struct {\n\t\tInfo *certInfo\n\t\tPass func(resp *http.Response, err error) bool\n\t}{\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: extendVerify[\"cn\"].(string),\n\t\t\t\tCurve: serverInfo.Curve,\n\t\t\t},\n\t\t\tPass: pass,\n\t\t},\n\t\t{\n\t\t\tInfo: &certInfo{\n\t\t\t\tCommonName: \"invalid client\",\n\t\t\t\tCurve: serverInfo.Curve,\n\t\t\t},\n\t\t\tPass: fail,\n\t\t},\n\t}\n\tfor i, tc := range testCases {\n\t\tcfg, err := tc.Info.CreateCertConfig()\n\t\tcfg.ServerName = \"127.0.0.1\"\n\t\tif err != nil {\n\t\t\tt.Errorf(\"#%d create client certificate error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tcltMng, err := NewTLSClientContextManager(cfg)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"#%d create client context manager failed %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresp, err := MockClient(t, server.Addr, cltMng)\n\t\tif !tc.Pass(resp, err) {\n\t\t\tt.Errorf(\"#%d verify failed\", i)\n\t\t}\n\t}\n\n}", "func TestAgent_HTTPCheck(t *testing.T) {\n\tt.Parallel()\n\tlogger := log.New(ioutil.Discard, \"\", 0)\n\tif testing.Verbose() {\n\t\tlogger = log.New(os.Stdout, \"[TestAgent_HTTPCheck] \", log.Lshortfile)\n\t}\n\tagent := func() *Agent {\n\t\treturn &Agent{\n\t\t\tlogger: logger,\n\t\t\tconfig: &Config{\n\t\t\t\tAdvertiseAddrs: &AdvertiseAddrs{HTTP: \"advertise:4646\"},\n\t\t\t\tnormalizedAddrs: &Addresses{HTTP: \"normalized:4646\"},\n\t\t\t\tConsul: &sconfig.ConsulConfig{\n\t\t\t\t\tChecksUseAdvertise: helper.BoolToPtr(false),\n\t\t\t\t},\n\t\t\t\tTLSConfig: &sconfig.TLSConfig{EnableHTTP: false},\n\t\t\t},\n\t\t}\n\t}\n\n\tt.Run(\"Plain HTTP Check\", func(t *testing.T) {\n\t\ta := agent()\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif check.Type != \"http\" {\n\t\t\tt.Errorf(\"expected http check not: %q\", check.Type)\n\t\t}\n\t\tif expected := \"/v1/agent/health?type=client\"; check.Path != expected {\n\t\t\tt.Errorf(\"expected %q path not: %q\", expected, check.Path)\n\t\t}\n\t\tif check.Protocol != \"http\" {\n\t\t\tt.Errorf(\"expected http proto not: %q\", check.Protocol)\n\t\t}\n\t\tif expected := a.config.normalizedAddrs.HTTP; check.PortLabel != expected {\n\t\t\tt.Errorf(\"expected normalized addr not %q\", check.PortLabel)\n\t\t}\n\t})\n\n\tt.Run(\"Plain HTTP + ChecksUseAdvertise\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.Consul.ChecksUseAdvertise = helper.BoolToPtr(true)\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif expected := a.config.AdvertiseAddrs.HTTP; check.PortLabel != expected {\n\t\t\tt.Errorf(\"expected advertise addr not %q\", check.PortLabel)\n\t\t}\n\t})\n\n\tt.Run(\"HTTPS\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.TLSConfig.EnableHTTP = true\n\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif !check.TLSSkipVerify {\n\t\t\tt.Errorf(\"expected tls skip verify\")\n\t\t}\n\t\tif check.Protocol != \"https\" {\n\t\t\tt.Errorf(\"expected https not: %q\", check.Protocol)\n\t\t}\n\t})\n\n\tt.Run(\"HTTPS + VerifyHTTPSClient\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.TLSConfig.EnableHTTP = true\n\t\ta.config.TLSConfig.VerifyHTTPSClient = true\n\n\t\tif check := a.agentHTTPCheck(false); check != nil {\n\t\t\tt.Fatalf(\"expected nil check not: %#v\", check)\n\t\t}\n\t})\n}", "func TestPionE2ELossy(t *testing.T) {\n\t// Check for leaking routines\n\treport := transportTest.CheckRoutines(t)\n\tdefer report()\n\n\ttype runResult struct {\n\t\tdtlsConn *dtls.Conn\n\t\terr error\n\t}\n\n\tserverCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclientCert, err := selfsign.GenerateSelfSigned()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, test := range []struct {\n\t\tLossChanceRange int\n\t\tDoClientAuth bool\n\t\tCipherSuites []dtls.CipherSuiteID\n\t\tMTU int\n\t}{\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 0,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tCipherSuites: []dtls.CipherSuiteID{dtls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 10,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 20,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t\t{\n\t\t\tLossChanceRange: 50,\n\t\t\tMTU: 100,\n\t\t\tDoClientAuth: true,\n\t\t},\n\t} {\n\t\tname := fmt.Sprintf(\"Loss%d_MTU%d\", test.LossChanceRange, test.MTU)\n\t\tif test.DoClientAuth {\n\t\t\tname += \"_WithCliAuth\"\n\t\t}\n\t\tfor _, ciph := range test.CipherSuites {\n\t\t\tname += \"_With\" + ciph.String()\n\t\t}\n\t\ttest := test\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Limit runtime in case of deadlocks\n\t\t\tlim := transportTest.TimeOut(lossyTestTimeout + time.Second)\n\t\t\tdefer lim.Stop()\n\n\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\tchosenLoss := rand.Intn(9) + test.LossChanceRange //nolint:gosec\n\t\t\tserverDone := make(chan runResult)\n\t\t\tclientDone := make(chan runResult)\n\t\t\tbr := transportTest.NewBridge()\n\n\t\t\tif err = br.SetLossChance(chosenLoss); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tCipherSuites: test.CipherSuites,\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.Certificates = []tls.Certificate{clientCert}\n\t\t\t\t}\n\n\t\t\t\tclient, startupErr := dtls.Client(dtlsnet.PacketConnFromConn(br.GetConn0()), br.GetConn0().RemoteAddr(), cfg)\n\t\t\t\tclientDone <- runResult{client, startupErr}\n\t\t\t}()\n\n\t\t\tgo func() {\n\t\t\t\tcfg := &dtls.Config{\n\t\t\t\t\tCertificates: []tls.Certificate{serverCert},\n\t\t\t\t\tFlightInterval: flightInterval,\n\t\t\t\t\tMTU: test.MTU,\n\t\t\t\t}\n\n\t\t\t\tif test.DoClientAuth {\n\t\t\t\t\tcfg.ClientAuth = dtls.RequireAnyClientCert\n\t\t\t\t}\n\n\t\t\t\tserver, startupErr := dtls.Server(dtlsnet.PacketConnFromConn(br.GetConn1()), br.GetConn1().RemoteAddr(), cfg)\n\t\t\t\tserverDone <- runResult{server, startupErr}\n\t\t\t}()\n\n\t\t\ttestTimer := time.NewTimer(lossyTestTimeout)\n\t\t\tvar serverConn, clientConn *dtls.Conn\n\t\t\tdefer func() {\n\t\t\t\tif serverConn != nil {\n\t\t\t\t\tif err = serverConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif clientConn != nil {\n\t\t\t\t\tif err = clientConn.Close(); err != nil {\n\t\t\t\t\t\tt.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor {\n\t\t\t\tif serverConn != nil && clientConn != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tbr.Tick()\n\t\t\t\tselect {\n\t\t\t\tcase serverResult := <-serverDone:\n\t\t\t\t\tif serverResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, serverError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, serverResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tserverConn = serverResult.dtlsConn\n\t\t\t\tcase clientResult := <-clientDone:\n\t\t\t\t\tif clientResult.err != nil {\n\t\t\t\t\t\tt.Errorf(\"Fail, clientError: clientComplete(%t) serverComplete(%t) LossChance(%d) error(%v)\", clientConn != nil, serverConn != nil, chosenLoss, clientResult.err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tclientConn = clientResult.dtlsConn\n\t\t\t\tcase <-testTimer.C:\n\t\t\t\t\tt.Errorf(\"Test expired: clientComplete(%t) serverComplete(%t) LossChance(%d)\", clientConn != nil, serverConn != nil, chosenLoss)\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(10 * time.Millisecond):\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func setup() {\n\tcert, err := tls.LoadX509KeyPair(\"./cert.pem\", \"./key.pem\")\n\tif err != nil {\n\t\tsrvLog.WithError(err).Error(\"Can't load cert\")\n\t\treturn\n\t}\n\tconfig := tls.Config{Certificates: []tls.Certificate{cert}}\n\tlistener, err := tls.Listen(\"tcp\", \"192.168.20.15:8000\", &config)\n\tif err != nil {\n\t\tsrvLog.WithError(err).Error(\"Can't create listener\")\n\t\treturn\n\t}\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tsrvLog.WithError(err).Error(\"Can't accept connection\")\n\t\t\tbreak\n\t\t}\n\t\tsrvLog.WithField(\"addr\", conn.RemoteAddr()).Info(\"Connection accepted\")\n\t}\n\n}", "func (t *Tracer) TLSHandshakeDone(state tls.ConnectionState, err error) {\n\tif err == nil {\n\t\tatomic.CompareAndSwapInt64(&t.tlsHandshakeDone, 0, now())\n\t}\n\t// if there is an error it will be returned by the http call\n}", "func speedtest1_final(tls *libc.TLS) { /* speedtest1.c:413:6: */\n\tbp := tls.Alloc(72)\n\tdefer tls.Free(72)\n\n\tif !(g.bSqlOnly != 0) {\n\t\tlibc.Xprintf(tls, ts+2583 /* \" TOTAL%.*s...\" */, libc.VaList(bp, (60-5), uintptr(unsafe.Pointer(&zDots)),\n\t\t\t(int32(g.iTotal/int64(1000))), (int32(g.iTotal%int64(1000)))))\n\t}\n\tif g.bVerify != 0 {\n\t\tvar i int32\n\t\tlibc.Xprintf(tls, ts+2611 /* \"Verification Has...\" */, libc.VaList(bp+40, g.nResByte))\n\t\tHashUpdate(tls, ts+2636 /* \"\\n\" */, uint32(1))\n\t\tHashFinal(tls)\n\t\tfor i = 0; i < 24; i++ {\n\t\t\tlibc.Xprintf(tls, ts+2638 /* \"%02x\" */, libc.VaList(bp+56, int32(*(*uint8)(unsafe.Pointer((uintptr(unsafe.Pointer(&g)) + 3104 /* &.hash */ + 259 /* &.r */) + uintptr(i))))))\n\t\t}\n\t\tif (g.hashFile != 0) && (g.hashFile != (libc.X__acrt_iob_func(tls, uint32(1)))) {\n\t\t\tlibc.Xfclose(tls, g.hashFile)\n\t\t}\n\t\tlibc.Xprintf(tls, ts+2636 /* \"\\n\" */, 0)\n\t}\n}", "func TLSChecks(chainIndex, certIndex int, certificate *x509.Certificate) mapval.Validator {\n\treturn mapval.MustCompile(mapval.Map{\n\t\t\"tls\": mapval.Map{\n\t\t\t\"rtt.handshake.us\": mapval.IsDuration,\n\t\t\t\"certificate_not_valid_before\": certificate.NotBefore,\n\t\t\t\"certificate_not_valid_after\": certificate.NotAfter,\n\t\t},\n\t})\n}", "func startHTTPSServer(ch chan<- bool) {\n\tserver := http.Server{\n\t\tAddr: \":443\",\n\t}\n\tlog.Println(\"HTTPS server started (listening on port 443).\")\n\tlog.Println(\"HTTPS server stopped with error:\", server.ListenAndServeTLS(filepath.Join(rootPath, \"static/certificate/fullchain.cer\"), filepath.Join(rootPath, \"static/certificate/www.yuzuka.tk.key\")))\n\tch <- true\n}", "func (s) TestEnd2End(t *testing.T) {\n\tcs := &testutils.CertStore{}\n\tif err := cs.LoadCerts(); err != nil {\n\t\tt.Fatalf(\"cs.LoadCerts() failed, err: %v\", err)\n\t}\n\tstage := &stageInfo{}\n\tfor _, test := range []struct {\n\t\tdesc string\n\t\tclientCert []tls.Certificate\n\t\tclientGetCert func(*tls.CertificateRequestInfo) (*tls.Certificate, error)\n\t\tclientRoot *x509.CertPool\n\t\tclientGetRoot func(params *GetRootCAsParams) (*GetRootCAsResults, error)\n\t\tclientVerifyFunc CustomVerificationFunc\n\t\tclientVType VerificationType\n\t\tserverCert []tls.Certificate\n\t\tserverGetCert func(*tls.ClientHelloInfo) ([]*tls.Certificate, error)\n\t\tserverRoot *x509.CertPool\n\t\tserverGetRoot func(params *GetRootCAsParams) (*GetRootCAsResults, error)\n\t\tserverVerifyFunc CustomVerificationFunc\n\t\tserverVType VerificationType\n\t}{\n\t\t// Test Scenarios:\n\t\t// At initialization(stage = 0), client will be initialized with cert\n\t\t// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.\n\t\t// The mutual authentication works at the beginning, since ClientCert1 is\n\t\t// trusted by ServerTrust1, and ServerCert1 by ClientTrust1.\n\t\t// At stage 1, client changes ClientCert1 to ClientCert2. Since ClientCert2\n\t\t// is not trusted by ServerTrust1, following rpc calls are expected to\n\t\t// fail, while the previous rpc calls are still good because those are\n\t\t// already authenticated.\n\t\t// At stage 2, the server changes ServerTrust1 to ServerTrust2, and we\n\t\t// should see it again accepts the connection, since ClientCert2 is trusted\n\t\t// by ServerTrust2.\n\t\t{\n\t\t\tdesc: \"test the reloading feature for client identity callback and server trust callback\",\n\t\t\tclientGetCert: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0:\n\t\t\t\t\treturn &cs.ClientCert1, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn &cs.ClientCert2, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tclientRoot: cs.ClientTrust1,\n\t\t\tclientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tclientVType: CertVerification,\n\t\t\tserverCert: []tls.Certificate{cs.ServerCert1},\n\t\t\tserverGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0, 1:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ServerTrust1}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ServerTrust2}, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tserverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tserverVType: CertVerification,\n\t\t},\n\t\t// Test Scenarios:\n\t\t// At initialization(stage = 0), client will be initialized with cert\n\t\t// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.\n\t\t// The mutual authentication works at the beginning, since ClientCert1 is\n\t\t// trusted by ServerTrust1, and ServerCert1 by ClientTrust1.\n\t\t// At stage 1, server changes ServerCert1 to ServerCert2. Since ServerCert2\n\t\t// is not trusted by ClientTrust1, following rpc calls are expected to\n\t\t// fail, while the previous rpc calls are still good because those are\n\t\t// already authenticated.\n\t\t// At stage 2, the client changes ClientTrust1 to ClientTrust2, and we\n\t\t// should see it again accepts the connection, since ServerCert2 is trusted\n\t\t// by ClientTrust2.\n\t\t{\n\t\t\tdesc: \"test the reloading feature for server identity callback and client trust callback\",\n\t\t\tclientCert: []tls.Certificate{cs.ClientCert1},\n\t\t\tclientGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0, 1:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ClientTrust1}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ClientTrust2}, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tclientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tclientVType: CertVerification,\n\t\t\tserverGetCert: func(*tls.ClientHelloInfo) ([]*tls.Certificate, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0:\n\t\t\t\t\treturn []*tls.Certificate{&cs.ServerCert1}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn []*tls.Certificate{&cs.ServerCert2}, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tserverRoot: cs.ServerTrust1,\n\t\t\tserverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tserverVType: CertVerification,\n\t\t},\n\t\t// Test Scenarios:\n\t\t// At initialization(stage = 0), client will be initialized with cert\n\t\t// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.\n\t\t// The mutual authentication works at the beginning, since ClientCert1\n\t\t// trusted by ServerTrust1, ServerCert1 by ClientTrust1, and also the\n\t\t// custom verification check allows the CommonName on ServerCert1.\n\t\t// At stage 1, server changes ServerCert1 to ServerCert2, and client\n\t\t// changes ClientTrust1 to ClientTrust2. Although ServerCert2 is trusted by\n\t\t// ClientTrust2, our authorization check only accepts ServerCert1, and\n\t\t// hence the following calls should fail. Previous connections should\n\t\t// not be affected.\n\t\t// At stage 2, the client changes authorization check to only accept\n\t\t// ServerCert2. Now we should see the connection becomes normal again.\n\t\t{\n\t\t\tdesc: \"test client custom verification\",\n\t\t\tclientCert: []tls.Certificate{cs.ClientCert1},\n\t\t\tclientGetRoot: func(params *GetRootCAsParams) (*GetRootCAsResults, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ClientTrust1}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn &GetRootCAsResults{TrustCerts: cs.ClientTrust2}, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tclientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\tif len(params.RawCerts) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"no peer certs\")\n\t\t\t\t}\n\t\t\t\tcert, err := x509.ParseCertificate(params.RawCerts[0])\n\t\t\t\tif err != nil || cert == nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"failed to parse certificate: \" + err.Error())\n\t\t\t\t}\n\t\t\t\tauthzCheck := false\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0, 1:\n\t\t\t\t\t// foo.bar.com is the common name on ServerCert1\n\t\t\t\t\tif cert.Subject.CommonName == \"foo.bar.com\" {\n\t\t\t\t\t\tauthzCheck = true\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\t// foo.bar.server2.com is the common name on ServerCert2\n\t\t\t\t\tif cert.Subject.CommonName == \"foo.bar.server2.com\" {\n\t\t\t\t\t\tauthzCheck = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif authzCheck {\n\t\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"custom authz check fails\")\n\t\t\t},\n\t\t\tclientVType: CertVerification,\n\t\t\tserverGetCert: func(*tls.ClientHelloInfo) ([]*tls.Certificate, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0:\n\t\t\t\t\treturn []*tls.Certificate{&cs.ServerCert1}, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn []*tls.Certificate{&cs.ServerCert2}, nil\n\t\t\t\t}\n\t\t\t},\n\t\t\tserverRoot: cs.ServerTrust1,\n\t\t\tserverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tserverVType: CertVerification,\n\t\t},\n\t\t// Test Scenarios:\n\t\t// At initialization(stage = 0), client will be initialized with cert\n\t\t// ClientCert1 and ClientTrust1, server with ServerCert1 and ServerTrust1.\n\t\t// The mutual authentication works at the beginning, since ClientCert1\n\t\t// trusted by ServerTrust1, ServerCert1 by ClientTrust1, and also the\n\t\t// custom verification check on server side allows all connections.\n\t\t// At stage 1, server disallows the connections by setting custom\n\t\t// verification check. The following calls should fail. Previous\n\t\t// connections should not be affected.\n\t\t// At stage 2, server allows all the connections again and the\n\t\t// authentications should go back to normal.\n\t\t{\n\t\t\tdesc: \"TestServerCustomVerification\",\n\t\t\tclientCert: []tls.Certificate{cs.ClientCert1},\n\t\t\tclientRoot: cs.ClientTrust1,\n\t\t\tclientVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t},\n\t\t\tclientVType: CertVerification,\n\t\t\tserverCert: []tls.Certificate{cs.ServerCert1},\n\t\t\tserverRoot: cs.ServerTrust1,\n\t\t\tserverVerifyFunc: func(params *VerificationFuncParams) (*VerificationResults, error) {\n\t\t\t\tswitch stage.read() {\n\t\t\t\tcase 0, 2:\n\t\t\t\t\treturn &VerificationResults{}, nil\n\t\t\t\tcase 1:\n\t\t\t\t\treturn nil, fmt.Errorf(\"custom authz check fails\")\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, fmt.Errorf(\"custom authz check fails\")\n\t\t\t\t}\n\t\t\t},\n\t\t\tserverVType: CertVerification,\n\t\t},\n\t} {\n\t\ttest := test\n\t\tt.Run(test.desc, func(t *testing.T) {\n\t\t\t// Start a server using ServerOptions in another goroutine.\n\t\t\tserverOptions := &ServerOptions{\n\t\t\t\tIdentityOptions: IdentityCertificateOptions{\n\t\t\t\t\tCertificates: test.serverCert,\n\t\t\t\t\tGetIdentityCertificatesForServer: test.serverGetCert,\n\t\t\t\t},\n\t\t\t\tRootOptions: RootCertificateOptions{\n\t\t\t\t\tRootCACerts: test.serverRoot,\n\t\t\t\t\tGetRootCertificates: test.serverGetRoot,\n\t\t\t\t},\n\t\t\t\tRequireClientCert: true,\n\t\t\t\tVerifyPeer: test.serverVerifyFunc,\n\t\t\t\tVType: test.serverVType,\n\t\t\t}\n\t\t\tserverTLSCreds, err := NewServerCreds(serverOptions)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to create server creds: %v\", err)\n\t\t\t}\n\t\t\ts := grpc.NewServer(grpc.Creds(serverTLSCreds))\n\t\t\tdefer s.Stop()\n\t\t\tlis, err := net.Listen(\"tcp\", \"localhost:0\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to listen: %v\", err)\n\t\t\t}\n\t\t\tdefer lis.Close()\n\t\t\taddr := fmt.Sprintf(\"localhost:%v\", lis.Addr().(*net.TCPAddr).Port)\n\t\t\tpb.RegisterGreeterServer(s, greeterServer{})\n\t\t\tgo s.Serve(lis)\n\t\t\tclientOptions := &ClientOptions{\n\t\t\t\tIdentityOptions: IdentityCertificateOptions{\n\t\t\t\t\tCertificates: test.clientCert,\n\t\t\t\t\tGetIdentityCertificatesForClient: test.clientGetCert,\n\t\t\t\t},\n\t\t\t\tVerifyPeer: test.clientVerifyFunc,\n\t\t\t\tRootOptions: RootCertificateOptions{\n\t\t\t\t\tRootCACerts: test.clientRoot,\n\t\t\t\t\tGetRootCertificates: test.clientGetRoot,\n\t\t\t\t},\n\t\t\t\tVType: test.clientVType,\n\t\t\t}\n\t\t\tclientTLSCreds, err := NewClientCreds(clientOptions)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"clientTLSCreds failed to create: %v\", err)\n\t\t\t}\n\t\t\t// ------------------------Scenario 1------------------------------------\n\t\t\t// stage = 0, initial connection should succeed\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\t\tdefer cancel()\n\t\t\tconn, greetClient, err := callAndVerifyWithClientConn(ctx, addr, \"rpc call 1\", clientTLSCreds, false)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer conn.Close()\n\t\t\t// ----------------------------------------------------------------------\n\t\t\tstage.increase()\n\t\t\t// ------------------------Scenario 2------------------------------------\n\t\t\t// stage = 1, previous connection should still succeed\n\t\t\terr = callAndVerify(\"rpc call 2\", greetClient, false)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\t// ------------------------Scenario 3------------------------------------\n\t\t\t// stage = 1, new connection should fail\n\t\t\tctx2, cancel2 := context.WithTimeout(context.Background(), defaultTestTimeout)\n\t\t\tconn2, _, err := callAndVerifyWithClientConn(ctx2, addr, \"rpc call 3\", clientTLSCreds, true)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer conn2.Close()\n\t\t\t// Immediately cancel the context so the dialing won't drag the entire timeout still it stops.\n\t\t\tcancel2()\n\t\t\t// ----------------------------------------------------------------------\n\t\t\tstage.increase()\n\t\t\t// ------------------------Scenario 4------------------------------------\n\t\t\t// stage = 2, new connection should succeed\n\t\t\tconn3, _, err := callAndVerifyWithClientConn(ctx, addr, \"rpc call 4\", clientTLSCreds, false)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer conn3.Close()\n\t\t\t// ----------------------------------------------------------------------\n\t\t\tstage.reset()\n\t\t})\n\t}\n}", "func (s *ProxyServer) serveGenericTLS(listener net.Listener, tlsConfig *tls.Config, dbName string) error {\n\ts.log.Debugf(\"Started %s proxy.\", dbName)\n\tdefer s.log.Debugf(\"%s proxy exited.\", dbName)\n\tfor {\n\t\tclientConn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif utils.IsOKNetworkError(err) || trace.IsConnectionProblem(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tgo func() {\n\t\t\tdefer clientConn.Close()\n\t\t\ttlsConn := tls.Server(clientConn, tlsConfig)\n\t\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\t\tif !utils.IsOKNetworkError(err) {\n\t\t\t\t\ts.log.WithError(err).Errorf(\"%s TLS handshake failed.\", dbName)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := s.handleConnection(tlsConn)\n\t\t\tif err != nil {\n\t\t\t\ts.log.WithError(err).Errorf(\"Failed to handle %s client connection.\", dbName)\n\t\t\t}\n\t\t}()\n\t}\n}", "func New(L *lua.LState) int {\n\tvar tlsConfig *tls.Config\n\tbind := \"127.0.0.1:0\"\n\tswitch bindOrTable := L.CheckAny(1).(type) {\n\tcase lua.LString:\n\t\tbind = string(bindOrTable)\n\tcase *lua.LTable:\n\t\tif addr, ok := L.GetField(bindOrTable, \"addr\").(lua.LString); ok {\n\t\t\tbind = string(addr)\n\t\t}\n\t\tserverPublicCertPEMFile := L.GetField(bindOrTable, `server_public_cert_pem_file`)\n\t\tserverPrivateKeyPemFile := L.GetField(bindOrTable, `server_private_key_pem_file`)\n\t\tif serverPublicCertPEMFile != lua.LNil && serverPrivateKeyPemFile != lua.LNil {\n\t\t\tserverCert, err := tls.LoadX509KeyPair(serverPublicCertPEMFile.String(), serverPrivateKeyPemFile.String())\n\t\t\tif err != nil {\n\t\t\t\tL.RaiseError(\"error loading server cert: %v\", err)\n\t\t\t}\n\t\t\ttlsConfig = &tls.Config{\n\t\t\t\tCertificates: []tls.Certificate{serverCert},\n\t\t\t}\n\n\t\t\tclientAuth := L.GetField(bindOrTable, \"client_auth\")\n\t\t\tif clientAuth != lua.LNil {\n\t\t\t\tif _, ok := clientAuth.(lua.LString); !ok {\n\t\t\t\t\tL.ArgError(1, \"client_auth should be a string\")\n\t\t\t\t}\n\t\t\t\tswitch clientAuth.String() {\n\t\t\t\tcase \"NoClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.NoClientCert\n\t\t\t\tcase \"RequestClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequestClientCert\n\t\t\t\tcase \"RequireAnyClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequireAnyClientCert\n\t\t\t\tcase \"VerifyClientCertIfGiven\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.VerifyClientCertIfGiven\n\t\t\t\tcase \"RequireAndVerifyClientCert\":\n\t\t\t\t\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclientCAs := L.GetField(bindOrTable, \"client_cas_pem_file\")\n\t\t\tif clientCAs != lua.LNil {\n\t\t\t\tif _, ok := clientCAs.(lua.LString); !ok {\n\t\t\t\t\tL.ArgError(1, \"client_cas_pem_file must be a string\")\n\t\t\t\t}\n\t\t\t\tdata, err := ioutil2.ReadFile(clientCAs.String())\n\t\t\t\tif err != nil {\n\t\t\t\t\tL.RaiseError(\"error reading %s: %v\", clientCAs, err)\n\t\t\t\t}\n\t\t\t\ttlsConfig.ClientCAs = x509.NewCertPool()\n\t\t\t\tif !tlsConfig.ClientCAs.AppendCertsFromPEM(data) {\n\t\t\t\t\tL.RaiseError(\"no certs loaded from %s\", clientCAs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tl, err := net.Listen(`tcp`, bind)\n\tif err != nil {\n\t\tL.Push(lua.LNil)\n\t\tL.Push(lua.LString(err.Error()))\n\t\treturn 2\n\t}\n\tif tlsConfig != nil {\n\t\tl = tls.NewListener(l, tlsConfig)\n\t}\n\tserver := &luaServer{\n\t\tListener: l,\n\t\tserveData: make(chan *serveData, 1),\n\t}\n\tserver.serve(L)\n\tud := L.NewUserData()\n\tud.Value = server\n\tL.SetMetatable(ud, L.GetTypeMetatable(\"http_server_ud\"))\n\tL.Push(ud)\n\treturn 1\n}", "func TestNewKeepAliveListener(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected listen error: %v\", err)\n\t}\n\n\tln, err = NewKeepAliveListener(ln, \"http\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"http://\" + ln.Addr().String())\n\tconn, err := ln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*keepAliveConn); !ok {\n\t\tt.Fatalf(\"Unexpected conn type: %T, wanted *keepAliveConn\", conn)\n\t}\n\tconn.Close()\n\tln.Close()\n\n\tln, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Listen error: %v\", err)\n\t}\n\n\t// tls\n\ttlsinfo, err := createSelfCert(t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create tmpfile: %v\", err)\n\t}\n\ttlsInfo := TLSInfo{CertFile: tlsinfo.CertFile, KeyFile: tlsinfo.KeyFile}\n\ttlsInfo.parseFunc = fakeCertificateParserFunc(tls.Certificate{}, nil)\n\ttlscfg, err := tlsInfo.ServerConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected serverConfig error: %v\", err)\n\t}\n\ttlsln, err := NewKeepAliveListener(ln, \"https\", tlscfg)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewKeepAliveListener error: %v\", err)\n\t}\n\n\tgo http.Get(\"https://\" + tlsln.Addr().String())\n\tconn, err = tlsln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected Accept error: %v\", err)\n\t}\n\tif _, ok := conn.(*tls.Conn); !ok {\n\t\tt.Errorf(\"failed to accept *tls.Conn\")\n\t}\n\tconn.Close()\n\ttlsln.Close()\n}", "func handlePacket(packet gopacket.Packet) {\n\t// Get the TCP layer from this packet\n\tif tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {\n\t\ttcp, _ := tcpLayer.(*layers.TCP)\n\t\tpayload := tcp.BaseLayer.Payload\n\n\t\t/*\n\t\t * We are searching for a TLS record header\n\t\t * (http://blog.fourthbit.com/2014/12/23/traffic-analysis-of-an-ssl-slash-tls-session)\n\t\t * First byte: 0x16 for ALLPLICATION_DATA\n\t\t * Two consecutive bytes: 0x0303 for TLS 1.2\n\t\t */\n\n\t\t// Payload must be bigger than 5 bytes (TLS header is 5 bytes)\n\t\tif len(payload) >= 5 {\n\t\t\t// Make sure we have a TLS record here.\n\t\t\tif payload[0] == tlsRecordHandshake {\n\t\t\t\t// See if message type in handshake layer is TLSRecordHandshakeClientHello\n\t\t\t\tTLSRecordHandshakeMessageType := payload[5]\n\n\t\t\t\t/*\n\t\t\t\t * If TLS handshake HELLO is CLIENT_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeClientHello {\n\t\t\t\t\t// TLS version in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11]) // Catch two bytes and interpret as single number (0xXXXX)\n\n\t\t\t\t\ttlsVersionsClients[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t/*\n\t\t\t\t\t * Get ciphers\n\t\t\t\t\t */\n\n\t\t\t\t\t// After payload byte 43 there is session ID length and session ID\n\t\t\t\t\t// In most cases session ID length is 0x00, so there is no session ID byte.\n\t\t\t\t\t// Check the length of the session ID and contunie from there\n\t\t\t\t\t// After the session ID length and session ID bytes, the cipher part starts\n\t\t\t\t\t// Anatomy of th CLIENT_HELLO handshake message:\n\t\t\t\t\t// \t<TLS VERSION 2B> | <RANDOM 32B> | <SESS ID LENGTH 1B> | <SESS ID 0..nB> | <CIPHER SUITES LEN 2B> | <CIPHER 1 2B> | CIPHER 2 2B> | ...\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\tCiphersLengthBytes := binary.BigEndian.Uint16(payload[cipherSuitesStart : cipherSuitesStart+2])\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\tvar i uint16\n\t\t\t\t\tfor i = 0; i < CiphersLengthBytes; i += 2 {\n\t\t\t\t\t\tcipherpos := cipherSuitesStart + 2 + byte(i)\n\t\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\t\tciphersClients[cipher]++ // Increment counter for this cipher\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * If TLS Handshake HELLO is SERVER_HELLO\n\t\t\t\t */\n\t\t\t\tif TLSRecordHandshakeMessageType == tlsRecordHandshakeServerHello {\n\t\t\t\t\t// TLS in Handshake layer\n\t\t\t\t\tTLSHandshakeLayerVersion := binary.BigEndian.Uint16(payload[9:11])\n\n\t\t\t\t\ttlsVersionsServers[TLSHandshakeLayerVersion]++\n\n\t\t\t\t\t// Detect cipher block start byte\n\t\t\t\t\tsessionIDLength := payload[43]\n\t\t\t\t\tcipherSuitesStart := 43 + 1 + sessionIDLength // session length offset (43B) + length byte (1B) + sessionIDLength\n\n\t\t\t\t\t// Detect length of cipher part\n\t\t\t\t\t// (Not needed for server part, because only one cipher is suggested by server)\n\n\t\t\t\t\t// Walk through all ciphers and count occurances\n\t\t\t\t\t// (no walking needed, because there is only one cipher suggested)\n\t\t\t\t\tcipherpos := cipherSuitesStart\n\t\t\t\t\tcipher := binary.BigEndian.Uint16(payload[cipherpos : cipherpos+2])\n\t\t\t\t\tciphersServers[cipher]++ // Increment counter for this cipher\n\n\t\t\t\t}\n\t\t\t} else if payload[0] == tlsRecordAlert {\n\t\t\t\t/*\n\t\t\t\t * If there is an alert message\n\t\t\t\t * Search for any Handshake failures\n\t\t\t\t */\n\t\t\t\ttlsAlertLength := binary.BigEndian.Uint16(payload[3:5])\n\t\t\t\t// Alerts need to have length 2 bytes\n\t\t\t\tif tlsAlertLength == 2 {\n\t\t\t\t\ttlsAlertDescription := payload[6]\n\t\t\t\t\talerts[uint16(tlsAlertDescription)]++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func BenchmarkClientEncoding(b *testing.B) {\n\tvar req pb.GetWithQueryRequest\n\treq.A = 12\n\treq.B = 45360\n\tfor i := 0; i < b.N; i++ {\n\t\thttpreq, _ := http.NewRequest(\"GET\", \"http://localhost/getwithquery\", strings.NewReader(string(\"\")))\n\t\thttpclient.EncodeHTTPGetWithQueryZeroRequest(context.Background(), httpreq, &req)\n\t}\n}", "func speedtest1_run(tls *libc.TLS) { /* speedtest1.c:532:6: */\n\tbp := tls.Alloc(8)\n\tdefer tls.Free(8)\n\n\tvar i int32\n\tvar n int32\n\tvar len int32\n\tif g.bSqlOnly != 0 {\n\t\treturn\n\t}\n\n\tg.nResult = 0\n\tfor sqlite3.Xsqlite3_step(tls, g.pStmt) == 100 {\n\t\tn = sqlite3.Xsqlite3_column_count(tls, g.pStmt)\n\t\tfor i = 0; i < n; i++ {\n\t\t\tvar z uintptr = sqlite3.Xsqlite3_column_text(tls, g.pStmt, i)\n\t\t\tif z == uintptr(0) {\n\t\t\t\tz = ts + 2732 /* \"nil\" */\n\t\t\t}\n\t\t\tlen = int32(libc.Xstrlen(tls, z))\n\t\t\tif g.bVerify != 0 {\n\t\t\t\tvar eType int32 = sqlite3.Xsqlite3_column_type(tls, g.pStmt, i)\n\t\t\t\t// var zPrefix [2]uint8 at bp, 2\n\n\t\t\t\t*(*uint8)(unsafe.Pointer(bp /* &zPrefix[0] */ + uintptr(0))) = uint8('\\n')\n\t\t\t\t*(*uint8)(unsafe.Pointer(bp /* &zPrefix[0] */ + uintptr(1))) = uint8(*(*int8)(unsafe.Pointer(ts + 2736 /* \"-IFTBN\" */ + uintptr(eType))))\n\t\t\t\tif g.nResByte != 0 {\n\t\t\t\t\tHashUpdate(tls, bp /* &zPrefix[0] */, uint32(2))\n\t\t\t\t} else {\n\t\t\t\t\tHashUpdate(tls, (bp /* &zPrefix[0] */ + uintptr(1)), uint32(1))\n\t\t\t\t}\n\t\t\t\tif eType == 2 {\n\t\t\t\t\t// Omit the value of floating-point results from the verification\n\t\t\t\t\t// hash. The only thing we record is the fact that the result was\n\t\t\t\t\t// a floating-point value.\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (uint64(2))\n\t\t\t\t} else if eType == 4 {\n\t\t\t\t\tvar nBlob int32 = sqlite3.Xsqlite3_column_bytes(tls, g.pStmt, i)\n\t\t\t\t\tvar iBlob int32\n\t\t\t\t\t// var zChar [2]uint8 at bp+2, 2\n\n\t\t\t\t\tvar aBlob uintptr = sqlite3.Xsqlite3_column_blob(tls, g.pStmt, i)\n\t\t\t\t\tfor iBlob = 0; iBlob < nBlob; iBlob++ {\n\t\t\t\t\t\t*(*uint8)(unsafe.Pointer(bp + 2 /* &zChar[0] */ + uintptr(0))) = uint8(*(*int8)(unsafe.Pointer(ts + 2743 /* \"0123456789abcdef\" */ + uintptr((int32(*(*uint8)(unsafe.Pointer(aBlob + uintptr(iBlob)))) >> 4)))))\n\t\t\t\t\t\t*(*uint8)(unsafe.Pointer(bp + 2 /* &zChar[0] */ + uintptr(1))) = uint8(*(*int8)(unsafe.Pointer(ts + 2743 /* \"0123456789abcdef\" */ + uintptr((int32(*(*uint8)(unsafe.Pointer(aBlob + uintptr(iBlob)))) & 15)))))\n\t\t\t\t\t\tHashUpdate(tls, bp+2 /* &zChar[0] */, uint32(2))\n\t\t\t\t\t}\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (u64((nBlob * 2) + 2))\n\t\t\t\t} else {\n\t\t\t\t\tHashUpdate(tls, z, uint32(len))\n\t\t\t\t\t*(*u64)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 88 /* &.nResByte */)) += (u64(len + 2))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (uint32(g.nResult + len)) < (uint32(unsafe.Sizeof([3000]int8{})) - uint32(2)) {\n\t\t\t\tif g.nResult > 0 {\n\t\t\t\t\t*(*int8)(unsafe.Pointer((uintptr(unsafe.Pointer(&g)) + 100 /* &.zResult */) + uintptr(libc.PostIncInt32(&g.nResult, 1)))) = int8(' ')\n\t\t\t\t}\n\t\t\t\tlibc.Xmemcpy(tls, ((uintptr(unsafe.Pointer(&g)) + 100 /* &.zResult */) + uintptr(g.nResult)), z, (uint32(len + 1)))\n\t\t\t\t*(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(&g)) + 96 /* &.nResult */)) += (len)\n\t\t\t}\n\t\t}\n\t}\n\tif g.bReprepare != 0 {\n\t\t// var pNew uintptr at bp+4, 4\n\n\t\tsqlite3.Xsqlite3_prepare_v2(tls, g.db, sqlite3.Xsqlite3_sql(tls, g.pStmt), -1, bp+4 /* &pNew */, uintptr(0))\n\t\tsqlite3.Xsqlite3_finalize(tls, g.pStmt)\n\t\tg.pStmt = *(*uintptr)(unsafe.Pointer(bp + 4 /* pNew */))\n\t} else {\n\t\tsqlite3.Xsqlite3_reset(tls, g.pStmt)\n\t}\n\tspeedtest1_shrink_memory(tls)\n}", "func ListenAndServeHTTP(addr string, connLimit int, certFile *string, keyFile *string, handler http.Handler, readTimeout *int, writeTimeout *int, http2Enabled bool) error {\n\tvar config *tls.Config\n\tif certFile != nil {\n\t\tconfig = &tls.Config{}\n\t\tconfig.MinVersion = tls.VersionTLS10 // Disable SSLv3 due to POODLE vulnerability\n\t\tprotocolsEnabled := []string{\"http/1.1\"}\n\t\tif http2Enabled {\n\t\t\tprotocolsEnabled = []string{\"h2\", \"http/1.1\"}\n\t\t}\n\t\tconfig.NextProtos = protocolsEnabled\n\t\tLogTo(\"HTTP\", \"Protocols enabled: %v on %v\", config.NextProtos, addr)\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tvar err error\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(*certFile, *keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlistener, err := ThrottledListen(\"tcp\", addr, connLimit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif config != nil {\n\t\tlistener = tls.NewListener(listener, config)\n\t}\n\tdefer listener.Close()\n\tserver := &http.Server{Addr: addr, Handler: handler}\n\tif readTimeout != nil {\n\t\tserver.ReadTimeout = time.Duration(*readTimeout) * time.Second\n\t}\n\tif writeTimeout != nil {\n\t\tserver.WriteTimeout = time.Duration(*writeTimeout) * time.Second\n\t}\n\n\treturn server.Serve(listener)\n}", "func SMTPServerSTARTTLS(t *testing.T, addr string, fn ...SMTPServerConfigureFunc) (*tls.Config, *SMTPBackend, *smtp.Server) {\n\tt.Helper()\n\n\tcert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tbe := new(SMTPBackend)\n\ts := smtp.NewServer(be)\n\ts.Domain = \"localhost\"\n\ts.AllowInsecureAuth = true\n\ts.TLSConfig = &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\tfor _, f := range fn {\n\t\tf(s)\n\t}\n\n\tpool := x509.NewCertPool()\n\tpool.AppendCertsFromPEM([]byte(testServerCert))\n\n\tclientCfg := &tls.Config{\n\t\tServerName: \"127.0.0.1\",\n\t\tTime: func() time.Time {\n\t\t\treturn time.Date(2019, time.November, 18, 17, 59, 41, 0, time.UTC)\n\t\t},\n\t\tRootCAs: pool,\n\t}\n\n\tgo func() {\n\t\tif err := s.Serve(l); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\t// Dial it once it make sure Server completes its initialization before\n\t// we try to use it. Notably, if test fails before connecting to the server,\n\t// it will call Server.Close which will call Server.listener.Close with a\n\t// nil Server.listener (Serve sets it to a non-nil value, so it is racy and\n\t// happens only sometimes).\n\ttestConn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttestConn.Close()\n\n\treturn clientCfg, be, s\n}", "func TestProbeHTTPSNoScheme(t *testing.T) {\n\tserver, certPEM, _, caFile, teardown, err := test.SetupHTTPSServer()\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tdefer teardown()\n\n\tserver.StartTLS()\n\tdefer server.Close()\n\n\tmodule := config.Module{\n\t\tTLSConfig: config.TLSConfig{\n\t\t\tCAFile: caFile,\n\t\t\tInsecureSkipVerify: false,\n\t\t},\n\t}\n\n\tu, err := url.Parse(server.URL)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\n\tregistry := prometheus.NewRegistry()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif err := ProbeHTTPS(ctx, newTestLogger(), u.Host, module, registry); err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\n\tcert, err := newCertificate(certPEM)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckCertificateMetrics(cert, registry, t)\n\tcheckOCSPMetrics([]byte{}, registry, t)\n\tcheckTLSVersionMetrics(\"TLS 1.3\", registry, t)\n}", "func TestXUpdateTLS_TLSToNone(t *testing.T) {\n\tappaddr := \"127.0.0.1:8080\"\n\ttestCases := []*XExtendTLSUpdateCase{\n\t\tNewXExtendTLSUpdateCase(t, bolt.ProtocolName, util.NewRPCServer(t, appaddr, bolt.ProtocolName)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(true)\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tverify()\n\t\t// update to non-tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{v2.TLSConfig{}}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tverify()\n\t\t// finish\n\t\ttc.FinishCase()\n\t}\n\n}", "func DTLSServer(conn net.Conn, config *Config) *Conn {\n\tc := &Conn{config: config, isDTLS: true, conn: conn}\n\tc.init()\n\treturn c\n}", "func (t *HTTPServer) ListenAndServeTLS() error {\n\tif t.options.Certificate == \"\" || t.options.CertificateKey == \"\" {\n\t\ttlsOptions := sslcert.DefaultOptions\n\t\ttlsOptions.Host = t.options.CertificateDomain\n\t\ttlsConfig, err := sslcert.NewTLSConfig(tlsOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpServer := &http.Server{\n\t\t\tAddr: t.options.ListenAddress,\n\t\t\tTLSConfig: tlsConfig,\n\t\t}\n\t\thttpServer.Handler = t.layers\n\t\treturn httpServer.ListenAndServeTLS(\"\", \"\")\n\t}\n\treturn http.ListenAndServeTLS(t.options.ListenAddress, t.options.Certificate, t.options.CertificateKey, t.layers)\n}", "func main() {\n\n // Open logfile for writing and write startup entries\n f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n if err != nil {\n log.Fatal(err)\n }\n defer f.Close()\n log.SetOutput(f)\n log.Printf(startup)\n log.Printf(\"version: \" + version)\n\n // Exit if process started as UID 0 (root)\n if syscall.Getuid() == 0 {\n log.Fatal(\"Failed to start: simple-agent must not run as root!\")\n }\n\n // Limit number of requests to prevent DoS and excessive resource use\n limiter := tollbooth.NewLimiter(10, time.Second)\n limiter.Message = \"[429] Too Many Requests\"\n\n // Start http server as TLS only, define handler and certificates\n s := &http.Server {\n Addr: \":\" + port,\n ReadTimeout: 10 * time.Second,\n WriteTimeout: 10 * time.Second,\n MaxHeaderBytes: 1 << 2,\n }\n http.Handle(\"/\", tollbooth.LimitFuncHandler(limiter,CommandHandler))\n err = s.ListenAndServeTLS(cert, key)\n if err != nil {\n log.Fatal(\"Failed to start: \", err)\n }\n\n}", "func TestLatencyTestReal(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping test in short mode.\")\n\t}\n\tserverID := \"16976\"\n\n\tconfig := configuration{\n\t\tServerID: serverID,\n\t\tTimeout: 5,\n\t\t//MaxSeconds: 4.0,\n\t}\n\n\tserver := GetServerByID(serverID)\n\tserver.Configuration = &config\n\n\tlocalAddr := net.TCPAddr{}\n\tsource, _ := net.ResolveTCPAddr(\"tcp\", localAddr.String())\n\n\tspdTest := speedtest{\n\t\tSource: source,\n\t}\n\n\tserver.Speedtest = &spdTest\n\tspdTest.Server = &server\n\n\tLatencyTest(&server)\n\tallResults := server.Results\n\n\tresults := allResults.Latency.Seconds()\n\n\tif results <= 0 {\n\t\tt.Fatalf(\"Error: Expected a positive Latency result, but got: %f, err: %s\", results, allResults.Error)\n\t}\n\tfmt.Printf(\"\\nLatency test results for server %s ... %f\\n\", serverID, results)\n}", "func SetupTLSServer(server *http.Server, caCertPath string) error {\n\tca, err := ioutil.ReadFile(caCertPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcaCertPool := x509.NewCertPool()\n\tif !caCertPool.AppendCertsFromPEM(ca) {\n\t\treturn errors.New(\"Can not load CA certificate\")\n\t}\n\n\ttlsConfig, err := commonTLSConfig(caCertPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsConfig.ClientCAs = tlsConfig.RootCAs\n\ttlsConfig.ClientAuth = tls.RequireAndVerifyClientCert\n\n\ttlsConfig.BuildNameToCertificate()\n\n\tserver.TLSConfig = tlsConfig\n\n\treturn nil\n}", "func TLS(address string) bool {\n\td := &net.Dialer{Timeout: timeout}\n\tconn, err := tls.DialWithDialer(d, \"tcp\", address, nil)\n\tif err != nil {\n\t\treturn false\n\t}\n\tconn.Close()\n\treturn true\n}", "func testset_main(tls *libc.TLS) { /* speedtest1.c:694:6: */\n\tbp := tls.Alloc(2968)\n\tdefer tls.Free(2968)\n\n\tvar i int32 // Loop counter\n\tvar n int32 // iteration count\n\tvar sz int32 // Size of the tables\n\tvar maxb int32 // Maximum swizzled value\n\tvar x1 uint32 = uint32(0)\n\tvar x2 uint32 = uint32(0) // Parameters\n\tvar len int32 = 0 // Length of the zNum[] string\n\t// var zNum [2000]int8 at bp+968, 2000\n\t// A number name\n\n\tsz = libc.AssignInt32(&n, (g.szTest * 500))\n\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8(0)\n\tmaxb = int32(roundup_allones(tls, uint32(sz)))\n\tspeedtest1_begin_test(tls, 100, ts+2760 /* \"%d INSERTs into ...\" */, libc.VaList(bp, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls, ts+2802, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+16, isTemp(tls, 9), g.zNN, g.zNN, g.zNN))\n\tspeedtest1_prepare(tls, ts+2860 /* \"INSERT INTO t1 V...\" */, libc.VaList(bp+56, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_int64(tls, g.pStmt, 1, sqlite3_int64(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, i)\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 3, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 110, ts+2913 /* \"%d ordered INSER...\" */, libc.VaList(bp+72, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls,\n\t\tts+2950, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+88, isTemp(tls, 5), g.zNN, g.zPK, g.zNN, g.zNN, g.zWR))\n\tspeedtest1_prepare(tls, ts+3013 /* \"INSERT INTO t2 V...\" */, libc.VaList(bp+144, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, i)\n\t\tsqlite3.Xsqlite3_bind_int64(tls, g.pStmt, 2, sqlite3_int64(x1))\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 3, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 120, ts+3058 /* \"%d unordered INS...\" */, libc.VaList(bp+160, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls,\n\t\tts+3097, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+176, isTemp(tls, 3), g.zNN, g.zPK, g.zNN, g.zNN, g.zWR))\n\tspeedtest1_prepare(tls, ts+3160 /* \"INSERT INTO t3 V...\" */, libc.VaList(bp+232, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, i)\n\t\tsqlite3.Xsqlite3_bind_int64(tls, g.pStmt, 1, sqlite3_int64(x1))\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 3, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = 25\n\tspeedtest1_begin_test(tls, 130, ts+3205 /* \"%d SELECTS, nume...\" */, libc.VaList(bp+248, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+3244 /* \"SELECT count(*),...\" */, libc.VaList(bp+264, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + (uint32(sz / 5000))) + x1)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = 10\n\tspeedtest1_begin_test(tls, 140, ts+3349 /* \"%d SELECTS, LIKE...\" */, libc.VaList(bp+280, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+3377 /* \"SELECT count(*),...\" */, libc.VaList(bp+296, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8('%')\n\t\t\tlen = speedtest1_numbername(tls, uint32(i), (bp + 968 /* &zNum[0] */ + uintptr(1)), (int32(uint32(unsafe.Sizeof([2000]int8{})) - uint32(2))))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(len))) = int8('%')\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr((len + 1)))) = int8(0)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, (len + 1), uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = 10\n\tspeedtest1_begin_test(tls, 142, ts+3472 /* \"%d SELECTS w/ORD...\" */, libc.VaList(bp+312, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+3505 /* \"SELECT a, b, c F...\" */, libc.VaList(bp+328, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8('%')\n\t\t\tlen = speedtest1_numbername(tls, uint32(i), (bp + 968 /* &zNum[0] */ + uintptr(1)), (int32(uint32(unsafe.Sizeof([2000]int8{})) - uint32(2))))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(len))) = int8('%')\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr((len + 1)))) = int8(0)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, (len + 1), uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = 10 // g.szTest/5;\n\tspeedtest1_begin_test(tls, 145, ts+3569 /* \"%d SELECTS w/ORD...\" */, libc.VaList(bp+344, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+3612 /* \"SELECT a, b, c F...\" */, libc.VaList(bp+360, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8('%')\n\t\t\tlen = speedtest1_numbername(tls, uint32(i), (bp + 968 /* &zNum[0] */ + uintptr(1)), (int32(uint32(unsafe.Sizeof([2000]int8{})) - uint32(2))))\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(len))) = int8('%')\n\t\t\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr((len + 1)))) = int8(0)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, (len + 1), uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 150, ts+3685 /* \"CREATE INDEX fiv...\" */, 0)\n\tspeedtest1_exec(tls, ts+3709 /* \"BEGIN;\" */, 0)\n\tspeedtest1_exec(tls, ts+3716 /* \"CREATE UNIQUE IN...\" */, 0)\n\tspeedtest1_exec(tls, ts+3750 /* \"CREATE INDEX t1c...\" */, 0)\n\tspeedtest1_exec(tls, ts+3777 /* \"CREATE UNIQUE IN...\" */, 0)\n\tspeedtest1_exec(tls, ts+3811 /* \"CREATE INDEX t2c...\" */, 0)\n\tspeedtest1_exec(tls, ts+3843 /* \"CREATE INDEX t3b...\" */, 0)\n\tspeedtest1_exec(tls, ts+3873 /* \"COMMIT;\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 160, ts+3881 /* \"%d SELECTS, nume...\" */, libc.VaList(bp+376, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+3918 /* \"SELECT count(*),...\" */, libc.VaList(bp+392, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + (uint32(sz / 5000))) + x1)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 161, ts+4023 /* \"%d SELECTS, nume...\" */, libc.VaList(bp+408, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+4055 /* \"SELECT count(*),...\" */, libc.VaList(bp+424, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + (uint32(sz / 5000))) + x1)\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 170, ts+4160 /* \"%d SELECTS, text...\" */, libc.VaList(bp+440, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+4194 /* \"SELECT count(*),...\" */, libc.VaList(bp+456, n))\n\tfor i = 1; i <= n; i++ {\n\t\tif ((i - 1) % g.nRepeat) == 0 {\n\t\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\t\tlen = speedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, (int32(uint32(unsafe.Sizeof([2000]int8{})) - uint32(1))))\n\t\t}\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, len, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 180, ts+4306 /* \"%d INSERTS with ...\" */, libc.VaList(bp+472, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls,\n\n\t\tts+4336, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+488, isTemp(tls, 1), g.zNN, g.zPK, g.zNN, g.zNN, g.zWR))\n\tspeedtest1_exec(tls, ts+4407 /* \"CREATE INDEX t4b...\" */, 0)\n\tspeedtest1_exec(tls, ts+4433 /* \"CREATE INDEX t4c...\" */, 0)\n\tspeedtest1_exec(tls, ts+4459 /* \"INSERT INTO t4 S...\" */, 0)\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 190, ts+4491 /* \"DELETE and REFIL...\" */, libc.VaList(bp+544, n))\n\tspeedtest1_exec(tls, ts+4519 /* \"DELETE FROM t2;\" */, 0)\n\tspeedtest1_exec(tls, ts+4535 /* \"INSERT INTO t2 S...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 200, ts+4568 /* \"VACUUM\" */, 0)\n\tspeedtest1_exec(tls, ts+4568 /* \"VACUUM\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 210, ts+4575 /* \"ALTER TABLE ADD ...\" */, 0)\n\tspeedtest1_exec(tls, ts+4609 /* \"ALTER TABLE t2 A...\" */, 0)\n\tspeedtest1_exec(tls, ts+4649 /* \"SELECT sum(d) FR...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 230, ts+4671 /* \"%d UPDATES, nume...\" */, libc.VaList(bp+560, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\t\tts+4708 /* \"UPDATE t2 SET d=...\" */, libc.VaList(bp+576, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = (speedtest1_random(tls) % uint32(maxb))\n\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + (uint32(sz / 5000))) + x1)\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 240, ts+4767 /* \"%d UPDATES of in...\" */, libc.VaList(bp+592, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\t\tts+4797 /* \"UPDATE t2 SET d=...\" */, libc.VaList(bp+608, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = ((speedtest1_random(tls) % uint32(sz)) + uint32(1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 250, ts+4841 /* \"One big UPDATE o...\" */, libc.VaList(bp+624, sz))\n\tspeedtest1_exec(tls, ts+4882 /* \"UPDATE t2 SET d=...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 260, ts+4902 /* \"Query added colu...\" */, 0)\n\tspeedtest1_exec(tls, ts+4649 /* \"SELECT sum(d) FR...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 270, ts+4935 /* \"%d DELETEs, nume...\" */, libc.VaList(bp+640, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\t\tts+4972 /* \"DELETE FROM t2 W...\" */, libc.VaList(bp+656, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = ((speedtest1_random(tls) % uint32(maxb)) + uint32(1))\n\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + (uint32(sz / 5000))) + x1)\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = sz\n\tspeedtest1_begin_test(tls, 280, ts+5026 /* \"%d DELETEs of in...\" */, libc.VaList(bp+672, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\t\tts+5056 /* \"DELETE FROM t3 W...\" */, libc.VaList(bp+688, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = ((speedtest1_random(tls) % uint32(sz)) + uint32(1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 290, ts+5095 /* \"Refill two %d-ro...\" */, libc.VaList(bp+704, sz))\n\tspeedtest1_exec(tls, ts+5134 /* \"REPLACE INTO t2(...\" */, 0)\n\tspeedtest1_exec(tls, ts+5178 /* \"REPLACE INTO t3(...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 300, ts+5222 /* \"Refill a %d-row ...\" */, libc.VaList(bp+720, sz))\n\tspeedtest1_exec(tls, ts+4519 /* \"DELETE FROM t2;\" */, 0)\n\tspeedtest1_exec(tls,\n\t\tts+5263 /* \"INSERT INTO t2(a...\" */, 0)\n\tspeedtest1_exec(tls,\n\t\tts+5328 /* \"INSERT INTO t2(a...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tn = (sz / 5)\n\tspeedtest1_begin_test(tls, 310, ts+5393 /* \"%d four-ways joi...\" */, libc.VaList(bp+736, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_prepare(tls,\n\n\t\tts+5412 /* \"SELECT t1.c FROM...\" */, 0)\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = ((speedtest1_random(tls) % uint32(sz)) + uint32(1))\n\t\tx2 = (((speedtest1_random(tls) % uint32(10)) + x1) + uint32(4))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(x1))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, int32(x2))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 320, ts+5525 /* \"subquery in resu...\" */, libc.VaList(bp+752, n))\n\tspeedtest1_prepare(tls,\n\n\t\tts+5548 /* \"SELECT sum(a), m...\" */, 0)\n\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, (est_square_root(tls, g.szTest) * 50))\n\tspeedtest1_run(tls)\n\tspeedtest1_end_test(tls)\n\n\tsz = libc.AssignInt32(&n, (g.szTest * 700))\n\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8(0)\n\tmaxb = int32(roundup_allones(tls, (uint32(sz / 3))))\n\tspeedtest1_begin_test(tls, 400, ts+5666 /* \"%d REPLACE ops o...\" */, libc.VaList(bp+768, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls, ts+5691, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+784, isTemp(tls, 9), g.zNN))\n\tspeedtest1_prepare(tls, ts+5739 /* \"REPLACE INTO t5 ...\" */, libc.VaList(bp+808, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, uint32(i), bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(sqlite3_int64(x1)))\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 2, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\tspeedtest1_begin_test(tls, 410, ts+5783 /* \"%d SELECTS on an...\" */, libc.VaList(bp+824, n))\n\tspeedtest1_prepare(tls, ts+5804 /* \"SELECT b FROM t5...\" */, libc.VaList(bp+840, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 1, int32(sqlite3_int64(x1)))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_end_test(tls)\n\n\tsz = libc.AssignInt32(&n, (g.szTest * 700))\n\t*(*int8)(unsafe.Pointer(bp + 968 /* &zNum[0] */ + uintptr(0))) = int8(0)\n\tmaxb = int32(roundup_allones(tls, (uint32(sz / 3))))\n\tspeedtest1_begin_test(tls, 500, ts+5846 /* \"%d REPLACE on TE...\" */, libc.VaList(bp+856, n))\n\tspeedtest1_exec(tls, ts+2796 /* \"BEGIN\" */, 0)\n\tspeedtest1_exec(tls, ts+5868, /* \"CREATE%s TABLE t...\" */\n\t\tlibc.VaList(bp+872, isTemp(tls, 9), g.zNN,\n\t\t\tfunc() uintptr {\n\t\t\t\tif sqlite3.Xsqlite3_libversion_number(tls) >= 3008002 {\n\t\t\t\t\treturn ts + 5915 /* \"WITHOUT ROWID\" */\n\t\t\t\t}\n\t\t\t\treturn ts + 2152 /* \"\" */\n\t\t\t}()))\n\tspeedtest1_prepare(tls, ts+5929 /* \"REPLACE INTO t6 ...\" */, libc.VaList(bp+904, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_int(tls, g.pStmt, 2, i)\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_exec(tls, ts+2906 /* \"COMMIT\" */, 0)\n\tspeedtest1_end_test(tls)\n\tspeedtest1_begin_test(tls, 510, ts+5973 /* \"%d SELECTS on a ...\" */, libc.VaList(bp+920, n))\n\tspeedtest1_prepare(tls, ts+5997 /* \"SELECT b FROM t6...\" */, libc.VaList(bp+936, n))\n\tfor i = 1; i <= n; i++ {\n\t\tx1 = swizzle(tls, uint32(i), uint32(maxb))\n\t\tspeedtest1_numbername(tls, x1, bp+968 /* &zNum[0] */, int32(unsafe.Sizeof([2000]int8{})))\n\t\tsqlite3.Xsqlite3_bind_text(tls, g.pStmt, 1, bp+968 /* &zNum[0] */, -1, uintptr(0))\n\t\tspeedtest1_run(tls)\n\t}\n\tspeedtest1_end_test(tls)\n\tspeedtest1_begin_test(tls, 520, ts+6039 /* \"%d SELECT DISTIN...\" */, libc.VaList(bp+952, n))\n\tspeedtest1_exec(tls, ts+6058 /* \"SELECT DISTINCT ...\" */, 0)\n\tspeedtest1_exec(tls, ts+6085 /* \"SELECT DISTINCT ...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 980, ts+6112 /* \"PRAGMA integrity...\" */, 0)\n\tspeedtest1_exec(tls, ts+6112 /* \"PRAGMA integrity...\" */, 0)\n\tspeedtest1_end_test(tls)\n\n\tspeedtest1_begin_test(tls, 990, ts+6135 /* \"ANALYZE\" */, 0)\n\tspeedtest1_exec(tls, ts+6135 /* \"ANALYZE\" */, 0)\n\tspeedtest1_end_test(tls)\n}", "func TestWebServer(t *testing.T) {\n\n\tctx, _ := context.WithCancel(context.Background())\n\n\tif testing.Short() {\n\t\tt.Skip()\n\t}\n\n\t// create a new kuberhealthy\n\tt.Log(\"Making fake check\")\n\tkh := makeTestKuberhealthy(t)\n\n\t// add a fake check to it\n\tfc := NewFakeCheck()\n\tt.Log(\"Adding fake check\")\n\tkh.AddCheck(fc)\n\n\tt.Log(\"Starting Kuberhealthy checks\")\n\tgo kh.Start(ctx)\n\t// give the checker time to make CRDs\n\tt.Log(\"Waiting for checks to run\")\n\ttime.Sleep(time.Second * 2)\n\tt.Log(\"Stopping Kuberhealthy checks\")\n\tkh.StopChecks()\n\n\t// now run our test against the web server handler\n\tt.Log(\"Simulating web request\")\n\trecorder := httptest.NewRecorder()\n\treq, err := http.NewRequest(\"GET\", \"/\", bytes.NewBufferString(\"\"))\n\tif err != nil {\n\t\tt.Fatal(\"Error creating request\", err)\n\t}\n\terr = kh.healthCheckHandler(recorder, req)\n\tif err != nil {\n\t\tt.Fatal(\"Error from health check handler:\", err)\n\t}\n\n\t// check the http status from the server\n\tt.Log(\"Checking status code\")\n\tif recorder.Code != http.StatusOK {\n\t\tt.Fatal(\"Bad response from handler\", recorder.Code)\n\t}\n\n\t// output the response from the server\n\tt.Log(\"Reading reponse body\")\n\tb, err := ioutil.ReadAll(recorder.Body)\n\tif err != nil {\n\t\tt.Fatal(\"Error reading response body\", err)\n\t}\n\n\tt.Log(string(b))\n\n}", "func ConnHandshake(c *tls.Conn,) error", "func TestSmash(t *testing.T) {\n\tfmt.Println(\"This test is costs 4 puppies.\")\n\ttime.Sleep(1 * time.Second)\n\tfmt.Println(\"And takes 5 seconds\")\n\ttime.Sleep(1 * time.Second)\n\tvar wg sync.WaitGroup\n\tt1 := time.Now()\n\tfor u := 0; u < 2500; u++ { // Hit 10,000 URLs in 5 seconds\n\t\t//for u := 0; u < 10000; u++ { // Hit 40,000 URLs in 16.71 seconds\n\t\tfor hostname := range s.config {\n\t\t\twg.Add(1)\n\t\t\tgo func(i string) {\n\t\t\t\treq, e := http.NewRequest(\"GET\", i, nil)\n\t\t\t\tassert.Nil(t, e)\n\t\t\t\treq.Host = i\n\t\t\t\tw := httptest.NewRecorder()\n\t\t\t\tf := s\n\t\t\t\tf.ServeHTTP(w, req)\n\t\t\t\tassert.Equal(t, 200, w.Code)\n\t\t\t\tbod, _ := ioutil.ReadAll(w.Result().Body)\n\t\t\t\tswitch string(bod) {\n\t\t\t\tcase \"ONE\":\n\t\t\t\t\tassert.Equal(t, \"testOne.com\", i)\n\t\t\t\tcase \"TWO\":\n\t\t\t\t\tassert.Equal(t, \"testTwo.com\", i)\n\t\t\t\tcase \"THREE\":\n\t\t\t\t\tassert.Equal(t, \"testThree.com\", i)\n\t\t\t\tcase \"FOUR\":\n\t\t\t\t\tassert.Equal(t, \"testFour.com\", i)\n\t\t\t\t}\n\t\t\t\tif !t.Failed() {\n\t\t\t\t\tfmt.Println(\"Head:\", i, \"PASS\")\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(hostname)\n\t\t}\n\n\t\twg.Wait()\n\t\tif !t.Failed() {\n\t\t\tfmt.Println(\"Smash Test\", \"PASS\", time.Now().Sub(t1).String())\n\t\t}\n\t}\n}", "func TestTransportTimeoutServerHangs(t *testing.T) {\n\tclientDone := make(chan struct{})\n\tct := newClientTester(t)\n\tct.client = func() error {\n\t\tdefer ct.cc.(*net.TCPConn).CloseWrite()\n\t\tdefer close(clientDone)\n\n\t\tbuf := make([]byte, 1<<19)\n\t\t_, err := rand.Read(buf)\n\t\tif err != nil {\n\t\t\tt.Fatal(\"fail to gen random data\")\n\t\t}\n\t\theaderVal := hex.EncodeToString(buf)\n\n\t\treq, err := http.NewRequest(\"PUT\", \"https://dummy.tld/\", nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\t\tdefer cancel()\n\t\treq = req.WithContext(ctx)\n\t\treq.Header.Add(\"Authorization\", headerVal)\n\t\t_, err = ct.tr.RoundTrip(req)\n\t\tif err == nil {\n\t\t\treturn errors.New(\"error should not be nil\")\n\t\t}\n\t\tif ne, ok := err.(net.Error); !ok || !ne.Timeout() {\n\t\t\treturn fmt.Errorf(\"error should be a net error timeout was: +%v\", err)\n\t\t}\n\t\treturn nil\n\t}\n\tct.server = func() error {\n\t\tct.greet()\n\t\tselect {\n\t\tcase <-time.After(5 * time.Second):\n\t\tcase <-clientDone:\n\t\t}\n\t\treturn nil\n\t}\n\tct.run()\n}", "func TestXUpdateTLS_NoneToTLS(t *testing.T) {\n\tappaddr := \"127.0.0.1:8080\"\n\ttestCases := []*XExtendTLSUpdateCase{\n\t\tNewXExtendTLSUpdateCase(t, bolt.ProtocolName, util.NewRPCServer(t, appaddr, bolt.ProtocolName)),\n\t}\n\tfor i, tc := range testCases {\n\t\tverify := func() {\n\t\t\tselect {\n\t\t\tcase err := <-tc.C:\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"request failed, case %d, protocol %v, error: %v\", i, tc.Protocol, err)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\tt.Errorf(\"request hung up case %d, protocol %v\", i, tc.Protocol)\n\t\t\t}\n\t\t}\n\t\tt.Logf(\"start case #%d\\n\", i)\n\t\ttc.Start(false)\n\t\tgo tc.RequestTLS(false, 1, 0)\n\t\tt.Logf(\"verify non-tls\")\n\t\tverify()\n\t\t// update to tls\n\t\tif err := tc.UpdateTLS(false, []v2.TLSConfig{DefaultTLSConfig}); err != nil {\n\t\t\tt.Fatal(\"update tls failed\")\n\t\t}\n\t\tgo tc.RequestTLS(true, 1, 0)\n\t\tt.Logf(\"verify tls\")\n\t\tverify()\n\t\ttc.FinishCase()\n\n\t}\n}", "func (tc *testConn) handshake() {\n\ttc.t.Helper()\n\tif *testVV {\n\t\t*testVV = false\n\t\tdefer func() {\n\t\t\t*testVV = true\n\t\t\ttc.t.Logf(\"performed connection handshake\")\n\t\t}()\n\t}\n\tdefer func(saved map[byte]bool) {\n\t\ttc.ignoreFrames = saved\n\t}(tc.ignoreFrames)\n\ttc.ignoreFrames = nil\n\tt := tc.t\n\tdgrams := handshakeDatagrams(tc)\n\ti := 0\n\tfor {\n\t\tif i == len(dgrams)-1 {\n\t\t\tif tc.conn.side == clientSide {\n\t\t\t\twant := tc.now.Add(maxAckDelay - timerGranularity)\n\t\t\t\tif !tc.timer.Equal(want) {\n\t\t\t\t\tt.Fatalf(\"want timer = %v (max_ack_delay), got %v\", want, tc.timer)\n\t\t\t\t}\n\t\t\t\tif got := tc.readDatagram(); got != nil {\n\t\t\t\t\tt.Fatalf(\"client unexpectedly sent: %v\", got)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttc.advance(maxAckDelay)\n\t\t}\n\n\t\t// Check that we're sending exactly the data we expect.\n\t\t// Any variation from the norm here should be intentional.\n\t\tgot := tc.readDatagram()\n\t\tvar want *testDatagram\n\t\tif !(tc.conn.side == serverSide && i == 0) && i < len(dgrams) {\n\t\t\twant = dgrams[i]\n\t\t\tfillCryptoFrames(want, tc.cryptoDataOut)\n\t\t\ti++\n\t\t}\n\t\tif !reflect.DeepEqual(got, want) {\n\t\t\tt.Fatalf(\"dgram %v:\\ngot %v\\n\\nwant %v\", i, got, want)\n\t\t}\n\t\tif i >= len(dgrams) {\n\t\t\tbreak\n\t\t}\n\n\t\tfillCryptoFrames(dgrams[i], tc.cryptoDataIn)\n\t\ttc.write(dgrams[i])\n\t\ti++\n\t}\n}", "func Benchmark_Ctx_Send(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar str = \"Hello, World!\"\n\tvar byt = []byte(\"Hello, World!\")\n\tvar nmb = 123\n\tvar bol = true\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.Send(str)\n\t\tc.Send(byt)\n\t\tc.Send(nmb)\n\t\tc.Send(bol)\n\t}\n\tutils.AssertEqual(b, \"true\", string(c.Fasthttp.Response.Body()))\n}", "func (r *Report) TLSHandshakeTime() time.Duration {\n\treturn r.TLSHandshakeDone.Sub(r.TLSHandshakeStart)\n}", "func GenericTLSWrap(conn *net.TCPConn, cfg *tls.Config, tFunc TLSWrapperFunc) (*tls.Conn, error) {\n\tvar tConn *tls.Conn\n\n\ttCfg := cfg.Clone()\n\ttCfg.MinVersion = tls.VersionTLS12\n\n\tfor {\n\t\tif err := conn.SetDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttConn = tFunc(conn, tCfg)\n\n\t\t// check if the connection is upgraded before returning\n\t\t// we want to catch the error early\n\t\tif err := tConn.Handshake(); err != nil {\n\t\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\t\tif netErr.Timeout() || netErr.Temporary() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := conn.SetDeadline(time.Time{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbreak\n\t}\n\n\treturn tConn, nil\n}", "func init() {\n\t//\tflag.IntVar(&timeout, \"timeout\", 10, \"Seconds to max. wait for each response\")\n\t//\tflag.BoolVar(&disableCompression, \"disable-compression\", false, \"Disable compression\")\n\t//\tflag.BoolVar(&disableKeepalive, \"disable-keepalive\", true, \"Disable keepalive\")\n\t//\tflag.Parse()\n\n\t//\thttp.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 2000\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\tMaxIdleConnsPerHost: 2000,\n\t\tDisableCompression: false,\n\t\tDisableKeepAlives: false,\n\t}\n\tClient = &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: time.Duration(10) * time.Second,\n\t}\n}", "func testClientAuth(t *testing.T) {\n\tsrv := getServer(rootPort, testdataDir, \"\", 0, t)\n\tsrv = getTLSConfig(srv, \"RequireAndVerifyClientCert\", []string{\"../testdata/root.pem\"})\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Root server start failed: %s\", err)\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tclientConfig := &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t},\n\t}\n\n\trawURL := fmt.Sprintf(\"https://admin:adminpw@localhost:%d\", rootPort)\n\n\t// Enrolling without any client certificate and key information set\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err == nil {\n\t\tt.Errorf(\"Client Auth Type: RequireAndVerifyClientCert, should have failed as no client cert was provided\")\n\t}\n\n\t// Client created with certificate and key for TLS\n\tclientConfig = &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t\tClient: tls.KeyCertFiles{\n\t\t\t\tKeyFile: \"../testdata/tls_client-key.pem\",\n\t\t\t\tCertFile: \"../testdata/tls_client-cert.pem\",\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err != nil {\n\t\tt.Errorf(\"Client Auth Type: RequireAndVerifyClientCert, failed to enroll over TLS with client certificate provided\")\n\t}\n\n\terr = srv.Stop()\n\tif err != nil {\n\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t}\n}", "func TestLivenessHttp(c *client.Client) bool {\n\treturn runLivenessTest(c, \"http-liveness.yaml\")\n}", "func TLSServer() {\n\tif _, err := os.Stat(Temp + tun.WWW); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(Temp+tun.WWW, 0700)\n\t\tif err != nil {\n\t\t\tCliFatalError(\"TLSServer: %v\", err)\n\t\t}\n\t}\n\tr := mux.NewRouter()\n\n\t// Load CA\n\ttun.CACrt = []byte(RuntimeConfig.CAPEM)\n\n\t// handlers\n\tr.HandleFunc(fmt.Sprintf(\"/%s/{api}/{token}\", tun.WebRoot), dispatcher)\n\n\t// shutdown TLSServer if it's already running\n\tif EmpTLSServer != nil {\n\t\tEmpTLSServer.Shutdown(EmpTLSServerCtx)\n\t}\n\n\t// initialize EmpTLSServer\n\tEmpTLSServer = &http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", RuntimeConfig.CCPort), // C2 service port\n\t\tHandler: r, // use mux router\n\t}\n\tEmpTLSServerCtx, EmpTLSServerCancel = context.WithCancel(context.Background())\n\n\tCliPrintInfo(\"Starting C2 TLS service at port %s\", RuntimeConfig.CCPort)\n\t// emp3r0r.crt and emp3r0r.key is generated by build.sh\n\terr := EmpTLSServer.ListenAndServeTLS(EmpWorkSpace+\"/emp3r0r-cert.pem\", EmpWorkSpace+\"/emp3r0r-key.pem\")\n\tif err != nil {\n\t\tif err == http.ErrServerClosed {\n\t\t\tCliPrintWarning(\"C2 TLS service is shutdown\")\n\t\t\treturn\n\t\t}\n\t\tCliFatalError(\"Failed to start HTTPS server at *:%s\", RuntimeConfig.CCPort)\n\t}\n}", "func ListenAndServeTLS(addr string, handler http.Handler, crt Certifier) error {\n\tcerts := newCertCache(crt)\n\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\n\ts := http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t\tTLSConfig: &tls.Config{\n\t\t\tGetCertificate: func(h *tls.ClientHelloInfo) (c *tls.Certificate, err error) {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpromVPKICertError.With(prometheus.Labels{\"server_name\": h.ServerName}).Inc()\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tif h.ServerName == \"\" {\n\t\t\t\t\terr = fmt.Errorf(\"Cannot generate certs without TLS SNI (no server name was indicated)\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif crt, ok := crt.(SNICertifier); ok {\n\t\t\t\t\tc, err = crt.GetCertificate(h)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc, err = certs.get(h.ServerName)\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s.ListenAndServeTLS(\"\", \"\")\n}", "func (r *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {\n return http.ListenAndServeTLS(addr, certFile, keyFile, r.router)\n}", "func createTLSClient(serverName string, certFile string, keyFile string, caFile string) (*http.Client, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn &http.Client{}, err\n\t}\n\n\tca, err := ioutil.ReadFile(caFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn &http.Client{}, err\n\t}\n\tcertPool := x509.NewCertPool()\n\tcertPool.AppendCertsFromPEM(ca)\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t\tRootCAs: certPool,\n\t}\n\tif len(serverName) == 0 {\n\t\ttlsConfig.InsecureSkipVerify = true\n\t} else {\n\t\ttlsConfig.ServerName = serverName\n\t}\n\tdebuges(\"InsecureSkipVerify is set to %t\", tlsConfig.InsecureSkipVerify)\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{TLSClientConfig: tlsConfig},\n\t}, nil\n}", "func Benchmark_Ctx_SendBytes(b *testing.B) {\n\tapp := New()\n\tc := app.AcquireCtx(&fasthttp.RequestCtx{})\n\tdefer app.ReleaseCtx(c)\n\tvar byt = []byte(\"Hello, World!\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tc.SendBytes(byt)\n\t}\n\tutils.AssertEqual(b, \"Hello, World!\", string(c.Fasthttp.Response.Body()))\n}", "func testNoClientCert(t *testing.T) {\n\tsrv := getServer(rootPort, testdataDir, \"\", 0, t)\n\tsrv = getTLSConfig(srv, \"NoClientCert\", []string{})\n\n\terr := srv.Start()\n\tif err != nil {\n\t\tt.Fatalf(\"Root server start failed: %s\", err)\n\t}\n\n\ttime.Sleep(time.Second)\n\n\tclientConfig := &ClientConfig{\n\t\tURL: fmt.Sprintf(\"https://localhost:%d\", rootPort),\n\t\tTLS: tls.ClientTLSConfig{\n\t\t\tCertFiles: []string{\"../testdata/root.pem\"},\n\t\t},\n\t}\n\n\trawURL := fmt.Sprintf(\"https://admin:adminpw@localhost:%d\", rootPort)\n\n\t_, err = clientConfig.Enroll(rawURL, testdataDir)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to enroll over TLS with no client authentication required: %s\", err)\n\t}\n\n\terr = srv.Stop()\n\tif err != nil {\n\t\tt.Errorf(\"Server stop failed: %s\", err)\n\t}\n}" ]
[ "0.64035565", "0.62989646", "0.5874605", "0.5736923", "0.56831396", "0.568139", "0.5672263", "0.5621604", "0.559326", "0.5580611", "0.5565968", "0.5552248", "0.54870826", "0.5469495", "0.5454844", "0.54547435", "0.5453599", "0.54317886", "0.54296577", "0.5429156", "0.54179287", "0.5385852", "0.5364508", "0.53422844", "0.533497", "0.5312379", "0.531068", "0.5308773", "0.53016955", "0.52966094", "0.5289278", "0.52572393", "0.523107", "0.5229396", "0.52286994", "0.5216847", "0.52076876", "0.5201377", "0.51971173", "0.51959026", "0.51871884", "0.5184396", "0.5173966", "0.51717407", "0.51707226", "0.51679283", "0.51624715", "0.51406866", "0.5139251", "0.51369935", "0.5119453", "0.50906676", "0.5088123", "0.5074007", "0.5065666", "0.505899", "0.5051096", "0.5050092", "0.5045472", "0.5044997", "0.50383455", "0.49970996", "0.49935302", "0.4993221", "0.49914154", "0.4979641", "0.49761456", "0.49672478", "0.4962834", "0.49627987", "0.4953458", "0.4950163", "0.4949579", "0.4940508", "0.49401468", "0.49375954", "0.49364", "0.49362022", "0.4933352", "0.49249116", "0.49245995", "0.49221277", "0.49125075", "0.49108705", "0.4903285", "0.48996276", "0.48970497", "0.4896987", "0.4889259", "0.48848072", "0.48830903", "0.48777476", "0.48742318", "0.48723564", "0.4871113", "0.48709384", "0.48698497", "0.4866575", "0.48597953", "0.48578018" ]
0.6004358
2
make sure the elastic connection is intact during elasticsearch restarts
func (e *elasticsearchTestSuite) TestElasticsearchRestart(c *C) { elasticsearchName := c.TestName() signer, _, trustRoots, err := testutils.GetCAKit() Assert(c, err == nil, "Error getting CA artifacts") elasticAddr, dir, err := testutils.StartElasticsearch(elasticsearchName, "", signer, trustRoots) Assert(c, err == nil, fmt.Sprintf("failed to start elasticsearch container, err: %v", err)) defer testutils.StopElasticsearch(elasticsearchName, dir) var esClient elastic.ESClient ctx := context.Background() // create mock resolver mr := mockresolver.New() si := &types.ServiceInstance{ TypeMeta: api.TypeMeta{ Kind: "ServiceInstance", }, ObjectMeta: api.ObjectMeta{ Name: globals.ElasticSearch, }, Service: globals.ElasticSearch, URL: elasticAddr, } // add mock elastic service to mock resolver mr.AddServiceInstance(si) logger := log.GetNewLogger(&log.Config{ Module: c.TestName(), Format: log.LogFmt, Filter: log.AllowAllFilter, Debug: true, CtxSelector: log.ContextAll, LogToStdout: true, LogToFile: false, }) // create elastic client AssertEventually(c, func() (bool, interface{}) { esClient, err = testutils.CreateElasticClient("", mr, logger, signer, trustRoots) if err != nil { log.Errorf("error creating client: %v", err) return false, nil } log.Infof("created elastic client") return true, nil }, "failed to create elastic client", "10ms", "2m") // check elasticsearch cluster health AssertEventually(c, func() (bool, interface{}) { return esClient.IsClusterHealthy(ctx) }, "failed to get elasticsearch cluster health") mapping, err := mapper.ElasticMapper(eventObj, elastic.String(globals.Events), mapper.WithShardCount(1), mapper.WithReplicaCount(0)) AssertOk(c, err, "Failed to generate elastic mapping for events") // Generate JSON string for the mapping configs, err := mapping.JSONString() AssertOk(c, err, "Failed to get JSONString from elastic mapper") runtime.GOMAXPROCS(runtime.NumCPU()) errs := make(chan error, 10) defer close(errs) prevResetCount := 0 for re := 0; re < 5; re++ { var wg sync.WaitGroup wg.Add(2) // restart elasticsearch server in intervals go func() { defer wg.Done() testutils.StopElasticsearch(elasticsearchName, dir) mr.DeleteServiceInstance(si) time.Sleep(100 * time.Millisecond) elasticAddr, dir, err = testutils.StartElasticsearch(elasticsearchName, dir, signer, trustRoots) if err != nil { errs <- fmt.Errorf("failed to start elasticsearch, err:%v", err) return } // update elastic address si.URL = elasticAddr mr.AddServiceInstance(si) }() go func() { defer wg.Done() // use the above created client to perform elastic operations for i := 0; i < 10; i++ { // create index if err := esClient.CreateIndex(ctx, fmt.Sprintf("%s%d", indexName, i), configs); err != nil && !elastic.IsIndexExists(err) && !elastic.IsConnRefused(err) { errs <- fmt.Errorf("failed to create index, err: %v", err.Error()) return } // index a document if err := esClient.Index(ctx, indexName, fmt.Sprintf("test%d", i), `{}`); err != nil && !elastic.IsIndexNotExists(err) && !elastic.IsConnRefused(err) { errs <- fmt.Errorf("failed to perform index operation, err: %v", err.Error()) return } // bulk index documents if _, err := esClient.Bulk(ctx, []*elastic.BulkRequest{ {RequestType: elastic.Index, Index: indexName, Obj: "{}", ID: "dummy1"}, {RequestType: elastic.Index, Index: indexName, Obj: "{}", ID: "dummy2"}, }); err != nil && !elastic.IsConnRefused(err) { errs <- fmt.Errorf("failed to perform bulk operation, err: %v", err.Error()) return } } // make the restart happened resetCount := esClient.GetResetCount() if resetCount < prevResetCount { errs <- fmt.Errorf("expected client to be reset") return } prevResetCount = resetCount }() wg.Wait() // non-blocking receive on the error channel select { case er := <-errs: log.Fatalf("failed with err: %v", er) default: break } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func OpenElasticSearchConnection(esAddr, mainIndex, secondIndex, thirdIndex string) *EngineConfig {\n\tvar r map[string]interface{}\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\tesAddr,\n\t\t},\n\t}\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating the client: %s\", err)\n\t}\n\tres, err := es.Info()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting response: %s\", err)\n\t}\n\t// Check response status\n\tif res.IsError() {\n\t\tlog.Fatalf(\"Error: %s\", res.String())\n\t}\n\t// Deserialize the response into a map.\n\tif err := json.NewDecoder(res.Body).Decode(&r); err != nil {\n\t\tlog.Fatalf(\"Error parsing the response body: %s\", err)\n\t}\n\t// Print client and server version numbers.\n\tlog.Printf(\"Client: %s\", elasticsearch.Version)\n\tlog.Printf(\"Server: %s\", r[\"version\"].(map[string]interface{})[\"number\"])\n\tlog.Println(strings.Repeat(\"~\", 37))\n\n\tEngineClient.Client = es\n\tEngineClient.MainIndexName = mainIndex\n\tEngineClient.SecondIndexName = secondIndex\n\tEngineClient.ThirdIndexName = thirdIndex\n\n\treturn &EngineClient\n}", "func ESConn(t *testing.T) *elastic.Client {\n\tes, err := elastic.NewClient(elastic.SetURL(constants.EsAddress))\n\trequire.NoError(t, err, \"unable to connect to ES\")\n\treturn es\n}", "func Setup(conf model.ElasticLoggingConfig) (*Elastic, error) {\n\ttlsCfg, err := elasticTLSConfig(conf.Security.TLS)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to make elastic tls config\")\n\t}\n\n\tvar scheme string\n\tif tlsCfg != nil {\n\t\tscheme = \"https://\"\n\t} else {\n\t\tscheme = \"http://\"\n\t}\n\taddr := fmt.Sprintf(\"%s%s:%d\", scheme, conf.Host, conf.Port)\n\tlog.Infof(\"connecting to elasticsearch %s\", addr)\n\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{addr},\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsCfg,\n\t\t},\n\t}\n\n\tif conf.Security.Username != nil && conf.Security.Password != nil {\n\t\tcfg.Username = *conf.Security.Username\n\t\tcfg.Password = *conf.Security.Password\n\t}\n\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create elastic client from config\")\n\t}\n\n\t// Try to connect to elastic - we'd rather fail hard here than on first log write.\n\tnumTries := 0\n\tfor {\n\t\ti, err := es.Info()\n\t\tif err == nil {\n\t\t\tlog.Infof(\"connected to elasticsearch cluster with info: %s\", i.String())\n\t\t\treturn &Elastic{es}, nil\n\t\t}\n\t\tnumTries++\n\t\t// Elastic can take a really long time to come up and we'd rather not fail integrations on this.\n\t\tif numTries >= 45 {\n\t\t\treturn nil, errors.Wrapf(err, \"could not connect to elastic after %v tries\", numTries)\n\t\t}\n\t\ttoWait := 4 * time.Second\n\t\ttime.Sleep(toWait)\n\t\tlog.WithError(err).Warnf(\"failed to connect to elastic, trying again in %s\", toWait)\n\t}\n}", "func (e ElasticSearch) Flush() {\n\te.client.Flush().\n\t\tIndex(e.index).\n\t\tAllowNoIndices(true).\n\t\tIgnoreUnavailable(true).\n\t\tDo()\n}", "func newBgMetadataElasticSearchConnector(elasticSearchClient ElasticSearchClient, registry prometheus.Registerer, bulkSize, maxRetry uint, indexName, IndexDateFmt string) *BgMetadataElasticSearchConnector {\n\tvar esc = BgMetadataElasticSearchConnector{\n\t\tclient: elasticSearchClient,\n\t\tBulkSize: bulkSize,\n\t\tbulkBuffer: make([]ElasticSearchDocument, 0, bulkSize),\n\t\tMaxRetry: maxRetry,\n\t\tIndexName: indexName,\n\t\tIndexDateFmt: IndexDateFmt,\n\n\t\tUpdatedDocuments: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"updated_documents\",\n\t\t\tHelp: \"total number of documents updated in ElasticSearch splited between metrics and directories\",\n\t\t}, []string{\"status\", \"type\"}),\n\n\t\tHTTPErrors: prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"http_errors\",\n\t\t\tHelp: \"total number of http errors encountered partitionned by status code\",\n\t\t}, []string{\"code\"}),\n\n\t\tWriteDurationMs: prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"write_duration_ms\",\n\t\t\tHelp: \"time spent writing to ElasticSearch based on `took` field of response \",\n\t\t\tBuckets: []float64{250, 500, 750, 1000, 1500, 2000, 5000, 10000}}),\n\n\t\tRequestSize: prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"write_request_size_bytes\",\n\t\t\tHelp: \"Size of batch create requests performed on elasticsearch\",\n\t\t\tBuckets: []float64{10000, 100000, 1000000, 5000000, 10000000, 20000000, 50000000}}),\n\n\t\tDocumentBuildDurationMs: prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"document_build_duration_ms\",\n\t\t\tHelp: \"time spent building an ElasticSearch document\",\n\t\t\tBuckets: []float64{1, 5, 10, 50, 100, 250, 500, 750, 1000, 2000}}),\n\t\tlogger: zap.L(),\n\t}\n\t_ = registry.Register(esc.UpdatedDocuments)\n\t_ = registry.Register(esc.WriteDurationMs)\n\t_ = registry.Register(esc.DocumentBuildDurationMs)\n\t_ = registry.Register(esc.HTTPErrors)\n\t_ = registry.Register(esc.RequestSize)\n\tif esc.IndexName == \"\" {\n\t\tesc.IndexName = default_metrics_metadata_index\n\t}\n\tif esc.IndexDateFmt == \"\" {\n\t\tesc.DirectoriesIndexAlias = fmt.Sprintf(\"%s_%s\", esc.IndexName, directories_index_suffix)\n\t\tesc.MetricsIndexAlias = fmt.Sprintf(\"%s_%s\", esc.IndexName, metrics_index_suffix)\n\t}\n\n\tesc.KnownIndices = map[string]bool{}\n\treturn &esc\n}", "func EnsureESIsSetup() (ok bool) {\n\tvar es ES\n\n\tes.Init(os.Getenv(\"ES_PORT\"))\n\n\tqs := QueryBody{\n\t\tCarrierName: \"Logstash Airways\",\n\t\tCancelled: \"all\",\n\t\tDelayed: \"all\",\n\t\tDestCountry: \"all\",\n\t\tOriginCountry: \"all\",\n\t\tStartDate: \"02/13/2020\",\n\t\tEndDate: \"02/19/2020\",\n\t}\n\n\tstartDate, _ := ConvertTimeLayoutToISO(qs.StartDate)\n\tendDate, _ := ConvertTimeLayoutToISO(qs.EndDate)\n\n\t_, totalHits, ok := es.GetDocumentsByQuery(qs, startDate, endDate)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif totalHits == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (elasticCluster *ElasticCluster) Init() error {\n\t//加载配置文件\n\tif err := elasticCluster.loadConfig(); err != nil {\n\t\tlog.Logger.Error(\"load adapter file error\")\n\t\treturn err\n\t}\n\tlog.Logger.Info(\"load adapter file success\")\n\n\t//拼接urls\n\tvar urls []string\n\tfor _, elasticNode := range elasticCluster.ElasticNodes {\n\t\turl := \"http://\" + elasticNode.IP + \":\" + elasticNode.Port\n\t\turls = append(urls, url)\n\t}\n\n\t//创建client\n\telasticClient, err := elastic.NewClient(elastic.SetURL(urls...), elastic.SetSniff(elasticCluster.Sniff),\n\t\telastic.SetHealthcheck(elasticCluster.Healthcheck), elastic.SetBasicAuth(elasticCluster.User, elasticCluster.Password))\n\tif err != nil {\n\t\tlog.Logger.Error(\"create client for ES error\")\n\t\treturn err\n\t}\n\tlog.Logger.Info(\"create client for ES success\")\n\n\t//client赋值\n\telasticCluster.Client = elasticClient\n\n\t//验证index/type是否存在\n\tif mapping, err := elasticClient.GetMapping().Index(elasticCluster.Index).\n\t\tType(elasticCluster.TypeAlias).Do(context.Background()); err != nil || len(mapping) == 0 {\n\t\tlog.Logger.Warn(\"type is not exist\")\n\t\tif err := elasticCluster.createType(); err != nil {\n\t\t\tlog.Logger.Error(\"create type error\")\n\t\t\treturn err\n\t\t}\n\t\tlog.Logger.Info(\"create type success\")\n\t} else {\n\t\tlog.Logger.Info(\"type is already exist\")\n\t}\n\treturn nil\n}", "func (out *elasticsearchOutput) Init(beat string, config outputs.MothershipConfig, topology_expire int) error {\n\n\tif len(config.Protocol) == 0 {\n\t\tconfig.Protocol = \"http\"\n\t}\n\n\tvar urls []string\n\n\tif len(config.Hosts) > 0 {\n\t\t// use hosts setting\n\t\tfor _, host := range config.Hosts {\n\t\t\turl := fmt.Sprintf(\"%s://%s%s\", config.Protocol, host, config.Path)\n\t\t\turls = append(urls, url)\n\t\t}\n\t} else {\n\t\t// use host and port settings\n\t\turl := fmt.Sprintf(\"%s://%s:%d%s\", config.Protocol, config.Host, config.Port, config.Path)\n\t\turls = append(urls, url)\n\t}\n\n\tes := NewElasticsearch(urls, config.Username, config.Password)\n\tout.Conn = es\n\n\tif config.Index != \"\" {\n\t\tout.Index = config.Index\n\t} else {\n\t\tout.Index = beat\n\t}\n\n\tout.TopologyExpire = 15000\n\tif topology_expire != 0 {\n\t\tout.TopologyExpire = topology_expire /*sec*/ * 1000 // millisec\n\t}\n\n\tout.FlushInterval = 1000 * time.Millisecond\n\tif config.Flush_interval != nil {\n\t\tout.FlushInterval = time.Duration(*config.Flush_interval) * time.Millisecond\n\t}\n\tout.BulkMaxSize = 10000\n\tif config.Bulk_size != nil {\n\t\tout.BulkMaxSize = *config.Bulk_size\n\t}\n\n\tif config.Max_retries != nil {\n\t\tout.Conn.SetMaxRetries(*config.Max_retries)\n\t}\n\n\tlogp.Info(\"[ElasticsearchOutput] Using Elasticsearch %s\", urls)\n\tlogp.Info(\"[ElasticsearchOutput] Using index pattern [%s-]YYYY.MM.DD\", out.Index)\n\tlogp.Info(\"[ElasticsearchOutput] Topology expires after %ds\", out.TopologyExpire/1000)\n\tif out.FlushInterval > 0 {\n\t\tlogp.Info(\"[ElasticsearchOutput] Insert events in batches. Flush interval is %s. Bulk size is %d.\", out.FlushInterval, out.BulkMaxSize)\n\t} else {\n\t\tlogp.Info(\"[ElasticsearchOutput] Insert events one by one. This might affect the performance of the shipper.\")\n\t}\n\n\tif config.Save_topology {\n\t\terr := out.EnableTTL()\n\t\tif err != nil {\n\t\t\tlogp.Err(\"Fail to set _ttl mapping: %s\", err)\n\t\t\t// keep trying in the background\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\terr := out.EnableTTL()\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tlogp.Err(\"Fail to set _ttl mapping: %s\", err)\n\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\tout.sendingQueue = make(chan EventMsg, 1000)\n\tgo out.SendMessagesGoroutine()\n\n\treturn nil\n}", "func (es *Etcd) trySetDefault() {\n\tif len(es.Endpoints) == 0 {\n\t\tes.Endpoints = []string{\"127.0.0.1:2379\"}\n\t}\n\n\tif es.DialTimeoutMS == 0 {\n\t\tes.DialTimeoutMS = 200\n\t}\n}", "func init() {\n\terr := NewElasticSearchClient()\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n}", "func (logsProvider *esLogsProvider) Init() error {\n\tf := logsProvider.Framework\n\t// Check for the existence of the Elasticsearch service.\n\tBy(\"Checking the Elasticsearch service exists.\")\n\ts := f.ClientSet.Core().Services(api.NamespaceSystem)\n\t// Make a few attempts to connect. This makes the test robust against\n\t// being run as the first e2e test just after the e2e cluster has been created.\n\tvar err error\n\tfor start := time.Now(); time.Since(start) < esRetryTimeout; time.Sleep(esRetryDelay) {\n\t\tif _, err = s.Get(\"elasticsearch-logging\", meta_v1.GetOptions{}); err == nil {\n\t\t\tbreak\n\t\t}\n\t\tframework.Logf(\"Attempt to check for the existence of the Elasticsearch service failed after %v\", time.Since(start))\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Wait for the Elasticsearch pods to enter the running state.\n\tBy(\"Checking to make sure the Elasticsearch pods are running\")\n\tlabelSelector := fields.SelectorFromSet(fields.Set(map[string]string{\"k8s-app\": \"elasticsearch-logging\"})).String()\n\toptions := meta_v1.ListOptions{LabelSelector: labelSelector}\n\tpods, err := f.ClientSet.Core().Pods(api.NamespaceSystem).List(options)\n\tExpect(err).NotTo(HaveOccurred())\n\tfor _, pod := range pods.Items {\n\t\terr = framework.WaitForPodRunningInNamespace(f.ClientSet, &pod)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t}\n\n\tBy(\"Checking to make sure we are talking to an Elasticsearch service.\")\n\t// Perform a few checks to make sure this looks like an Elasticsearch cluster.\n\tvar statusCode int\n\terr = nil\n\tvar body []byte\n\tfor start := time.Now(); time.Since(start) < esRetryTimeout; time.Sleep(esRetryDelay) {\n\t\tproxyRequest, errProxy := framework.GetServicesProxyRequest(f.ClientSet, f.ClientSet.Core().RESTClient().Get())\n\t\tif errProxy != nil {\n\t\t\tframework.Logf(\"After %v failed to get services proxy request: %v\", time.Since(start), errProxy)\n\t\t\tcontinue\n\t\t}\n\t\t// Query against the root URL for Elasticsearch.\n\t\tresponse := proxyRequest.Namespace(api.NamespaceSystem).\n\t\t\tName(\"elasticsearch-logging\").\n\t\t\tDo()\n\t\terr = response.Error()\n\t\tresponse.StatusCode(&statusCode)\n\n\t\tif err != nil {\n\t\t\tframework.Logf(\"After %v proxy call to elasticsearch-loigging failed: %v\", time.Since(start), err)\n\t\t\tcontinue\n\t\t}\n\t\tif int(statusCode) != 200 {\n\t\t\tframework.Logf(\"After %v Elasticsearch cluster has a bad status: %v\", time.Since(start), statusCode)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\tif int(statusCode) != 200 {\n\t\tframework.Failf(\"Elasticsearch cluster has a bad status: %v\", statusCode)\n\t}\n\n\t// Now assume we really are talking to an Elasticsearch instance.\n\t// Check the cluster health.\n\tBy(\"Checking health of Elasticsearch service.\")\n\thealthy := false\n\tfor start := time.Now(); time.Since(start) < esRetryTimeout; time.Sleep(esRetryDelay) {\n\t\tproxyRequest, errProxy := framework.GetServicesProxyRequest(f.ClientSet, f.ClientSet.Core().RESTClient().Get())\n\t\tif errProxy != nil {\n\t\t\tframework.Logf(\"After %v failed to get services proxy request: %v\", time.Since(start), errProxy)\n\t\t\tcontinue\n\t\t}\n\t\tbody, err = proxyRequest.Namespace(api.NamespaceSystem).\n\t\t\tName(\"elasticsearch-logging\").\n\t\t\tSuffix(\"_cluster/health\").\n\t\t\tParam(\"level\", \"indices\").\n\t\t\tDoRaw()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\thealth := make(map[string]interface{})\n\t\terr := json.Unmarshal(body, &health)\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Bad json response from elasticsearch: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tstatusIntf, ok := health[\"status\"]\n\t\tif !ok {\n\t\t\tframework.Logf(\"No status field found in cluster health response: %v\", health)\n\t\t\tcontinue\n\t\t}\n\t\tstatus := statusIntf.(string)\n\t\tif status != \"green\" && status != \"yellow\" {\n\t\t\tframework.Logf(\"Cluster health has bad status: %v\", health)\n\t\t\tcontinue\n\t\t}\n\t\tif err == nil && ok {\n\t\t\thealthy = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !healthy {\n\t\treturn fmt.Errorf(\"after %v elasticsearch cluster is not healthy\", esRetryTimeout)\n\t}\n\n\treturn nil\n}", "func (d *Dao) pingESCluster(ctx context.Context) (err error) {\n\t//for name, client := range d.ESPool {\n\t//\tif _, _, err = client.Ping(d.c.Es[name].Addr[0]).Do(ctx); err != nil {\n\t//\t\td.PromError(\"Es:Ping\", \"%s:Ping error(%v)\", name, err)\n\t//\t\treturn\n\t//\t}\n\t//}\n\treturn\n}", "func CheckESConnection(es EsConnection) error {\n\t_, err := executeEsRequest(es, http.MethodGet, \"/\", nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"there was a problem while connecting to the ES instance: %s\", err)\n\t}\n\treturn nil\n}", "func (dn *DNode) SoftRestart() error {\n\tvar err error\n\n\t// first stop everythig\n\tdn.isStopped = true\n\tdn.watcher.Stop()\n\tdn.tshards.Range(func(key interface{}, value interface{}) bool {\n\t\tshard := value.(*TshardState)\n\t\t// clean up syncbuffer\n\t\tdn.deleteShardSyncBuffer(&shard.syncBuffer)\n\n\t\tif shard.store != nil {\n\t\t\tshard.store.Close()\n\t\t\tshard.store = nil\n\t\t}\n\t\treturn true\n\t})\n\tdn.kshards.Range(func(key interface{}, value interface{}) bool {\n\t\tshard := value.(*KshardState)\n\t\t// clean up syncbuffer\n\t\tdn.deleteShardSyncBuffer(&shard.syncBuffer)\n\t\tif shard.kstore != nil {\n\t\t\tshard.kstore.Close()\n\t\t\tshard.kstore = nil\n\t\t}\n\t\treturn true\n\t})\n\n\t// close the rpc clients\n\tdn.rpcClients.Range(func(key interface{}, value interface{}) bool {\n\t\trc, ok := value.(*rpckit.RPCClient)\n\t\tif ok {\n\t\t\trc.Close()\n\t\t\tdn.rpcClients.Delete(key)\n\t\t}\n\t\treturn true\n\t})\n\n\t// stop rpc server\n\tdn.rpcServer.Stop()\n\n\t// restart everything back up\n\tdn.isStopped = false\n\n\t// Start a rpc server\n\tdn.rpcServer, err = rpckit.NewRPCServer(globals.Citadel, dn.nodeURL, rpckit.WithLoggerEnabled(false))\n\tif err != nil {\n\t\tdn.logger.Errorf(\"failed to listen to %s: Err %v\", dn.nodeURL, err)\n\t\treturn err\n\t}\n\n\t// create watcher\n\tdn.watcher, err = meta.NewWatcher(dn.nodeUUID, dn.clusterCfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// register RPC handlers\n\ttproto.RegisterDataNodeServer(dn.rpcServer.GrpcServer, dn)\n\tdn.rpcServer.Start()\n\tdn.logger.Infof(\"Datanode RPC server is listening on: %s\", dn.nodeURL)\n\n\t// read all shard state from metadata store and restore it\n\terr = dn.readAllShards(dn.clusterCfg)\n\tif err != nil {\n\t\tdn.logger.Errorf(\"Error reading state from metadata store. Err: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (rs *RedisCluster) trySetDefault() {\n\tif len(rs.Endpoints) == 0 {\n\t\trs.Endpoints = []string{\"127.0.0.1:6379\"}\n\t}\n\n\tif rs.DialTimeoutMS == 0 {\n\t\trs.DialTimeoutMS = 100\n\t}\n\n\tif rs.ReadTimeoutMS == 0 {\n\t\trs.ReadTimeoutMS = 500\n\t}\n\n\tif rs.WriteTimeoutMS == 0 {\n\t\trs.WriteTimeoutMS = 500\n\t}\n\n\tif rs.MinIdleConn == 0 {\n\t\trs.MinIdleConn = 10\n\t}\n\n\tif rs.PoolSize == 0 {\n\t\trs.PoolSize = 300\n\t}\n\n\tif rs.MaxSlowLogLatencyMS == 0 {\n\t\trs.MaxSlowLogLatencyMS = 100\n\t}\n\n}", "func MustOpenConnection() *elastic.Client {\n\tc, err := elastic.NewClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}", "func (e *esearch) wipe() error {\n\n\t// Delete indexes\n\tdeleteIndexResp, err := e.client.DeleteIndex(e.index + \"-*\").Do(e.ctx)\n\tif elastic.IsNotFound(err) {\n\t\t// We're good\n\t} else if elastic.IsStatusCode(err, 400) {\n\t\t// This means that it's an alias and not an index, also okay\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"Failed to remove Elasticsearch base index '%s' error: %v\", e.index+\"*\", err)\n\t} else if !deleteIndexResp.Acknowledged {\n\t\treturn fmt.Errorf(\"Failed to receive Elasticsearch delete indexes response\")\n\t}\n\n\t// Delete Aliases\n\tdeleteAliasesRepsonse, err := e.client.Alias().Remove(\"*\", e.index+\"-*\").Do(e.ctx)\n\tif elastic.IsNotFound(err) {\n\t\t// We're good\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"Failed to remove Elasticsearch partition aliases '%s' error: %v\", e.index+\"*\", err)\n\t} else if !deleteAliasesRepsonse.Acknowledged {\n\t\treturn fmt.Errorf(\"Failed to receive Elasticsearch delete partition aliases response\")\n\t}\n\n\treturn nil\n}", "func (t *tInfo) startElasticsearch() error {\n\tvar err error\n\tt.elasticsearchName = uuid.NewV4().String()\n\tt.elasticsearchAddr, t.elasticsearchDir, err = testutils.StartElasticsearch(t.elasticsearchName, t.elasticsearchDir, t.signer, t.trustRoots)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start elasticsearch, err: %v\", err)\n\t}\n\n\t// add mock elastic service to mock resolver\n\tt.updateResolver(globals.ElasticSearch, t.elasticsearchAddr)\n\treturn nil\n}", "func (t *tInfo) createElasticClient() error {\n\tvar err error\n\tt.esClient, err = testutils.CreateElasticClient(t.elasticsearchAddr, t.mockResolver, t.logger, t.signer, t.trustRoots)\n\treturn err\n}", "func ElasticDump(opt Options) (err error) {\n\tif opt.Debug {\n\t\tlogger.Level = logrus.DebugLevel\n\t}\n\n\tinputElasticURL, inputElasticIndexName, isInputFile, err := parseElasticURL(opt.InputElasticURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tif isInputFile {\n\t\treturn fmt.Errorf(`file input not suported`)\n\t}\n\tinputClient, err := elastic.NewClient(\n\t\telastic.SetURL(inputElasticURL),\n\t\telastic.SetSniff(opt.InputElasticSniff),\n\t\telastic.SetBasicAuth(opt.InputBasicAuth.BasicUsername, opt.InputBasicAuth.BasicPassword),\n\t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutputElasticURL, outputElasticIndexName, isOutputFile, err := parseElasticURL(opt.OutputElasticURL)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar outputClient *elastic.Client\n\tvar outputFile *os.File\n\n\tif isOutputFile {\n\t\toutputFile, err = os.OpenFile(outputElasticIndexName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toutputClient, err = elastic.NewClient(\n\t\t\telastic.SetURL(outputElasticURL),\n\t\t\telastic.SetSniff(opt.OutputElasticSniff),\n\t\t\telastic.SetBasicAuth(opt.OutputBasicAuth.BasicUsername, opt.OutputBasicAuth.BasicPassword),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tctx := context.Background()\n\tctx = contextWithOSSignal(ctx, os.Interrupt, os.Kill)\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tlogger.Debug(\"start\")\n\n\ttotalDoc, err := inputClient.Count(inputElasticIndexName).Do(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\tbar := pb.New64(totalDoc).Start()\n\tdefer bar.Finish()\n\n\thits := make(chan elasticMessage, opt.ScrollSize)\n\tg.Go(func() error {\n\t\tdefer close(hits)\n\n\t\t// Initialize scroller. Just don't call Do yet.\n\t\tscroll := inputClient.Scroll(inputElasticIndexName).Size(opt.ScrollSize)\n\n\t\treturn getData(ctx, hits, scroll)\n\t})\n\n\tsavedHits := make(chan elasticMessage, opt.ScrollSize)\n\tg.Go(func() error {\n\t\tdefer close(savedHits)\n\n\t\tif isOutputFile {\n\t\t\treturn setDataFile(ctx, hits, savedHits, outputFile)\n\t\t}\n\n\t\toutputBulkProcess, err2 := outputClient.BulkProcessor().\n\t\t\tName(\"golasticdump-output\").\n\t\t\tBulkActions(opt.BulkActions).\n\t\t\tBulkSize(opt.BulkSize).\n\t\t\tFlushInterval(opt.BulkFlushInterval).\n\t\t\tDo(ctx)\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\n\t\tif err2 := setData(ctx, hits, savedHits, outputBulkProcess, outputElasticIndexName); err2 != nil {\n\t\t\treturn err2\n\t\t}\n\n\t\tlogger.Debug(\"closing output bulk process\")\n\t\treturn outputBulkProcess.Close()\n\t})\n\n\tg.Go(func() error {\n\t\tinputBulkProcess, err2 := inputClient.BulkProcessor().\n\t\t\tName(\"golasticdump-input\").\n\t\t\tBulkActions(opt.BulkActions).\n\t\t\tBulkSize(opt.BulkSize).\n\t\t\tFlushInterval(opt.BulkFlushInterval).\n\t\t\tDo(ctx)\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\n\t\tif err2 := delData(ctx, savedHits, inputBulkProcess, opt.Delete, bar); err2 != nil {\n\t\t\treturn err2\n\t\t}\n\n\t\tlogger.Debug(\"closing input bulk process\")\n\t\treturn inputBulkProcess.Close()\n\t})\n\n\t// Check whether any goroutines failed.\n\tif err = g.Wait(); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (e *dockerEngine) Recover() {\n\t// clean old services in docker mode\n\te.clean()\n}", "func (esHandler *ESHandler) Close() error {\n\tlog.Println(\"Stopping Elasticsearch client\")\n\tesHandler.Client.Stop()\n\treturn nil\n}", "func dialElastic(esNotify elasticSearchNotify) (*elastic.Client, error) {\n\tif !esNotify.Enable {\n\t\treturn nil, errNotifyNotEnabled\n\t}\n\treturn elastic.NewClient(\n\t\telastic.SetURL(esNotify.URL),\n\t\telastic.SetSniff(false),\n\t\telastic.SetMaxRetries(10),\n\t)\n}", "func (dn *DNode) readAllShards(cfg *meta.ClusterConfig) error {\n\t// read current state of the cluster and restore the shards\n\t// FIXME: if etcd was unreachable when we come up we need to handle it\n\tif cfg.EnableTstore {\n\t\tdbfiles := dn.getDbFiles(meta.ClusterTypeTstore)\n\n\t\tcluster, err := meta.GetClusterState(cfg, meta.ClusterTypeTstore)\n\t\tif err == nil {\n\t\t\tfor _, shard := range cluster.ShardMap.Shards {\n\t\t\t\tfor _, repl := range shard.Replicas {\n\t\t\t\t\tif repl.NodeUUID == dn.nodeUUID {\n\t\t\t\t\t\tdbPath := dn.getDbPath(meta.ClusterTypeTstore, repl.ReplicaID)\n\t\t\t\t\t\tdelete(dbfiles, dbPath)\n\t\t\t\t\t\tts, serr := tstore.NewTstore(dbPath)\n\t\t\t\t\t\tif serr != nil {\n\t\t\t\t\t\t\tdn.logger.Errorf(\"Error creating tstore at %s. Err: %v\", dbPath, serr)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// create a shard instance\n\t\t\t\t\t\t\ttshard := TshardState{\n\t\t\t\t\t\t\t\treplicaID: repl.ReplicaID,\n\t\t\t\t\t\t\t\tshardID: repl.ShardID,\n\t\t\t\t\t\t\t\tisPrimary: repl.IsPrimary,\n\t\t\t\t\t\t\t\tstore: ts,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdn.logger.Infof(\"Restored tstore replica %d shard %d\", repl.ReplicaID, repl.ShardID)\n\n\t\t\t\t\t\t\t// collect all replicas in this shard\n\t\t\t\t\t\t\tvar replicaList []*tproto.ReplicaInfo\n\t\t\t\t\t\t\tfor _, sr := range shard.Replicas {\n\t\t\t\t\t\t\t\t// get node for url\n\t\t\t\t\t\t\t\tnode, nerr := cluster.GetNode(sr.NodeUUID)\n\t\t\t\t\t\t\t\tif nerr != nil {\n\t\t\t\t\t\t\t\t\t// recover if it is our own node missing in the node map\n\t\t\t\t\t\t\t\t\tif sr.NodeUUID == dn.nodeUUID {\n\t\t\t\t\t\t\t\t\t\tlog.Warnf(\"failed to find node %v in node list\", sr.NodeUUID)\n\t\t\t\t\t\t\t\t\t\t// recover\n\t\t\t\t\t\t\t\t\t\tnode = &meta.NodeState{\n\t\t\t\t\t\t\t\t\t\t\tNodeUUID: dn.nodeUUID,\n\t\t\t\t\t\t\t\t\t\t\tNodeURL: dn.nodeURL,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Errorf(\"failed to find node %v in node list\", sr.NodeUUID)\n\t\t\t\t\t\t\t\t\t\treturn nerr\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// build replica info\n\t\t\t\t\t\t\t\trpinfo := tproto.ReplicaInfo{\n\t\t\t\t\t\t\t\t\tClusterType: meta.ClusterTypeTstore,\n\t\t\t\t\t\t\t\t\tReplicaID: sr.ReplicaID,\n\t\t\t\t\t\t\t\t\tShardID: sr.ShardID,\n\t\t\t\t\t\t\t\t\tIsPrimary: sr.IsPrimary,\n\t\t\t\t\t\t\t\t\tNodeUUID: sr.NodeUUID,\n\t\t\t\t\t\t\t\t\tNodeURL: node.NodeURL,\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treplicaList = append(replicaList, &rpinfo)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttshard.replicas = replicaList\n\n\t\t\t\t\t\t\t// save the datastore\n\t\t\t\t\t\t\tdn.tshards.Store(repl.ReplicaID, &tshard)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k := range dbfiles {\n\t\t\tlog.Infof(\"deleting replica file %v\", k)\n\t\t\tif err := os.RemoveAll(k); err != nil {\n\t\t\t\tlog.Errorf(\"failed to delete %v, %v\", k, err)\n\t\t\t}\n\t\t}\n\n\t}\n\t// restore all kstore shards\n\tif cfg.EnableKstore {\n\t\tdbfiles := dn.getDbFiles(meta.ClusterTypeKstore)\n\n\t\tcluster, err := meta.GetClusterState(cfg, meta.ClusterTypeKstore)\n\t\tif err == nil {\n\t\t\tfor _, shard := range cluster.ShardMap.Shards {\n\t\t\t\tfor _, repl := range shard.Replicas {\n\t\t\t\t\tif repl.NodeUUID == dn.nodeUUID {\n\t\t\t\t\t\tdbPath := dn.getDbPath(meta.ClusterTypeKstore, repl.ReplicaID)\n\t\t\t\t\t\tdelete(dbfiles, dbPath)\n\n\t\t\t\t\t\tks, serr := kstore.NewKstore(kstore.BoltDBType, dbPath)\n\t\t\t\t\t\tif serr != nil {\n\t\t\t\t\t\t\tdn.logger.Errorf(\"Error creating kstore at %s. Err: %v\", dbPath, serr)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// create a shard instance\n\t\t\t\t\t\t\tkshard := KshardState{\n\t\t\t\t\t\t\t\treplicaID: repl.ReplicaID,\n\t\t\t\t\t\t\t\tshardID: repl.ShardID,\n\t\t\t\t\t\t\t\tisPrimary: repl.IsPrimary,\n\t\t\t\t\t\t\t\tkstore: ks,\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdn.logger.Infof(\"Restored kstore replica %d shard %d\", repl.ReplicaID, repl.ShardID)\n\n\t\t\t\t\t\t\t// collect all replicas in this shard\n\t\t\t\t\t\t\tvar replicaList []*tproto.ReplicaInfo\n\t\t\t\t\t\t\tfor _, sr := range shard.Replicas {\n\t\t\t\t\t\t\t\t// get node for url\n\t\t\t\t\t\t\t\tnode, nerr := cluster.GetNode(sr.NodeUUID)\n\t\t\t\t\t\t\t\tif nerr != nil {\n\t\t\t\t\t\t\t\t\t// recover if it is our own node missing in the node map\n\t\t\t\t\t\t\t\t\tif sr.NodeUUID == dn.nodeUUID {\n\t\t\t\t\t\t\t\t\t\tlog.Warnf(\"failed to find node %v in node list\", sr.NodeUUID)\n\t\t\t\t\t\t\t\t\t\t// recover\n\t\t\t\t\t\t\t\t\t\tnode = &meta.NodeState{\n\t\t\t\t\t\t\t\t\t\t\tNodeUUID: dn.nodeUUID,\n\t\t\t\t\t\t\t\t\t\t\tNodeURL: dn.nodeURL,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Errorf(\"failed to find node %v in node list\", sr.NodeUUID)\n\t\t\t\t\t\t\t\t\t\treturn nerr\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t// build replica info\n\t\t\t\t\t\t\t\trpinfo := tproto.ReplicaInfo{\n\t\t\t\t\t\t\t\t\tClusterType: meta.ClusterTypeKstore,\n\t\t\t\t\t\t\t\t\tReplicaID: sr.ReplicaID,\n\t\t\t\t\t\t\t\t\tShardID: sr.ShardID,\n\t\t\t\t\t\t\t\t\tIsPrimary: sr.IsPrimary,\n\t\t\t\t\t\t\t\t\tNodeUUID: sr.NodeUUID,\n\t\t\t\t\t\t\t\t\tNodeURL: node.NodeURL,\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treplicaList = append(replicaList, &rpinfo)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tkshard.replicas = replicaList\n\n\t\t\t\t\t\t\t// save the datastore\n\t\t\t\t\t\t\tdn.kshards.Store(repl.ReplicaID, &kshard)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k := range dbfiles {\n\t\t\tlog.Infof(\"deleting replica file %v\", k)\n\t\t\tif err := os.RemoveAll(k); err != nil {\n\t\t\t\tlog.Errorf(\"failed to delete %v, %v\", k, err)\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func ensureClient(config hz.Config) *hz.Client {\n\tfor i := 0; i < 60; i++ {\n\t\tclient, err := hz.StartNewClientWithConfig(context.Background(), config)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, hzerrors.ErrClientNotAllowedInCluster) {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\t\treturn client\n\t}\n\tpanic(\"the client could not connect to the cluster in 60 seconds.\")\n}", "func (ec *ElasticClient) InitAllMappings() {\n\tec.DeleteIndex(string(\"collectd_*\"))\n\tec.DeleteIndex(string(\"ceilometer_*\"))\n\tec.DeleteIndex(string(\"generic_*\"))\n}", "func (ns *EsIndexer) Start(grpcClient types.AergoRPCServiceClient, reindex bool) error {\n\turl := ns.esURL\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = fmt.Sprintf(\"http://%s\", url)\n\t}\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\thttpClient := &http.Client{Transport: tr}\n\tclient, err := elastic.NewClient(\n\t\telastic.SetHttpClient(httpClient),\n\t\telastic.SetURL(url),\n\t\telastic.SetHealthcheckTimeoutStartup(30*time.Second),\n\t\telastic.SetSniff(false),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tns.client = client\n\tns.grpcClient = grpcClient\n\n\tif reindex {\n\t\tns.log.Warn().Msg(\"Reindexing database. Will sync from scratch and replace index aliases when caught up\")\n\t\tns.reindexing = true\n\t}\n\n\tns.CreateIndexIfNotExists(\"tx\")\n\tns.CreateIndexIfNotExists(\"block\")\n\tns.CreateIndexIfNotExists(\"name\")\n\tns.UpdateLastBlockHeightFromDb()\n\tns.log.Info().Uint64(\"lastBlockHeight\", ns.lastBlockHeight).Msg(\"Started Elasticsearch Indexer\")\n\n\tgo ns.CheckConsistency()\n\n\treturn ns.StartStream()\n}", "func elasticSearchContainerSpec(cr *wp.WebProject) corev1.Container {\n\timage := \"elasticsearch:7.10.1\"\n\tcontainer := corev1.Container{\n\t\tImage: image,\n\t\tName: \"search\",\n\t\tPorts: []corev1.ContainerPort{\n\t\t\t{\n\t\t\t\tContainerPort: int32(9200),\n\t\t\t\tName: \"reset-port\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerPort: int32(9300),\n\t\t\t\tName: \"intra-node-port\",\n\t\t\t},\n\t\t},\n\t\tLifecycle: &corev1.Lifecycle{\n\t\t\tPostStart: &corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t/*StartupProbe: &corev1.Probe{\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tPeriodSeconds: 2,\n\t\t\tHandler: corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},*/\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"discovery.type\",\n\t\t\t\tValue: \"single-node\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"ES_JAVA_OPTS\",\n\t\t\t\tValue: \"-Xms512m -Xmx512m\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAME\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.name\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_ID\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.uid\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAMESPACE\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tVolumeMounts: getElasticSearchVolumeMounts(cr),\n\n\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\tAllowPrivilegeEscalation: createBool(false),\n\t\t\tReadOnlyRootFilesystem: createBool(false),\n\t\t\tRunAsNonRoot: createBool(false),\n\t\t},\n\t}\n\n\tif cr.Spec.SearchSidecar.CronJob.Enabled {\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{\n\t\t\tName: \"search-cron-script\",\n\t\t\tMountPath: \"/opt/script\",\n\t\t})\n\t}\n\n\treturn container\n}", "func (s *Server) Init(dbconf, env, esurl, fluentHost string) {\n\tcs, err := db.NewConfigsFromFile(dbconf)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot open database configuration. exit. %s\", err)\n\t}\n\tdb, err := cs.Open(env)\n\tif err != nil {\n\t\tlog.Fatalf(\"db initialization failed: %s\", err)\n\t}\n\ts.db = db\n\n\tclient, err := elastic.NewClient(\n\t\telastic.SetURL(esurl),\n\t\telastic.SetMaxRetries(5),\n\t\telastic.SetSniff(false))\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize Elasticsearch client failed: %s\", err)\n\t}\n\ts.es = client\n\n\tfor {\n\t\tlogger, err := fluent.New(fluent.Config{\n\t\t\tFluentHost: fluentHost,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Printf(\"initialize fluentd client failed: %s\", err)\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\ts.fluent = logger\n\t\tbreak\n\t}\n\n\t// NOTE: define helper func to use from templates here.\n\tt := template.Must(template.New(\"\").Funcs(template.FuncMap{\n\t\t\"LoggedIn\": controller.LoggedIn,\n\t\t\"CurrentName\": controller.CurrentName,\n\t\t\"nl2br\": func(text string) template.HTML {\n\t\t\treturn template.HTML(strings.Replace(template.HTMLEscapeString(text), \"\\n\", \"<br>\", -1))\n\t\t},\n\t}).ParseGlob(\"templates/*\"))\n\ts.Engine.SetHTMLTemplate(t)\n\n\tstore := sessions.NewCookieStore([]byte(\"secretkey\"))\n\ts.Engine.Use(sessions.Sessions(\"blogsession\", store))\n\ts.Engine.Use(csrf.Middleware(csrf.Options{\n\t\tSecret: \"secretkey\",\n\t\tErrorFunc: func(c *gin.Context) {\n\t\t\tc.String(400, \"CSRF token mismach\")\n\t\t\tc.Abort()\n\t\t},\n\t}))\n\n\ts.Route()\n}", "func (e *Exporter) TryClientConnection() {\n\tfor {\n\t\tif tryConnectCnt > 5 {\n\t\t\tutil.LogFatalAndExit(nil, \"%s: ovn-monitor failed to reconnect db socket finally\", e.Client.System.Hostname)\n\t\t}\n\n\t\tif err := e.StartConnection(); err != nil {\n\t\t\ttryConnectCnt++\n\t\t\tklog.Errorf(\"%s: ovn-monitor failed to reconnect db socket %v times\", e.Client.System.Hostname, tryConnectCnt)\n\t\t} else {\n\t\t\tklog.Infof(\"%s: ovn-monitor reconnect db successfully\", e.Client.System.Hostname)\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}", "func (es *EtcdService) startHeartBeating() {\n\tsafego.RunWithRestart(func() {\n\t\tfor {\n\t\t\tif es.closed {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err := es.heartBeat(); err != nil {\n\t\t\t\tlogging.Errorf(\"Error heart beat to etcd: %v\", err)\n\t\t\t\t//delay after error\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttime.Sleep(90 * time.Second)\n\t\t}\n\t})\n}", "func (c *Connection) healthCheck() {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(healthCheckTime):\n\t\t\tif !c.Retrying {\n\t\t\t\t// capture current rmq host\n\t\t\t\toldHost := c.Config.Host\n\n\t\t\t\tif err := c.validateHost(); err != nil {\n\t\t\t\t\tkillService(\"failed to validate rmq host: \", err)\n\t\t\t\t}\n\n\t\t\t\t// this means new host was assigned meanwhile (in c.validateHost())\n\t\t\t\tif oldHost != c.Config.Host {\n\t\t\t\t\tif err := c.recreateConn(); err != nil {\n\t\t\t\t\t\tkillService(\"failed to recreate rmq connection: \", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Println(\"rmq connected to new host: \", c.Config.Host)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (bu *Builder) Elastic(elastic *elasticsearch.Client) *Builder {\n\tbu.srv.elastic = elastic\n\treturn bu\n}", "func main() {\n\t// Create a client\n\tclient, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdeleteIndex, err := client.DeleteIndex(INDEX).Do()\n\tif err != nil {\n\t\t// Handle error\n\t\tpanic(err)\n\t}\n\tif !deleteIndex.Acknowledged {\n\t\t// Not acknowledged\n\t}\n\n}", "func TestEventsMgrWithElasticRestart(t *testing.T) {\n\tti := tInfo{dedupInterval: 300 * time.Second, batchInterval: 100 * time.Millisecond}\n\tAssertOk(t, ti.setup(t), \"failed to setup test\")\n\tdefer ti.teardown()\n\n\tnumRecorders := 3\n\n\tstopEventRecorders := make(chan struct{})\n\twg := new(sync.WaitGroup)\n\twg.Add(numRecorders + 1) // +1 for elastic restart go routine\n\n\t// uuid to make each source unique\n\tcomponentID := uuid.NewV4().String()\n\ttotalEventsSentBySrc := make([]int, numRecorders)\n\n\t// create recorder events directory\n\trecorderEventsDir, err := ioutil.TempDir(\"\", \"\")\n\tAssertOk(t, err, \"failed to create recorder events directory\")\n\tdefer os.RemoveAll(recorderEventsDir)\n\tfor i := 0; i < numRecorders; i++ {\n\t\tgo func(i int) {\n\t\t\tevtsRecorder, err := recorder.NewRecorder(&recorder.Config{\n\t\t\t\tComponent: fmt.Sprintf(\"%v-%v\", componentID, i),\n\t\t\t\tEvtsProxyURL: ti.evtProxyServices.EvtsProxy.RPCServer.GetListenURL(),\n\t\t\t\tBackupDir: recorderEventsDir}, ti.logger)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to create recorder for source %v\", i)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tti.recorders.Lock()\n\t\t\tti.recorders.list = append(ti.recorders.list, evtsRecorder)\n\t\t\tti.recorders.Unlock()\n\n\t\t\tticker := time.NewTicker(100 * time.Millisecond)\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stopEventRecorders:\n\t\t\t\t\twg.Done()\n\t\t\t\t\treturn\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tevtsRecorder.Event(eventtypes.SERVICE_RUNNING, \"test event - 1\", nil)\n\t\t\t\t\ttotalEventsSentBySrc[i]++\n\n\t\t\t\t\tevtsRecorder.Event(eventtypes.SERVICE_UNRESPONSIVE, \"test event - 2\", nil)\n\t\t\t\t\ttotalEventsSentBySrc[i]++\n\n\t\t\t\t\tevtsRecorder.Event(eventtypes.SERVICE_STOPPED, \"test event - 3\", nil)\n\t\t\t\t\ttotalEventsSentBySrc[i]++\n\t\t\t\t}\n\t\t\t}\n\t\t}(i)\n\t}\n\n\t// restart elasticsearch multiple times\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tfor i := 0; i < 3; i++ {\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t\ttestutils.StopElasticsearch(ti.elasticsearchName, ti.elasticsearchDir)\n\t\t\tti.removeResolverEntry(globals.ElasticSearch, ti.elasticsearchAddr)\n\n\t\t\t// let elasticsearch come up on the same port as before.\n\t\t\t// so, wait for the port to become available\n\t\t\tAssertEventually(t,\n\t\t\t\tfunc() (bool, interface{}) {\n\t\t\t\t\ttemp := strings.Split(ti.elasticsearchAddr, \":\")\n\t\t\t\t\tif len(temp) != 2 {\n\t\t\t\t\t\treturn false, fmt.Sprintf(\"invalid elastic addr: %v\", ti.elasticsearchAddr)\n\t\t\t\t\t}\n\n\t\t\t\t\tport, err := strconv.Atoi(temp[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, fmt.Sprintf(\"invalid elastic port: %v\", temp[1])\n\n\t\t\t\t\t}\n\t\t\t\t\tif getAvailablePort(port, port) == port {\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\n\t\t\t\t\treturn false, fmt.Sprintf(\"elastic port not yet available\")\n\t\t\t\t}, \"port not available to start elasticsearch\", \"50ms\", \"5s\")\n\t\t\tti.elasticsearchAddr, ti.elasticsearchDir, err = testutils.StartElasticsearch(ti.elasticsearchName, ti.elasticsearchDir, ti.signer, ti.trustRoots)\n\t\t\tAssertOk(t, err, \"failed to start elasticsearch, err: %v\", err)\n\t\t\tti.updateResolver(globals.ElasticSearch, ti.elasticsearchAddr)\n\t\t}\n\n\t\ttime.Sleep(5 * time.Second)\n\t\tclose(stopEventRecorders) // stop all the recorders\n\t}()\n\n\twg.Wait()\n\n\t//total events sent by all the recorders\n\ttotalEventsSent := 0\n\tfor _, val := range totalEventsSentBySrc {\n\t\ttotalEventsSent += val\n\t}\n\n\t// total number of events received at elastic should match the total events sent\n\t// query all the events received from this source.component\n\tquery := es.NewRegexpQuery(\"source.component.keyword\", fmt.Sprintf(\"%v-.*\", componentID))\n\tti.assertElasticUniqueEvents(t, query, true, 3*numRecorders, \"120s\")\n\tti.assertElasticTotalEvents(t, query, false, totalEventsSent, \"120s\")\n\tAssert(t, ti.esClient.GetResetCount() > 0, \"client should have restarted\")\n}", "func TestIngesterRestart(t *testing.T) {\n\tconfig := defaultIngesterTestConfig()\n\tclientConfig := defaultClientTestConfig()\n\tlimits := defaultLimitsTestConfig()\n\tconfig.LifecyclerConfig.UnregisterOnShutdown = false\n\n\t{\n\t\t_, ingester := newTestStore(t, config, clientConfig, limits, nil)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t// Doesn't actually unregister due to UnregisterFromRing: false.\n\t\trequire.NoError(t, services.StopAndAwaitTerminated(context.Background(), ingester))\n\t}\n\n\ttest.Poll(t, 100*time.Millisecond, 1, func() interface{} {\n\t\treturn testutils.NumTokens(config.LifecyclerConfig.RingConfig.KVStore.Mock, \"localhost\", ring.IngesterRingKey)\n\t})\n\n\t{\n\t\t_, ingester := newTestStore(t, config, clientConfig, limits, nil)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t// Doesn't actually unregister due to UnregisterFromRing: false.\n\t\trequire.NoError(t, services.StopAndAwaitTerminated(context.Background(), ingester))\n\t}\n\n\ttime.Sleep(200 * time.Millisecond)\n\n\ttest.Poll(t, 100*time.Millisecond, 1, func() interface{} {\n\t\treturn testutils.NumTokens(config.LifecyclerConfig.RingConfig.KVStore.Mock, \"localhost\", ring.IngesterRingKey)\n\t})\n}", "func (rs *RedisService) startHeartBeating() {\n\tsafego.RunWithRestart(func() {\n\t\tfor {\n\t\t\tif rs.closed {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err := rs.heartBeat(); err != nil {\n\t\t\t\tlogging.Errorf(\"Error heart beat to redis: %v\", err)\n\t\t\t\t//delay after error\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttime.Sleep(90 * time.Second)\n\t\t}\n\t})\n}", "func CreateElasticSearchConfig(uri *url.URL) (*ElasticSearchConfig, error) {\n\n\tvar esConfig ElasticSearchConfig\n\topts, err := url.ParseQuery(uri.RawQuery)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parser url's query string: %s\", err)\n\t}\n\n\t// set the index for es,the default value is \"heapster\"\n\tesConfig.Index = ESIndex\n\tif len(opts[\"index\"]) > 0 {\n\t\tesConfig.Index = opts[\"index\"][0]\n\t}\n\n\t// Set the URL endpoints of the ES's nodes. Notice that when sniffing is\n\t// enabled, these URLs are used to initially sniff the cluster on startup.\n\tif len(opts[\"nodes\"]) < 1 {\n\t\treturn nil, fmt.Errorf(\"There is no node assigned for connecting ES cluster\")\n\t}\n\n\tstartupFns := []elastic.ClientOptionFunc{elastic.SetURL(opts[\"nodes\"]...)}\n\n\t// If the ES cluster needs authentication, the username and secret\n\t// should be set in sink config.Else, set the Authenticate flag to false\n\tif len(opts[\"esUserName\"]) > 0 && len(opts[\"esUserSecret\"]) > 0 {\n\t\tstartupFns = append(startupFns, elastic.SetBasicAuth(opts[\"esUserName\"][0], opts[\"esUserSecret\"][0]))\n\t}\n\n\tif len(opts[\"maxRetries\"]) > 0 {\n\t\tmaxRetries, err := strconv.Atoi(opts[\"maxRetries\"][0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse URL's maxRetries value into an int\")\n\t\t}\n\t\tstartupFns = append(startupFns, elastic.SetMaxRetries(maxRetries))\n\t}\n\n\tif len(opts[\"healthCheck\"]) > 0 {\n\t\thealthCheck, err := strconv.ParseBool(opts[\"healthCheck\"][0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse URL's healthCheck value into a bool\")\n\t\t}\n\t\tstartupFns = append(startupFns, elastic.SetHealthcheck(healthCheck))\n\t}\n\n\tif len(opts[\"sniff\"]) > 0 {\n\t\tsniff, err := strconv.ParseBool(opts[\"sniff\"][0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse URL's sniff value into a bool\")\n\t\t}\n\t\tstartupFns = append(startupFns, elastic.SetSniff(sniff))\n\t}\n\n\tif len(opts[\"startupHealthcheckTimeout\"]) > 0 {\n\t\ttimeout, err := time.ParseDuration(opts[\"startupHealthcheckTimeout\"][0] + \"s\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to parse URL's startupHealthcheckTimeout: %s\", err.Error())\n\t\t}\n\t\tstartupFns = append(startupFns, elastic.SetHealthcheckTimeoutStartup(timeout))\n\t}\n\n\tesConfig.EsClient, err = elastic.NewClient(startupFns...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create ElasticSearch client: %v\", err)\n\t}\n\n\tglog.V(2).Infof(\"elasticsearch sink configure successfully\")\n\n\treturn &esConfig, nil\n}", "func crashAndFastRestore(t *testing.T) {\n\tvar err error\n\tproxyURL := tutils.RandomProxyURL(t)\n\tsmap := tutils.GetClusterMap(t, proxyURL)\n\ttlog.Logf(\"targets: %d, proxies: %d\\n\", smap.CountActiveTargets(), smap.CountActiveProxies())\n\n\t// Make sure proxyURL is not primary URL.\n\t_, proxyURL, err = chooseNextProxy(smap)\n\ttassert.CheckFatal(t, err)\n\toldPrimaryID := smap.Primary.ID()\n\ttlog.Logf(\"The current primary %s, Smap version %d\\n\", oldPrimaryID, smap.Version)\n\n\tcmd, err := tutils.KillNode(smap.Primary)\n\ttassert.CheckFatal(t, err)\n\n\t// quick crash and recover\n\ttime.Sleep(2 * time.Second)\n\terr = tutils.RestoreNode(cmd, true, \"proxy (primary)\")\n\ttassert.CheckFatal(t, err)\n\n\ttlog.Logf(\"The %s is currently restarting\\n\", oldPrimaryID)\n\n\t// NOTE: using (version - 1) because the primary will restart with its old version,\n\t// there will be no version change for this restore, so force beginning version to 1 less\n\t// than the original version in order to use WaitForClusterState.\n\tsmap, err = tutils.WaitForClusterState(proxyURL, \"restore\", smap.Version-1, 0, 0)\n\ttassert.CheckFatal(t, err)\n\n\tif smap.Primary.ID() != oldPrimaryID {\n\t\tt.Fatalf(\"Wrong primary proxy: %s, expecting: %s\", smap.Primary.ID(), oldPrimaryID)\n\t}\n}", "func Init() {\n\n\tvar err error\n\n\tclient, err := elastic.NewClient(\n\t\telastic.SetURL(\"http://127.0.0.1:9200\"),\n\t\telastic.SetHealthcheckInterval(10*time.Second),\n\t\telastic.SetErrorLog(log.New(os.Stderr, \"ELASTIC: \", log.LstdFlags)),\n\t\telastic.SetInfoLog(log.New(os.Stdout, \"\", log.LstdFlags)),\n\t\t//elastic.SetHeaders(http.Header{\n\t\t//\t\"X-User-Id\": []string{\"...\"},\n\t\t//}),\n\t)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tClient.setClient(client)\n}", "func (s *HttpServer) recover() {\n\tlog.Println(\"recovering from database if any job exists and not expired\")\n\t_job := job.Job{}\n\t_jobs, err := _job.List(s.db)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _,_job = range _jobs {\n\t\t if (_job.EndDate.Unix()<0 || _job.EndDate.UnixNano() > time.Now().UnixNano()) && _job.IsActive {\n\t\t\tentryID, err := s.cron.AddJob(_job.Frequency, _job)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\t_job.CronEntryID = int(entryID)\n\t\t\terr = _job.Update(s.db)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}else if _job.CronEntryID>0 {\n\t\t\t_job.CronEntryID=0\n\t\t\terr = _job.Update(s.db)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func Index(data []byte){\n\n api.Domain = \"localhost\"\n fmt.Println(\"Entered inside elasticgo file...lets do this\")\n response, _ := core.Index(\"scalegray_sample\", \"first_sampleset\", \"3\", nil, data)\n fmt.Println(response)\n fmt.Println(\"Done pushing the data into elastic search..woohoo!\")\n}", "func (k *Kinsumer) refreshShards() (bool, error) {\n\tvar shardIDs []string\n\n\tif err := registerWithClientsTable(k.dynamodb, k.clientID, k.clientName, k.clientsTableName); err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"clientsTableName\": k.clientsTableName,\n\t\t\t\"name\": k.clientName,\n\t\t\t\"clientID\": k.clientID,\n\t\t\t\"err\": err.Error(),\n\t\t}).Error(\"Error registering with clients table\")\n\t\treturn false, err\n\t}\n\n\t//TODO: Move this out of refreshShards and into refreshClients\n\tclients, err := getClients(k.dynamodb, k.clientID, k.clientsTableName, k.maxAgeForClientRecord)\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"clientsTableName\": k.clientsTableName,\n\t\t\t\"clientID\": k.clientID,\n\t\t\t\"err\": err.Error(),\n\t\t}).Error(\"Error getting clients\")\n\t\treturn false, err\n\t}\n\n\ttotalClients := len(clients)\n\tthisClient := 0\n\n\tfound := false\n\tfor i, c := range clients {\n\t\tif c.ID == k.clientID {\n\t\t\tthisClient = i\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn false, ErrThisClientNotInDynamo\n\t}\n\n\tif thisClient == 0 && !k.isLeader {\n\t\tk.becomeLeader()\n\t} else if thisClient != 0 && k.isLeader {\n\t\tk.unbecomeLeader()\n\t}\n\n\tshardIDs, err = loadShardIDsFromDynamo(k.dynamodb, k.metadataTableName)\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"metadataTableName\": k.metadataTableName,\n\t\t\t\"err\": err.Error(),\n\t\t}).Error(\"Error loading shardIds from dynamo\")\n\t\treturn false, err\n\t}\n\n\tif len(shardIDs) == 0 {\n\t\tshardIDs, err = loadShardIDsFromKinesis(k.kinesis, k.streamName)\n\t\tif err == nil {\n\t\t\terr = k.setCachedShardIDs(shardIDs)\n\t\t}\n\t}\n\n\tif err != nil {\n\t\t\treturn false, err\n }\n\n\tchanged := (totalClients != k.totalClients) ||\n\t\t(thisClient != k.thisClient) ||\n\t\t(len(k.shardIDs) != len(shardIDs))\n\n\tif !changed {\n\t\tfor idx := range shardIDs {\n\t\t\tif shardIDs[idx] != k.shardIDs[idx] {\n\t\t\t\tchanged = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif changed {\n\t\tk.shardIDs = shardIDs\n\t}\n\n\tk.thisClient = thisClient\n\tk.totalClients = totalClients\n\n\tlogger.WithFields(logrus.Fields{\n\t\t\"name\": k.clientName,\n\t\t\"clientID\": k.clientID,\n\t}).Info(\"Successfully refreshed shards\")\n\n\treturn changed, nil\n}", "func Startup() {\n\n\tlog.Println(\"[elk] config file : \", viper.ConfigFileUsed())\n\n\thttpAddr = viper.GetString(\"elasticsearch.listen\")\n\toutputFileName := viper.GetString(\"elasticsearch.output\")\n\n\t// Catch signals to cleanup before exiting\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM|syscall.SIGKILL)\n\tgo func() {\n\t\t<-c\n\t\tShutdown()\n\t}()\n\n\trunning = true\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/healthcheck\", healthCheckHandler)\n\tmux.HandleFunc(\"/_bulk\", bulkHandler)\n\tmux.HandleFunc(\"/_shutdown\", shutdownHandler)\n\tmux.HandleFunc(\"/\", allHandler)\n\tlogger := negroni.NewLogger()\n\tlogger.SetFormat(\"{{.StartTime}} | {{.Status}} | \\t {{.Duration}} | {{.Hostname}} | {{.Method}} {{.Path}}\")\n\tn := negroni.New(negroni.NewRecovery(), logger, negroni.NewStatic(http.Dir(\"public\")))\n\tn.UseHandler(mux)\n\n\tif 0 < len(outputFileName) {\n\t\tvar err error\n\t\tlog.Println(\"[elk] creating file : \", outputFileName)\n\t\toutputFile, err = os.Create(outputFileName)\n\t\tcheck(err)\n\t}\n\n\tlog.Println(\"[elk] starting HTTP server on address : \", httpAddr)\n\t// Start HTTP server in another thread\n\t//http.Handle(\"/static/\", http.FileServer(http.Dir(\"./static\")))\n\t//go log.Fatal(http.ListenAndServe(httpAddr, accesslog.NewLoggingHandler(handler, logger)))\n\tgo func() {\n\t\tlog.Fatal(http.ListenAndServe(httpAddr, n))\n\t}()\n\tlog.Println(\"[elk] HTTP server started\")\n\n\t// Wait for termination\n\twg.Wait()\n}", "func (c *Client) handleRefreshError() {\n\tif c.state != StateConnected {\n\t\treturn\n\t}\n\tc.refreshTimer = time.AfterFunc(10*time.Second, c.sendRefresh)\n}", "func (kv *ShardKV) tick() {\n\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\n\tconfig := kv.sm.Query(-1)\n\n\tif kv.config.Num == -1 && config.Num == 1 {\n\t\tDPrintf(\"Tick:\", \"Initial reconfiguration\")\n\t\tkv.config = config\n\t\treturn\n\t}\n\n\t//else update database until the latest config\n\tfor i := kv.config.Num + 1; i <= config.Num; i++ {\n\n\t\tcurrentConfig := kv.sm.Query(i)\n\n\t\tnew_datastore := map[string]string{}\n\t\tnew_logs := map[string]string{}\n\n\t\t//for each shard in kv\n\t\tfor shard, old_gid := range kv.config.Shards {\n\t\t\tnew_gid := currentConfig.Shards[shard]\n\t\t\tif old_gid != new_gid && new_gid == kv.gid {\n\t\t\t\tlabel := false\n\t\t\t\t//get data from all the servers of this group\n\t\t\t\tfor _, server := range kv.config.Groups[old_gid] {\n\n\t\t\t\t\targs := &GetDataArgs{\n\t\t\t\t\t\tShard: shard,\n\t\t\t\t\t\tIndex: kv.config.Num,\n\t\t\t\t\t}\n\n\t\t\t\t\treply := &GetDataReply{}\n\n\t\t\t\t\tok := call(server, \"ShardKV.GetShardData\", args, reply)\n\t\t\t\t\tif ok && reply.Err == OK {\n\t\t\t\t\t\tfor k, v := range reply.Datastore {\n\t\t\t\t\t\t\tnew_datastore[k] = v\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor k, v := range reply.Logs {\n\t\t\t\t\t\t\tval, exists := new_logs[k]\n\t\t\t\t\t\t\tif !(exists && val >= v) {\n\t\t\t\t\t\t\t\tnew_logs[k] = v\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlabel = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif label == false && old_gid > 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} //for each shard\n\n\t\treq := Op{\n\t\t\tOp: Reconfigure,\n\t\t\tTimestamp: strconv.FormatInt(time.Now().UnixNano(), 10),\n\t\n\t\t\tIndex: i,\n\t\t\tConfig: currentConfig,\n\t\t\tDatastore: new_datastore,\n\t\t\tLogs : new_logs,\n\t\t}\n\t\tkv.RequestPaxosToUpdateDB(req)\n\t} //outer for\n}", "func (r *ReconcileAerospikeCluster) recoverFailedCreate(aeroCluster *aerospikev1alpha1.AerospikeCluster) error {\n\tlogger := pkglog.New(log.Ctx{\"AerospikeCluster\": utils.ClusterNamespacedName(aeroCluster)})\n\tlogger.Info(\"Forcing a cluster recreate as status is nil. The cluster could be unreachable due to bad configuration.\")\n\n\t// Delete all statefulsets and everything related so that it can be properly created and updated in next run.\n\tstatefulSetList, err := r.getClusterStatefulSets(aeroCluster)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting statefulsets while forcing recreate of the cluster as status is nil: %v\", err)\n\t}\n\n\tlogger.Debug(\"Found statefulset for cluster. Need to delete them\", log.Ctx{\"nSTS\": len(statefulSetList.Items)})\n\tfor _, statefulset := range statefulSetList.Items {\n\t\tif err := r.deleteStatefulSet(aeroCluster, &statefulset); err != nil {\n\t\t\treturn fmt.Errorf(\"Error deleting statefulset while forcing recreate of the cluster as status is nil: %v\", err)\n\t\t}\n\t}\n\n\t// Clear pod status as well in status since we want to be re-initializing or cascade deleting devices if any.\n\t// This is not necessary since scale-up would cleanup danglin pod status. However done here for general\n\t// cleanliness.\n\trackStateList := getNewRackStateList(aeroCluster)\n\tfor _, state := range rackStateList {\n\t\tpods, err := r.getRackPodList(aeroCluster, state.Rack.ID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed recover failed cluster: %v\", err)\n\t\t}\n\n\t\tnewPodNames := []string{}\n\t\tfor i := 0; i < len(pods.Items); i++ {\n\t\t\tnewPodNames = append(newPodNames, pods.Items[i].Name)\n\t\t}\n\n\t\terr = r.cleanupPods(aeroCluster, newPodNames, state)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed recover failed cluster: %v\", err)\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Forcing recreate of the cluster as status is nil\")\n}", "func handlerCluster(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Received one request for clustering\")\n\tw.Header().Set(\"Access­Control­Allow­Origin\", \"*\")\n\tw.Header().Set(\"Content­Type\", \"application/json\")\n\tw.Header().Set(\"Access­Control­Allow­Headers\", \"Content­Type,Authorization\")\n\n\tif r.Method != \"GET\" {\n\t\treturn\n\t}\n\n\tterm := r.URL.Query().Get(\"term\")\n\n\t// Create a client\n\tclient, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))\n\tif err != nil {\n\t\thttp.Error(w, \"ES is not setup\", http.StatusInternalServerError)\n\t\tfmt.Printf(\"ES is not setup %v\\n\", err)\n\t\treturn\n\t}\n\t// Range query.\n\t// For details, https://www.elastic.co/guide/en/elasticsearch/reference/current/query­dsl­range­query.html\n\tq := elastic.NewRangeQuery(term).Gte(0.9)\n\n\tsearchResult, err := client.Search().\n\t\tIndex(INDEX).\n\t\tQuery(q).\n\t\tPretty(true).\n\t\tDo()\n\tif err != nil {\n\t\t// Handle error\n\t\tm := fmt.Sprintf(\"Failed to query ES %v\", err)\n\t\tfmt.Println(m)\n\t\thttp.Error(w, m, http.StatusInternalServerError)\n\t}\n\n\t// searchResult is of type SearchResult and returns hits, suggestions,\n\t// and all kinds of other information from Elasticsearch.\n\tfmt.Printf(\"Query took %d milliseconds\\n\", searchResult.TookInMillis)\n\t// TotalHits is another convenience function that works even when something goes wrong.\n\tfmt.Printf(\"Found a total of %d post\\n\", searchResult.TotalHits())\n\n\t// Each is a convenience function that iterates over hits in a search result.\n\t// It makes sure you don't need to check for nil values in the response.\n\t// However, it ignores errors in serialization.\n\tvar typ Post\n\tvar ps []Post\n\tfor _, item := range searchResult.Each(reflect.TypeOf(typ)) {\n\t\tp := item.(Post)\n\t\tps = append(ps, p)\n\t}\n\tjs, err := json.Marshal(ps)\n\tif err != nil {\n\t\tm := fmt.Sprintf(\"Failed to parse post object %v\", err)\n\t\tfmt.Println(m)\n\t\thttp.Error(w, m, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(js)\n}", "func NewClient(url string, maxRetries int, esIndexPerfix, esType string, timeout time.Duration, awsService bool) *Client {\n\tctx := context.Background()\n\tvar client *elastic.Client\n\tvar err error\n\tif awsService {\n\t\tsigningTransport := awsSigningTransport{\n\t\t\tCredentials: awsauth.Credentials{\n\t\t\t\tAccessKeyID: os.Getenv(\"AWS_ACCESS_KEY\"),\n\t\t\t\tSecretAccessKey: os.Getenv(\"AWS_SECRET_KEY\"),\n\t\t\t},\n\t\t\tHTTPClient: http.DefaultClient,\n\t\t}\n\n\t\tsigningClient := &http.Client{\n\t\t\tTransport: http.RoundTripper(signingTransport),\n\t\t}\n\n\t\tclient, err = elastic.NewClient(\n\t\t\telastic.SetURL(url),\n\t\t\telastic.SetScheme(\"https\"),\n\t\t\telastic.SetHttpClient(signingClient),\n\t\t\telastic.SetSniff(false),\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tclient, err = elastic.NewClient(\n\t\t\telastic.SetURL(url),\n\t\t\telastic.SetSniff(false),\n\t\t\telastic.SetMaxRetries(maxRetries),\n\t\t\t// TODO: add basic auth support.\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\t// Use the IndexExists service to check if a specified index exists.\n\tesIndex := generateEsIndex(esIndexPerfix)\n\n\texists, err := client.IndexExists(esIndex).Do(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"index %v is not found in Elastic.\", esIndex)\n\t}\n\n\t// Create an index if it is not exist.\n\tif !exists {\n\t\t// Create a new index.\n\t\tcreateIndex, err := client.CreateIndex(esIndex).Do(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to create index %v, err: %v\", esIndex, err)\n\t\t}\n\t\tif !createIndex.Acknowledged {\n\t\t\t// Not acknowledged\n\t\t\tlog.Fatalf(\"elasticsearch no acknowledged.\")\n\t\t}\n\t}\n\n\treturn &Client{\n\t\tclient: client,\n\t\tesIndex: esIndex,\n\t\tesType: esType,\n\t\ttimeout: timeout,\n\t\tignoredSamples: prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"prometheus_elasticsearch_ignored_samples_total\",\n\t\t\t\tHelp: \"The total number of samples not sent to Elasticsearch due to unsupported float values (Inf, -Inf, NaN).\",\n\t\t\t},\n\t\t),\n\t}\n}", "func ESClient() *elastic.Client {\n\tif client == nil {\n\t\tif config.Config.ElasticSearch.Enabled {\n\t\t\t// setting up execution context\n\t\t\tctx = context.Background()\n\n\t\t\t// setup ElasticSearch client\n\t\t\tclient = createESClient()\n\t\t} else {\n\t\t\tconfig.Config.Logger.Fatal().\n\t\t\t\tStr(\"component\", \"elasticsearch\").\n\t\t\t\tMsg(\"FATAL: trying to call elasticsearch when not enabled.\")\n\t\t}\n\t}\n\n\treturn client\n}", "func ResetBoltDBIndexClientWithShipper() {\n\tif boltDBIndexClientWithShipper == nil {\n\t\treturn\n\t}\n\tboltDBIndexClientWithShipper.Stop()\n\tboltDBIndexClientWithShipper = nil\n}", "func checkOldStateOfGluster() error {\n\n\tvar glusterUUID string\n\tvar partofExistingGluster string\n\n\tpeers, err := client.PeerStatus()\n\tif err != nil {\n\t\trwolog.Error(\"Error Getting Gluster Peer Status\")\n\t\treturn err\n\t}\n\tfor _, peer := range peers {\n\t\tif strings.Contains(peer.Name, \"localhost\") {\n\t\t\tglusterUUID = peer.ID\n\t\t}\n\t}\n\n\tvar retryCount int\n\n\taliveMembers := helpers.CountAliveMembers()\n\tif aliveMembers == 1 {\n\t\terr = purgeOldStateOfGluster()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvols, _ := client.ListVolumes()\n\t\t// Check if there is any IP Change in the gluster.\n\t\tvar ipChanged bool\n\t\tipChanged = true\n\n\t\tfor _, vol := range vols {\n\n\t\t\t// Iterate over bricks and remove bricks but one\n\t\t\tfor _, brick := range vol.Bricks {\n\t\t\t\t// since peers are disconnected, we delete bricks individually\n\t\t\t\tourIP, err := helpers.GetIPAddr()\n\t\t\t\tif err != nil {\n\t\t\t\t\trwolog.Error(\"Failed to get network IP:\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif strings.Contains(brick, ourIP) {\n\t\t\t\t\tipChanged = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// incase ip has been changed then we need to remove the volumes and create the volumes.\n\t\tif ipChanged == true {\n\t\t\trwolog.Debug(\"Ip has been changed, Deleting the volumes.\")\n\t\t\terr = deleteGlusterVolumes()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\n\t\tfor {\n\t\t\tcheckForPoolList, _ := helpers.SerfQuery(\"gluster\", \"pool list\")\n\t\t\tpartofExistingGluster = strings.TrimSuffix(string(checkForPoolList), \"\\n\")\n\t\t\tif len(partofExistingGluster) == 0 && retryCount < 5 {\n\t\t\t\trwolog.Debug(\"Gluster pool list response is empty from the server. Retrying\")\n\t\t\t\ttime.Sleep(15 * time.Second)\n\t\t\t\tretryCount++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif len(partofExistingGluster) > 0 {\n\t\t\tif strings.Contains(string(partofExistingGluster), glusterUUID) {\n\t\t\t\terr = helpers.SetGlusterTag(glusterUUID)\n\t\t\t\tif err != nil {\n\t\t\t\t\trwolog.Error(\"Error while setting up serf tag for gluster \")\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = purgeOldStateOfGluster()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = deleteGlusterVolumes()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (r *KubeCover) tryUpdateConnection(cx *gin.Context) error {\n\t// step: dial the kubernetes endpoint\n\ttlsConn, err := tryDialEndpoint(r.upstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tlsConn.Close()\n\n\t// step: we need to hijack the underlining client connection\n\tclientConn, _, err := cx.Writer.(http.Hijacker).Hijack()\n\tif err != nil {\n\n\t}\n\tdefer clientConn.Close()\n\n\t// step: write the request to upstream\n\tif err = cx.Request.Write(tlsConn); err != nil {\n\t\treturn err\n\t}\n\n\t// step: copy the date between client and upstream endpoint\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo transferBytes(tlsConn, clientConn, &wg)\n\tgo transferBytes(clientConn, tlsConn, &wg)\n\twg.Wait()\n\n\tglog.V(10).Infof(\"closing the http stream from upstream and client\")\n\n\treturn nil\n}", "func recoverCluster(c client.Client, clusterName string, originalAPIEndpoint string) error {\n\terr := wait.Poll(pollInterval, pollTimeout, func() (done bool, err error) {\n\t\tclusterObj := &clusterv1alpha1.Cluster{}\n\t\tif err := c.Get(context.TODO(), client.ObjectKey{Name: clusterName}, clusterObj); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tclusterObj.Spec.APIEndpoint = originalAPIEndpoint\n\t\tif err := c.Update(context.TODO(), clusterObj); err != nil {\n\t\t\tif errors.IsConflict(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tfmt.Printf(\"recovered API endpoint is %s\\n\", clusterObj.Spec.APIEndpoint)\n\t\treturn true, nil\n\t})\n\treturn err\n}", "func TestIngesterRestart(t *testing.T) {\n\tconfig := defaultIngesterTestConfig(t)\n\tconfig.LifecyclerConfig.UnregisterOnShutdown = false\n\n\t{\n\t\tingester, err := prepareIngesterWithBlocksStorage(t, config, prometheus.NewRegistry())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, services.StartAndAwaitRunning(context.Background(), ingester))\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t// Doesn't actually unregister due to UnregisterFromRing: false.\n\t\trequire.NoError(t, services.StopAndAwaitTerminated(context.Background(), ingester))\n\t}\n\n\ttest.Poll(t, 100*time.Millisecond, 1, func() interface{} {\n\t\treturn numTokens(config.LifecyclerConfig.RingConfig.KVStore.Mock, \"localhost\", RingKey)\n\t})\n\n\t{\n\t\tingester, err := prepareIngesterWithBlocksStorage(t, config, prometheus.NewRegistry())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, services.StartAndAwaitRunning(context.Background(), ingester))\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t// Doesn't actually unregister due to UnregisterFromRing: false.\n\t\trequire.NoError(t, services.StopAndAwaitTerminated(context.Background(), ingester))\n\t}\n\n\ttime.Sleep(200 * time.Millisecond)\n\n\ttest.Poll(t, 100*time.Millisecond, 1, func() interface{} {\n\t\treturn numTokens(config.LifecyclerConfig.RingConfig.KVStore.Mock, \"localhost\", RingKey)\n\t})\n}", "func (c *Connection) markAsHealthy() {\n\tc.IsDead = false\n\tc.DeadSince = time.Time{}\n\tc.Failures = 0\n}", "func SavingIndex(addr string, iName string, size int, t int, o string) {\n\tlog.SetOutput(os.Stdout)\n\n\t_, err := os.Stat(o)\n\tif !os.IsNotExist(err) {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The file already exists.\")\n\t\tos.Exit(0)\n\t}\n\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\taddr,\n\t\t},\n\t}\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tcnt := indices.GetDocCount(es, iName)\n\tif cnt != 0 {\n\t\tcnt = cnt/size + 1\n\t} else {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The document does not exist in the target index.\")\n\t\tos.Exit(0)\n\t}\n\n\teg, ctx := errgroup.WithContext(context.Background())\n\n\tchRes := make(chan map[string]interface{}, 10)\n\tchResDone := make(chan struct{})\n\tchDoc := make(chan []map[string]string, 10)\n\n\tvar scrollID string\n\n\tscrollID, err = getScrollID(es, iName, size, t, chRes)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tvar mu1 sync.Mutex\n\n\tfor i := 0; i < cnt; i++ {\n\t\teg.Go(func() error {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\tmu1.Lock()\n\t\t\t\tdefer mu1.Unlock()\n\t\t\t\terr := getScrollRes(es, iName, scrollID, t, chRes, chResDone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t})\n\t}\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-chResDone:\n\t\t\tclose(chRes)\n\t\t\treturn nil\n\t\t}\n\t})\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tdefer close(chDoc)\n\t\t\treturn processing.GetDocsData(chRes, chDoc)\n\t\t}\n\t})\n\n\tvar mu2 sync.Mutex\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tmu2.Lock()\n\t\t\tdefer mu2.Unlock()\n\t\t\treturn saveDocToFile(o, chDoc)\n\t\t}\n\t})\n\n\tif err := eg.Wait(); err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tdeleteScrollID(es, scrollID)\n\n\tlog.Println(\"The index was saved successfully.\")\n}", "func (engine *Engine) initIndexer(options *types.EngineOpts) {\n\t// 初始化索引器\n\tengine.indexers = make([]*core.Indexer, options.NumShards)\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tindexer, _ := core.NewIndexer(*options.IndexerOpts)\n\t\tengine.indexers[shard] = indexer\n\t}\n\n\t// 初始所有管道\n\tengine.indexerAddDocChans = make([]chan indexerAddDocReq, options.NumShards)\n\tengine.indexerLookupChans = make([]chan indexerLookupReq, options.NumShards)\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tengine.indexerAddDocChans[shard] = make(chan indexerAddDocReq, options.IndexerBufLen)\n\t\tengine.indexerLookupChans[shard] = make(chan indexerLookupReq, options.IndexerBufLen)\n\t}\n}", "func TestActiveReplicatorReconnectOnStart(t *testing.T) {\n\tbase.RequireNumTestBuckets(t, 2)\n\n\tif testing.Short() {\n\t\tt.Skipf(\"Test skipped in short mode\")\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tusernameOverride string\n\t\tremoteURLHostOverride string\n\t\texpectedErrorContains string\n\t\texpectedErrorIsConnectionRefused bool\n\t}{\n\t\t{\n\t\t\tname: \"wrong user\",\n\t\t\tusernameOverride: \"bob\",\n\t\t\texpectedErrorContains: \"unexpected status code 401 from target database\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid port\", // fails faster than unroutable address (connection refused vs. connect timeout)\n\t\t\tremoteURLHostOverride: \"127.0.0.1:1234\",\n\t\t\texpectedErrorIsConnectionRefused: true,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\n\t\t\tvar abortTimeout = time.Millisecond * 500\n\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\t// A longer timeout is required on Windows as connection refused errors take approx 2 seconds vs. instantaneous on Linux.\n\t\t\t\tabortTimeout = time.Second * 5\n\t\t\t}\n\t\t\t// test cases with and without a timeout. Ensure replicator retry loop is stopped in both cases.\n\t\t\ttimeoutVals := []time.Duration{\n\t\t\t\t0,\n\t\t\t\tabortTimeout,\n\t\t\t}\n\n\t\t\tfor _, timeoutVal := range timeoutVals {\n\t\t\t\tt.Run(test.name+\" with timeout \"+timeoutVal.String(), func(t *testing.T) {\n\n\t\t\t\t\tbase.SetUpTestLogging(t, logger.LevelDebug, logger.KeyAll)\n\n\t\t\t\t\t// Passive\n\t\t\t\t\ttb2 := base.GetTestBucket(t)\n\t\t\t\t\trt2 := NewRestTester(t, &RestTesterConfig{\n\t\t\t\t\t\tTestBucket: tb2,\n\t\t\t\t\t\tDatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{\n\t\t\t\t\t\t\tUsers: map[string]*db.PrincipalConfig{\n\t\t\t\t\t\t\t\t\"alice\": {\n\t\t\t\t\t\t\t\t\tPassword: base.StringPtr(\"pass\"),\n\t\t\t\t\t\t\t\t\tExplicitChannels: utils.SetOf(\"alice\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}},\n\t\t\t\t\t})\n\t\t\t\t\tdefer rt2.Close()\n\n\t\t\t\t\t// Make rt2 listen on an actual HTTP port, so it can receive the blipsync request from rt1\n\t\t\t\t\tsrv := httptest.NewServer(rt2.TestPublicHandler())\n\t\t\t\t\tdefer srv.Close()\n\n\t\t\t\t\t// Build remoteDBURL with basic auth creds\n\t\t\t\t\tremoteDBURL, err := url.Parse(srv.URL + \"/db\")\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\t// Add basic auth creds to target db URL\n\t\t\t\t\tusername := \"alice\"\n\t\t\t\t\tif test.usernameOverride != \"\" {\n\t\t\t\t\t\tusername = test.usernameOverride\n\t\t\t\t\t}\n\t\t\t\t\tremoteDBURL.User = url.UserPassword(username, \"pass\")\n\n\t\t\t\t\tif test.remoteURLHostOverride != \"\" {\n\t\t\t\t\t\tremoteDBURL.Host = test.remoteURLHostOverride\n\t\t\t\t\t}\n\n\t\t\t\t\t// Active\n\t\t\t\t\ttb1 := base.GetTestBucket(t)\n\t\t\t\t\trt1 := NewRestTester(t, &RestTesterConfig{\n\t\t\t\t\t\tTestBucket: tb1,\n\t\t\t\t\t})\n\t\t\t\t\tdefer rt1.Close()\n\n\t\t\t\t\tid, err := base.GenerateRandomID()\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tarConfig := db.ActiveReplicatorConfig{\n\t\t\t\t\t\tID: id,\n\t\t\t\t\t\tDirection: db.ActiveReplicatorTypePush,\n\t\t\t\t\t\tRemoteDBURL: remoteDBURL,\n\t\t\t\t\t\tActiveDB: &db.Database{\n\t\t\t\t\t\t\tDatabaseContext: rt1.GetDatabase(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tContinuous: true,\n\t\t\t\t\t\t// aggressive reconnect intervals for testing purposes\n\t\t\t\t\t\tInitialReconnectInterval: time.Millisecond,\n\t\t\t\t\t\tMaxReconnectInterval: time.Millisecond * 50,\n\t\t\t\t\t\tTotalReconnectTimeout: timeoutVal,\n\t\t\t\t\t\tReplicationStatsMap: base.SyncGatewayStats.NewDBStats(t.Name(), false, false, false).DBReplicatorStats(t.Name()),\n\t\t\t\t\t}\n\n\t\t\t\t\t// Create the first active replicator to pull from seq:0\n\t\t\t\t\tar := db.NewActiveReplicator(&arConfig)\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\tassert.Equal(t, int64(0), ar.Push.GetStats().NumConnectAttempts.Value())\n\n\t\t\t\t\terr = ar.Start()\n\t\t\t\t\tassert.Error(t, err, \"expecting ar.Start() to return error, but it didn't\")\n\n\t\t\t\t\tif test.expectedErrorIsConnectionRefused {\n\t\t\t\t\t\tassert.True(t, base.IsConnectionRefusedError(err))\n\t\t\t\t\t}\n\n\t\t\t\t\tif test.expectedErrorContains != \"\" {\n\t\t\t\t\t\tassert.True(t, strings.Contains(err.Error(), test.expectedErrorContains))\n\t\t\t\t\t}\n\n\t\t\t\t\t// wait for an arbitrary number of reconnect attempts\n\t\t\t\t\twaitAndRequireCondition(t, func() bool {\n\t\t\t\t\t\treturn ar.Push.GetStats().NumConnectAttempts.Value() > 2\n\t\t\t\t\t}, \"Expecting NumConnectAttempts > 2\")\n\n\t\t\t\t\tif timeoutVal > 0 {\n\t\t\t\t\t\ttime.Sleep(timeoutVal + time.Millisecond*250)\n\t\t\t\t\t\t// wait for the retry loop to hit the TotalReconnectTimeout and give up retrying\n\t\t\t\t\t\twaitAndRequireCondition(t, func() bool {\n\t\t\t\t\t\t\treturn ar.Push.GetStats().NumReconnectsAborted.Value() > 0\n\t\t\t\t\t\t}, \"Expecting NumReconnectsAborted > 0\")\n\t\t\t\t\t}\n\n\t\t\t\t\tassert.NoError(t, ar.Stop())\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n}", "func (kv *ShardKV) TryUpdateConfig () {\n\n kv.configMtx.Lock()\n curConfig := kv.config\n kv.configMtx.Unlock()\n\n newConfig := kv.mck.Query(curConfig.Num+1)\n if newConfig.Num == curConfig.Num+1 {\n if _, isLeader := kv.rf.GetState(); isLeader {\n recvFinished := false\n kv.configMtx.Lock()\n recvFinished = kv.shardToRecv.Empty() == true\n kv.configMtx.Unlock()\n\n if recvFinished {\n request := CfgChangeArgs{newConfig}\n kv.rf.Start(Op{Type: ReqCfgChange, ArgsCfgChange: request})\n }\n }\n }\n}", "func (elasticCluster *ElasticCluster) loadConfig() error {\n\t//获取配置文件路径\n\tadapterFilePath, err := path.GetPath(*flagUtil.GetStringFlag(flag.AdapterFilePath))\n\tif err != nil {\n\t\tlog.Logger.Error(\"get adapter file path error\")\n\t\treturn err\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\n\t\tflag.AdapterFilePath: adapterFilePath,\n\t}).Info(\"get adapter file path success\")\n\n\t//加载对应storage的配置文件\n\tif err := yaml.Unmarshal(elasticCluster, adapterFilePath); err != nil {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tflag.AdapterFilePath: adapterFilePath,\n\t\t}).Error(\"load adapter file error\")\n\t\treturn err\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\n\t\tflag.AdapterFilePath: adapterFilePath,\n\t}).Info(\"load adapter file success\")\n\n\t//校验字段\n\t//校验ElasticNode IP/Port\n\tif len(elasticCluster.ElasticNodes) == 0 {\n\t\telasticCluster.ElasticNodes = []*ElasticNode{{IP: \"127.0.0.1\", Port: \"9200\"}}\n\t}\n\tfor _, elasticNode := range elasticCluster.ElasticNodes {\n\t\t//检查ip,port格式\n\t\tif !regexp.MatchIp(elasticNode.IP) {\n\t\t\treturn errors.New(\"ip \" + elasticNode.IP + \" is not match pattern\")\n\t\t} else if !regexp.MatchPort(elasticNode.Port) {\n\t\t\treturn errors.New(\"port\" + elasticNode.Port + \" is not match pattern\")\n\t\t}\n\t\tlog.Logger.Info(elasticNode.IP + \":\" + elasticNode.Port + \" join cluster\")\n\t}\n\t//校验user\n\tif elasticCluster.User == \"\" {\n\t\telasticCluster.User = \"elastic\"\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"user\": elasticCluster.User}).Info()\n\t//校验password\n\tif elasticCluster.Password == \"\" {\n\t\telasticCluster.Password = \"changeme\"\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"password\": elasticCluster.Password}).Info()\n\t//校验index\n\tif elasticCluster.Index == \"\" {\n\t\telasticCluster.Index = \"prometheus\"\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"index\": elasticCluster.Index}).Info()\n\t//校验type\n\tif elasticCluster.TypeAlias == \"\" {\n\t\telasticCluster.TypeAlias = \"metric\"\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"type\": elasticCluster.TypeAlias}).Info()\n\t//校验sniff,初始化默认false\n\tlog.Logger.WithFields(logrus.Fields{\"sniff\": elasticCluster.Sniff}).Info()\n\t//校验healthcheck,初始化默认false\n\tlog.Logger.WithFields(logrus.Fields{\"healthcheck\": elasticCluster.Healthcheck}).Info()\n\t//校验workers\n\tif elasticCluster.Workers == 0 {\n\t\telasticCluster.Workers = 1\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"workers\": strconv.Itoa(elasticCluster.Workers)}).Info()\n\t//校验bulkSize\n\tif elasticCluster.BulkSize == 0 {\n\t\telasticCluster.BulkSize = 1\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"bulkSize\": strconv.Itoa(elasticCluster.BulkSize)}).Info()\n\t//校验querySize\n\tif elasticCluster.QuerySize == 0 {\n\t\telasticCluster.QuerySize = 5000\n\t} else if elasticCluster.QuerySize > 10000 {\n\t\treturn errors.New(adapterFilePath + \":querySize should less than 10000\")\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"querySize\": strconv.Itoa(elasticCluster.QuerySize)}).Info()\n\t//校验mappingPath\n\tif elasticCluster.MappingPath == \"\" {\n\t\telasticCluster.MappingPath = \"mapping.json\"\n\t}\n\tlog.Logger.WithFields(logrus.Fields{\"mappingPath\": elasticCluster.MappingPath}).Info()\n\n\treturn nil\n}", "func (w *MqttWrapper) maintainMqttConnection() {\n\tretries := -1 // First connection is free\n\n\tfor {\n\t\tif !(*w.mqttClient).IsConnected() {\n\t\t\tretries++\n\t\t}\n\t}\n}", "func CreateOrUpdateConfigMaps(dpl *v1alpha1.Elasticsearch) (err error) {\n\tkibanaIndexMode, err := kibanaIndexMode(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataNodeCount := int((getDataCount(dpl)))\n\tmasterNodeCount := int((getMasterCount(dpl)))\n\n\tconfigmap := newConfigMap(\n\t\tdpl.Name,\n\t\tdpl.Namespace,\n\t\tdpl.Labels,\n\t\tkibanaIndexMode,\n\t\tesUnicastHost(dpl.Name, dpl.Namespace),\n\t\trootLogger(),\n\t\tstrconv.Itoa(masterNodeCount/2+1),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(dataNodeCount),\n\t\tstrconv.Itoa(calculateReplicaCount(dpl)),\n\t)\n\n\taddOwnerRefToObject(configmap, getOwnerRef(dpl))\n\n\terr = sdk.Create(configmap)\n\tif err != nil {\n\t\tif !errors.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"Failure constructing Elasticsearch ConfigMap: %v\", err)\n\t\t}\n\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\t// Get existing configMap to check if it is same as what we want\n\t\t\tcurrent := configmap.DeepCopy()\n\t\t\terr = sdk.Get(current)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to get Elasticsearch cluster configMap: %v\", err)\n\t\t\t}\n\n\t\t\tif configMapContentChanged(current, configmap) {\n\t\t\t\t// Cluster settings has changed, make sure it doesnt go unnoticed\n\t\t\t\tif err := updateConditionWithRetry(dpl, v1.ConditionTrue, updateUpdatingSettingsCondition); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t\t\t\tif getErr := sdk.Get(current); getErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Could not get Elasticsearch configmap %v: %v\", configmap.Name, getErr)\n\t\t\t\t\t\treturn getErr\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent.Data = configmap.Data\n\t\t\t\t\tif updateErr := sdk.Update(current); updateErr != nil {\n\t\t\t\t\t\tlogrus.Debugf(\"Failed to update Elasticsearch configmap %v: %v\", configmap.Name, updateErr)\n\t\t\t\t\t\treturn updateErr\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewElasticSearchClient() *elastic.Client {\n\tvar err error\n\tconnected := false\n\tretries := 0\n\n\t// Custom retry strategy for docker-compose initialization\n\tfor connected == false {\n\t\t// Create a new elastic client\n\t\tclient, err = elastic.NewClient(\n\t\t\telastic.SetURL(\"http://elasticsearch:9200\"), elastic.SetSniff(false))\n\t\tif err != nil {\n\t\t\t// log.Fatal(err)\n\t\t\tif retries == 5 {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfmt.Println(\"Elasticsearch isn't ready for connection\", 5-retries, \"less\")\n\t\t\tretries++\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t} else {\n\t\t\tconnected = true\n\t\t}\n\t}\n\n\t// Getting the ES version number is quite common, so there's a shortcut\n\tesversion, err := client.ElasticsearchVersion(\"http://elasticsearch:9200\")\n\tif err != nil {\n\t\t// Handle error\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Elasticsearch version %s\\n\", esversion)\n\n\treturn client\n}", "func (ns *EsIndexer) RestartStream() {\n\tif ns.stream != nil {\n\t\tns.stream.CloseSend()\n\t\tns.stream = nil\n\t}\n\tns.log.Info().Msg(\"Restarting stream in 5 seconds\")\n\ttime.Sleep(5 * time.Second)\n\terr := ns.StartStream()\n\tif err != nil {\n\t\tns.log.Error().Err(err).Msg(\"Failed to restart stream\")\n\t\tns.RestartStream()\n\t}\n}", "func doEsSend(jsonBytes []byte, errorChannel chan<- error) error {\n\t// Send a HTTP POST to collector.atlas-ml.org, with a timeout!\n\tresp, err := http.Post(\"http://collector.atlas-ml.org:9951\", \"application/json\", bytes.NewBuffer(jsonBytes))\n\n\tif err != nil {\n\t\tlog.Errorln(\"Can't get collector.atlas-ml.org:\", err)\n\t\terrorChannel <- err\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tlog.Debugln(\"Returned from collector.atlas-ml.org:\", string(body))\n\terrorChannel <- nil\n\treturn nil\n}", "func (s *Shard) reopen() (err error) {\n\treopening := s.reopening.Load()\n\tif reopening == nil || reopening.(bool) {\n\t\treturn\n\t}\n\n\ts.reopening.Store(true)\n\tdefer s.reopening.Store(false)\n\n\tif err = s.Close(); err != nil {\n\t\treturn\n\t}\n\n\ttimeout := s.opts.Retryer.FirstTimeout()\n\tretries := 0\n\n\tfor {\n\t\tif timeout, err = s.opts.Retryer.NextTimeout(timeout, retries); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\ts.log(LogLevelInfo, \"Reconnect attempt #%d\", retries)\n\n\t\terr = s.Open()\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\ts.log(LogLevelError, \"Error while reconnecting: %v\", err)\n\n\t\ttime.Sleep(timeout)\n\t\tretries++\n\t}\n}", "func TestE2E(t *testing.T) {\n\tvar missingEnvs []string\n\tfor _, env := range []string{kopsEnvVarClusterName} {\n\t\tif _, ok := os.LookupEnv(env); !ok {\n\t\t\tmissingEnvs = append(missingEnvs, env)\n\t\t}\n\t}\n\tif len(missingEnvs) > 0 {\n\t\tt.Fatalf(\"missing required environment variable(s): %s\", missingEnvs)\n\t}\n\n\ts3Cl, err := createS3Client()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create S3 client: %s\", err)\n\t}\n\n\ttests := []struct {\n\t\tdesc string\n\t\tkubeVer string\n\t}{\n\t\t{\n\t\t\tdesc: \"latest release\",\n\t\t\tkubeVer: \"1.12.0\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"previous release\",\n\t\t\tkubeVer: \"1.11.2\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"previous previous release\",\n\t\t\tkubeVer: \"1.10.6\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\ttt := tt\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\tl := log.New(os.Stdout, fmt.Sprintf(\"[%s] \", t.Name()), 0)\n\n\t\t\tcs, cleanup, err := setupCluster(l, s3Cl, t.Name(), tt.kubeVer)\n\t\t\tdefer func() {\n\t\t\t\tl.Println(\"Cleaning up cluster\")\n\t\t\t\tif err := cleanup(); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to clean up after test: %s\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to set up cluster: %s\", err)\n\t\t\t}\n\n\t\t\t// Check that nodes become ready.\n\t\t\tl.Println(\"Polling for node readiness\")\n\t\t\tvar (\n\t\t\t\tgotNodes []corev1.Node\n\t\t\t\tnumReadyNodes int\n\t\t\t)\n\t\t\tstart := time.Now()\n\t\t\tif err := wait.Poll(5*time.Second, 6*time.Minute, func() (bool, error) {\n\t\t\t\tnl, err := cs.CoreV1().Nodes().List(metav1.ListOptions{LabelSelector: \"kubernetes.io/role=node\"})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tgotNodes = nl.Items\n\t\t\t\tnumReadyNodes = 0\n\t\t\tNodes:\n\t\t\t\tfor _, node := range gotNodes {\n\t\t\t\t\t// Make sure the \"uninitialized\" node taint is missing.\n\t\t\t\t\tfor _, taint := range node.Spec.Taints {\n\t\t\t\t\t\tif taint.Key == cloudprovider.TaintExternalCloudProvider {\n\t\t\t\t\t\t\tcontinue Nodes\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Make sure the node is ready and has a DO-specific label\n\t\t\t\t\t// attached.\n\t\t\t\t\tfor _, cond := range node.Status.Conditions {\n\t\t\t\t\t\tif cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\t\t\t\tif _, ok := node.Labels[doLabel]; ok {\n\t\t\t\t\t\t\t\tnumReadyNodes++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tl.Printf(\"Found %d/%d ready node(s)\", numReadyNodes, numWantNodes)\n\t\t\t\treturn numReadyNodes == numWantNodes, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"got %d ready node(s), want %d: %s\\nnnodes: %v\", numReadyNodes, numWantNodes, err, spew.Sdump(gotNodes))\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for nodes to become ready\\n\", time.Since(start))\n\n\t\t\t// Check that load balancer is working.\n\n\t\t\t// Install example pod to load-balance to.\n\t\t\tappName := \"app\"\n\t\t\tpod := corev1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: appName,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": appName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"nginx\",\n\t\t\t\t\t\t\tImage: \"nginx\",\n\t\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tContainerPort: 80,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tif _, err := cs.CoreV1().Pods(corev1.NamespaceDefault).Create(context.Background(), &pod, metav1.CreateOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to create example pod: %s\", err)\n\t\t\t}\n\n\t\t\t// Wait for example pod to become ready.\n\t\t\tl.Println(\"Polling for pod readiness\")\n\t\t\tstart = time.Now()\n\t\t\tvar appPod *corev1.Pod\n\t\t\tif err := wait.Poll(1*time.Second, 1*time.Minute, func() (bool, error) {\n\t\t\t\tpod, err := cs.CoreV1().Pods(corev1.NamespaceDefault).Get(appName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tif kerrors.IsNotFound(err) {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tappPod = pod\n\t\t\t\tfor _, cond := range appPod.Status.Conditions {\n\t\t\t\t\tif cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to observe ready example pod %q in time: %s\\npod: %v\", appName, err, appPod)\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for pod to become ready\\n\", time.Since(start))\n\n\t\t\t// Create service object.\n\t\t\tsvcName := \"svc\"\n\t\t\tsvc := corev1.Service{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: svcName,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\tSelector: map[string]string{\n\t\t\t\t\t\t\"app\": appName,\n\t\t\t\t\t},\n\t\t\t\t\tType: corev1.ServiceTypeLoadBalancer,\n\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tif _, err := cs.CoreV1().Services(corev1.NamespaceDefault).Create(context.Background(), &svc, metav1.CreateOptions{}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to create service: %s\", err)\n\t\t\t}\n\t\t\t// External LBs don't seem to get deleted when the kops cluster is\n\t\t\t// removed, at least not on DO. Hence, we'll do it explicitly.\n\t\t\tvar lbAddr string\n\t\t\tdefer func() {\n\t\t\t\tl.Printf(\"Deleting service %q\\n\", svcName)\n\t\t\t\tif err := cs.CoreV1().Services(corev1.NamespaceDefault).Delete(context.Background(), svcName, &metav1.DeleteOptions{}); err != nil {\n\t\t\t\t\tt.Errorf(\"failed to delete service: %s\", err)\n\t\t\t\t}\n\t\t\t\t// If this is the last test, CCM might not be able to remove\n\t\t\t\t// the LB before the cluster gets deleted, leaving the LB\n\t\t\t\t// dangling. Therefore, we make sure to stick around until it's\n\t\t\t\t// gone for sure, which we presume is the case if requests\n\t\t\t\t// cannot be delivered anymore due to a network error.\n\n\t\t\t\t// We skip this step if the LB address was never populated,\n\t\t\t\t// however, indicating that the test never came that far.\n\t\t\t\tif lbAddr == \"\" {\n\t\t\t\t\tl.Println(\"Load balancer IP address was never assigned -- skipping check for winded down LB\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcl := &http.Client{\n\t\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\t}\n\t\t\t\tu := fmt.Sprintf(\"http://%s:80\", lbAddr)\n\t\t\t\tvar attempts, lastStatusCode int\n\t\t\t\tif err := wait.Poll(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\t\t\t\tl.Printf(\"Sending request through winding down LB to %s\", u)\n\t\t\t\t\tattempts++\n\t\t\t\t\tresp, err := cl.Get(u)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tlastStatusCode = resp.StatusCode\n\t\t\t\t\t\tresp.Body.Close()\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil\n\t\t\t\t}); err != nil {\n\t\t\t\t\tt.Fatalf(\"continued to deliver requests over LB to example application: %s (last status code: %d / attempts: %d)\", err, lastStatusCode, attempts)\n\t\t\t\t}\n\t\t\t\tl.Printf(\"Needed %d attempt(s) to stop delivering sample request\\n\", attempts)\n\t\t\t}()\n\n\t\t\t// Wait for service IP address to be assigned.\n\t\t\tl.Println(\"Polling for service load balancer IP address assignment\")\n\t\t\tstart = time.Now()\n\t\t\tif err := wait.Poll(5*time.Second, 10*time.Minute, func() (bool, error) {\n\t\t\t\tsvc, err := cs.CoreV1().Services(corev1.NamespaceDefault).Get(context.Background(), svcName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tif len(svc.Status.LoadBalancer.Ingress) > 0 {\n\t\t\t\t\tlbAddr = svc.Status.LoadBalancer.Ingress[0].IP\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\n\t\t\t\treturn false, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to observe load balancer IP address assignment: %s\", err)\n\t\t\t}\n\t\t\tl.Printf(\"Took %v for load balancer to get its IP address assigned\\n\", time.Since(start))\n\n\t\t\t// Send request to the pod over the LB.\n\t\t\tcl := &http.Client{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t}\n\t\t\tu := fmt.Sprintf(\"http://%s:80\", lbAddr)\n\n\t\t\tvar attempts, lastStatusCode int\n\t\t\tif err := wait.Poll(1*time.Second, 3*time.Minute, func() (bool, error) {\n\t\t\t\tl.Printf(\"Sending request to %s\", u)\n\t\t\t\tattempts++\n\t\t\t\tresp, err := cl.Get(u)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\tlastStatusCode = resp.StatusCode\n\t\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\n\t\t\t\treturn true, nil\n\t\t\t}); err != nil {\n\t\t\t\tt.Fatalf(\"failed to send request over LB to example application: %s (last status code: %d / attempts: %d)\", err, lastStatusCode, attempts)\n\t\t\t}\n\t\t\tl.Printf(\"Needed %d attempt(s) to successfully deliver sample request\\n\", attempts)\n\t\t})\n\t}\n}", "func (k *k8sService) ElasticCuratorPodCleanup() {\n\n\tticker := time.NewTicker(curatorPodCleanupInterval)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif k.isLeader {\n\t\t\t\tpodList, err := k.client.CoreV1().Pods(defaultNS).List(metav1.ListOptions{LabelSelector: \"job-name\"})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Error getting pod from Kubernetes: %v\", err)\n\t\t\t\t}\n\t\t\t\tfor _, pod := range podList.Items {\n\t\t\t\t\tif strings.HasPrefix(pod.Name, globals.ElasticSearchCurator) && pod.Status.ContainerStatuses[0].State.Terminated != nil {\n\t\t\t\t\t\terr = k.client.CoreV1().Pods(defaultNS).Delete(pod.Name, &metav1.DeleteOptions{})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"Delete of Pod %v Failed %v\", pod.Name, err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Host) reconnectIfNecessary() {\n\tfor reconnectWait := uint32(0); h.Conn == nil; {\n\t\ttime.Sleep(time.Duration(reconnectWait) * time.Millisecond)\n\t\tif reconnectWait < h.MaxReconnectPeriodMs {\n\t\t\treconnectWait = reconnectWait*2 + h.ReconnectPeriodDeltaMs\n\t\t}\n\t\tif reconnectWait >= h.MaxReconnectPeriodMs {\n\t\t\treconnectWait = h.MaxReconnectPeriodMs\n\t\t}\n\n\t\th.Connect()\n\t}\n}", "func CheckReadyRollingUpgrade(url string) healthcheck.Check {\n\tvar nodeName string\n\tvar initialShards []string\n\tdoneOnce := false // disable after first success\n\tlc := lazyClient{\n\t\tURL: url,\n\t}\n\treturn func() error {\n\t\tlogger := zap.L().Named(\"CheckReadyRollingUpgrade\")\n\n\t\tif doneOnce {\n\t\t\tlogger.Debug(\"disabled due to doneOnce = true\")\n\t\t\treturn nil\n\t\t}\n\n\t\tclient, err := lc.Client()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif nodeName == \"\" {\n\t\t\tinfo, err := client.NodesInfo().NodeId(\"_local\").Metric(\"info\").Do(context.Background())\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(\"error getting node info\", zap.Error(err))\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n := len(info.Nodes); n != 1 {\n\t\t\t\tlogger.Panic(\"got incorrect number of nodes when requesting _local node info\", zap.Int(\"num_nodes\", n))\n\t\t\t}\n\t\t\tfor _, node := range info.Nodes {\n\t\t\t\tnodeName = node.Name\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tshards, err := es.NewCatShardsService(client).Do(context.Background())\n\t\tif err != nil {\n\t\t\tlogger.Info(\"error getting cluster shards\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\n\t\tif initialShards == nil {\n\t\t\tinitialShards = make([]string, 0, len(shards))\n\t\t\tfor _, shard := range shards {\n\t\t\t\tinitialShards = append(initialShards, shard.ID)\n\t\t\t}\n\t\t\tsort.Strings(initialShards)\n\t\t}\n\n\t\tfor _, shard := range shards {\n\t\t\tif shard.State == \"INITIALIZING\" {\n\t\t\t\tif i := sort.SearchStrings(initialShards, shard.ID); i < len(initialShards) && initialShards[i] == shard.ID {\n\t\t\t\t\tconst msg = \"shard is INITIALIZING\"\n\t\t\t\t\tlogger.Info(msg, zap.String(\"shard\", shard.ID))\n\t\t\t\t\treturn errors.New(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif shard.State == \"RELOCATING\" {\n\t\t\t\tconst msg = \"shard is RELOCATING\"\n\t\t\t\tlogger.Info(msg, zap.String(\"shard\", shard.ID))\n\t\t\t\treturn errors.New(msg)\n\t\t\t}\n\t\t}\n\n\t\tdoneOnce = true\n\t\treturn nil\n\t}\n}", "func (w *Worker) staleClient(authority string, timeout uint) {\n time.Sleep(int64(timeout) * 1e9)\n w.cl_lk.Lock()\n w.clients[authority].Close()\n w.clients[authority] = nil, false\n w.cl_lk.Unlock()\n}", "func init() {\n\tresetConnection()\n}", "func (r *ProxyHandler) tryUpgrade(w http.ResponseWriter, req, newReq *http.Request, location *url.URL, transport http.RoundTripper, gv schema.GroupVersion) bool {\n\tif !httpstream.IsUpgradeRequest(req) {\n\t\treturn false\n\t}\n\tbackendConn, err := proxyutil.DialURL(location, transport)\n\tif err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\tdefer backendConn.Close()\n\n\t// TODO should we use _ (a bufio.ReadWriter) instead of requestHijackedConn\n\t// when copying between the client and the backend? Docker doesn't when they\n\t// hijack, just for reference...\n\trequestHijackedConn, _, err := w.(http.Hijacker).Hijack()\n\tif err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\tdefer requestHijackedConn.Close()\n\n\tif err = newReq.Write(backendConn); err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\n\tdone := make(chan struct{}, 2)\n\n\tgo func() {\n\t\t_, err := io.Copy(backendConn, requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tglog.Errorf(\"Error proxying data from client to backend: %v\", err)\n\t\t}\n\t\tdone <- struct{}{}\n\t}()\n\n\tgo func() {\n\t\t_, err := io.Copy(requestHijackedConn, backendConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tglog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\tdone <- struct{}{}\n\t}()\n\n\t<-done\n\treturn true\n}", "func checkEnvoyStats(host string, port uint16) error {\n\tstate, ws, err := util.GetReadinessStats(host, port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get readiness stats: %v\", err)\n\t}\n\n\tif state != nil && admin.ServerInfo_State(*state) != admin.ServerInfo_LIVE {\n\t\treturn fmt.Errorf(\"server is not live, current state is: %v\", admin.ServerInfo_State(*state).String())\n\t}\n\n\tif !ws {\n\t\treturn fmt.Errorf(\"workers have not yet started\")\n\t}\n\n\treturn nil\n}", "func (m *SessionManager) RestartAll() (err error) {\n\tm.StopAll()\n\tm.Lock()\n\tm.numShards = int(float64(m.numShards) * 1.5)\n\tif err != nil {\n\t\treturn err\n\t}\n\ti := 0\n\tfor _, v := range m.Sessions {\n\t\tif i != 0 {\n\t\t\t// One identify every 5 seconds\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t}\n\t\tlog.Println(\"Reconnecting\")\n\t\tv.ShardCount = m.numShards\n\t\tv.ShardID = i\n\t\tif e := v.Open(); e != nil {\n\t\t\terr = e\n\t\t\treturn\n\t\t}\n\t\ti++\n\t}\n\t//No rescale\n\tif len(m.Sessions) >= m.numShards {\n\t\tm.Unlock()\n\t\treturn\n\t}\n\t//Do rescale\n\tfor i <= m.numShards {\n\t\tif i != 0 {\n\t\t\t// One identify every 5 seconds\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t}\n\t\tlog.Println(\"Reconnecting\")\n\t\tm.Sessions = append(m.Sessions, &discordgo.Session{})\n\t\terr := m.initSession(i)\n\t\tif err != nil {\n\t\t\tm.Unlock()\n\t\t\treturn errors.WithMessage(err, \"rescaling\")\n\t\t}\n\t\ti++\n\t}\n\n\tm.Unlock()\n\treturn\n}", "func (etcd *EtcdSource) refresh(node Node) error {\n\tvar opts = client.SetOptions{\n\t\tTTL: etcd.options.TTL,\n\t\tRefresh: true,\n\t}\n\n\tif etcd.options.mockRefreshDelay > 0 {\n\t\ttime.Sleep(time.Duration(rand.Float64() * float64(etcd.options.mockRefreshDelay)))\n\t}\n\n\tif _, err := etcd.keysAPI.Set(context.Background(), etcd.path(node.Path), \"\", &opts); err != nil {\n\t\treturn fixupClusterError(err)\n\t} else {\n\t\treturn nil\n\t}\n}", "func (z *zedrouter) checkConflictingNetworkInstances() {\n\tfor _, item := range z.pubNetworkInstanceStatus.GetAll() {\n\t\tniStatus := item.(types.NetworkInstanceStatus)\n\t\tif !niStatus.NIConflict {\n\t\t\tcontinue\n\t\t}\n\t\tniConfig := z.lookupNetworkInstanceConfig(niStatus.Key())\n\t\tif niConfig == nil {\n\t\t\tcontinue\n\t\t}\n\t\tniConflict, err := z.doNetworkInstanceSanityCheck(niConfig)\n\t\tif err == nil && niConflict == false {\n\t\t\t// Try to re-create the network instance now that the conflict is gone.\n\t\t\tz.log.Noticef(\"Recreating NI %s (%s) now that inter-NI conflict \"+\n\t\t\t\t\"is not present anymore\", niConfig.UUID, niConfig.DisplayName)\n\t\t\t// First release whatever has been already allocated for this NI.\n\t\t\tz.delNetworkInstance(&niStatus)\n\t\t\tz.handleNetworkInstanceCreate(nil, niConfig.Key(), *niConfig)\n\t\t}\n\t}\n}", "func New() (*esearch, error) {\n\n\te := &esearch{\n\t\tlogger: zap.S().With(\"package\", \"blockstore.esearch\"),\n\t\tctx: context.Background(),\n\n\t\tthrottleSearches: make(chan struct{}, config.GetInt(\"elasticsearch.throttle_searches\")),\n\n\t\tindexBlockById: true,\n\t\tindexTxById: true,\n\n\t\tindex: config.GetString(\"elasticsearch.index\"),\n\t\tcountMax: config.GetInt(\"elasticsearch.count_max\"),\n\t}\n\n\tif config.GetString(\"elasticsearch.host\") != \"\" && config.GetString(\"elasticsearch.port\") != \"\" {\n\t\te.url = fmt.Sprintf(\"http://%s:%s\", config.GetString(\"elasticsearch.host\"), config.GetString(\"elasticsearch.port\"))\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Unable to determine address of Elasticsearch\")\n\t}\n\n\t// Setup Elastic Options\n\tesOptions := []elastic.ClientOptionFunc{\n\t\telastic.SetErrorLog(&errorLogger{logger: e.logger}),\n\t\telastic.SetURL(e.url),\n\t\telastic.SetHttpClient(&http.Client{Timeout: config.GetDuration(\"elasticsearch.request_timeout\")}),\n\t}\n\tif config.GetDuration(\"elasticsearch.healthcheck_timeout\") != 0 {\n\t\tesOptions = append(esOptions,\n\t\t\telastic.SetHealthcheck(true),\n\t\t\telastic.SetHealthcheckTimeout(config.GetDuration(\"elasticsearch.healthcheck_timeout\")),\n\t\t)\n\t} else {\n\t\tesOptions = append(esOptions, elastic.SetHealthcheck(false))\n\t}\n\tif config.GetBool(\"elasticsearch.request_log\") {\n\t\tesOptions = append(esOptions, elastic.SetInfoLog(&infoLogger{logger: e.logger}))\n\t}\n\tif config.GetBool(\"elasticsearch.debug\") {\n\t\tesOptions = append(esOptions, elastic.SetTraceLog(&traceLogger{logger: e.logger}))\n\t}\n\tif config.GetBool(\"elasticsearch.sniff\") {\n\t\tesOptions = append(esOptions,\n\t\t\telastic.SetSniff(true),\n\t\t\telastic.SetSnifferCallback(func(node *elastic.NodesInfoNode) bool {\n\t\t\t\te.logger.Debugw(\"Elastic Sniffer\", \"node_name\", node.Name, \"node_ip\", node.IP, \"node_roles\", node.Roles)\n\t\t\t\t// If this node has only one role (master) don't use it for requests\n\t\t\t\tif len(node.Roles) == 1 && node.Roles[0] == \"master\" {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}),\n\t\t)\n\t} else {\n\t\tesOptions = append(esOptions, elastic.SetSniff(false))\n\t}\n\n\tvar err error\n\n\tfor retries := config.GetInt(\"elasticsearch.retries\"); retries > 0 && !conf.Stop.Bool(); retries-- {\n\t\te.client, err = elastic.NewClient(esOptions...)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\t\te.logger.Warnw(\"Connection to elasticsearch timed out. Sleeping and retry.\",\n\t\t\t\t\t\"host\", config.GetString(\"elasticsearch.host\"),\n\t\t\t\t\t\"port\", config.GetString(\"elasticsearch.port\"),\n\t\t\t\t)\n\t\t\t\ttime.Sleep(config.GetDuration(\"elasticsearch.sleep_between_retries\"))\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Could not connect to elasticsearch: %s\", err)\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\t// Aborted before connected\n\tif conf.Stop.Bool() {\n\t\treturn nil, fmt.Errorf(\"Connection to elasticsearch aborted\")\n\t}\n\n\t// Unable to connect to elastic\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to connect to elasticsearch: %v\", err)\n\t}\n\n\t// Ping the server to see what version we are running\n\tpingResult, status, err := e.client.Ping(e.url).Do(context.Background())\n\tif err != nil || status != 200 {\n\t\treturn nil, fmt.Errorf(\"Could not ping Elasticsearch: status:%d error:%v\", status, err)\n\t}\n\t// Get the version number\n\tif !versionRegexp.MatchString(pingResult.Version.Number) {\n\t\treturn nil, fmt.Errorf(\"Unsupported Elasticsearch version %s. Supported: 6.x\", pingResult.Version.Number)\n\t}\n\n\t// Remove indexes if we are set to wipe...\n\tif config.GetBool(\"elasticsearch.wipe_confirm\") {\n\t\te.logger.Warnw(\"We are about to wipe existing indexes. You have 4 seconds to press Ctrl-C\",\n\t\t\t\"index\", e.index+\"-*\",\n\t\t)\n\t\ttime.Sleep(4 * time.Second)\n\n\t\t// If the stop flag hasn't been set, we're ready to go\n\t\tif conf.Stop.Bool() {\n\t\t\treturn nil, fmt.Errorf(\"Wipe aborted.\")\n\t\t}\n\n\t\t// Handle the wipe\n\t\terr = e.wipe()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Could not wipe: %v\", err)\n\t\t}\n\n\t}\n\n\t// Setup the templates\n\tfor _, t := range []string{IndexTypeBlock, IndexTypeTx} {\n\t\terr = e.ApplyIndexTemplate(t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Could not ApplyIndexTemplate %s: %v\", t, err)\n\t\t}\n\t}\n\n\t// Start up the bulk processor - defaults to 5MB and flush interval\n\te.bulk, err = e.client.BulkProcessor().\n\t\tName(\"bulk\").\n\t\tBulkActions(-1).\n\t\tFlushInterval(config.GetDuration(\"elasticsearch.bulk_flush_interval\")).\n\t\tWorkers(config.GetInt(\"elasticsearch.bulk_workers\")).\n\t\tStats(config.GetBool(\"elasticsearch.bulk_stats\")).\n\t\tAfter(e.bulkAfter).\n\t\tDo(e.ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not start BulkProcessor: %s\", err)\n\t}\n\n\t// Did we enable stats\n\tif config.GetBool(\"elasticsearch.bulk_stats\") {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\ttime.Sleep(config.GetDuration(\"elasticsearch.bulk_stats_interval\"))\n\t\t\t\tstats := e.bulk.Stats()\n\t\t\t\te.logger.Infow(\"Bulk Stats\",\n\t\t\t\t\t\"flushed\", stats.Flushed,\n\t\t\t\t\t\"committed\", stats.Committed,\n\t\t\t\t\t\"indexed\", stats.Indexed,\n\t\t\t\t\t\"created\", stats.Created,\n\t\t\t\t\t\"updated\", stats.Updated,\n\t\t\t\t\t\"deleted\", stats.Deleted,\n\t\t\t\t\t\"succeeded\", stats.Succeeded,\n\t\t\t\t\t\"failed\", stats.Failed,\n\t\t\t\t)\n\t\t\t\tfor x, worker := range stats.Workers {\n\t\t\t\t\te.logger.Infow(\"Bulk Worker Stats\", \"worker\", x, \"queued\", worker.Queued, \"duration\", worker.LastDuration)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn e, nil\n}", "func (e *storageExecutor) checkShards() error {\n\tnumOfShards := len(e.shards)\n\tif numOfShards == 0 {\n\t\treturn errShardNotFound\n\t}\n\tnumOfShardIDs := len(e.ctx.shardIDs)\n\tif numOfShards != numOfShardIDs {\n\t\treturn errShardNumNotMatch\n\t}\n\treturn nil\n}", "func (h *HTTPApi) ensureShardInstance(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tdefer r.Body.Close()\n\tbytes, _ := ioutil.ReadAll(r.Body)\n\n\tvar shardInstance metadata.ShardInstance\n\tif err := json.Unmarshal(bytes, &shardInstance); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t} else {\n\t\tmeta := h.storageNode.Datasources[ps.ByName(\"datasource\")].GetMeta()\n\t\tif db, ok := meta.Databases[ps.ByName(\"dbname\")]; ok {\n\t\t\tif err := h.storageNode.Datasources[ps.ByName(\"datasource\")].EnsureExistsShardInstance(r.Context(), db, &shardInstance); err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tw.Write([]byte(err.Error()))\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// DB requested doesn't exist\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t}\n}", "func (q *quitTest) restartNode(ctx context.Context, nodeID int) {\n\tq.c.Start(ctx, q.t, q.args, q.c.Node(nodeID))\n\n\tq.t.l.Printf(\"waiting for readiness of node %d\\n\", nodeID)\n\t// Now perform a SQL query. This achieves two goals:\n\t// - it waits until the server is ready.\n\t// - the particular query forces a cluster-wide RPC; which\n\t// forces any circuit breaker to trip and re-establish\n\t// the RPC connection if needed.\n\tdb := q.c.Conn(ctx, nodeID)\n\tdefer db.Close()\n\tif _, err := db.ExecContext(ctx, `TABLE crdb_internal.cluster_sessions`); err != nil {\n\t\tq.Fatal(err)\n\t}\n}", "func (s *Server) Reload() { s.loadHosts() }", "func StartServer(gid int64, shardmasters []string,\n servers []string, me int) *ShardKV {\n gob.Register(Op{})\n gob.Register(ServerState{})\n\n kv := new(ShardKV)\n kv.me = me\n kv.gid = gid\n kv.sm = shardmaster.MakeClerk(shardmasters)\n\n // Your initialization code here.\n // Don't call Join().\n kv.localLog = make(map[int]Op)\n kv.Counter = 1\n kv.horizon = 0\n kv.configNum = -1\n kv.max = 0\n // setup cell storage\n id := int(rand.Int31n(1000000)) // TODO: change to be recoverable?\n kv.storage = MakeStorage(id, 1000000000, \"127.0.0.1:27017\")\n kv.storage.Clear()\n\n\n kv.current = ServerState{make(map[int]map[string]string), make(map[string]ClientReply)}\n kv.results = make(map[string]ClientReply)\n kv.configs = make(map[int]shardmaster.Config)\n kv.configs[-1] = shardmaster.Config{}\n\n rpcs := rpc.NewServer()\n rpcs.Register(kv)\n\n kv.px = paxos.Make(servers, me, rpcs)\n kv.uid = strconv.FormatInt(nrand(), 10)\n\n // Logging\n kv.logFilename = fmt.Sprintf(\"logs/paxos_log_%d_%d.log\", kv.me, kv.gid)\n var err error\n kv.logFile, err = os.OpenFile(kv.logFilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n if err != nil {\n log.Fatal(err)\n }\n kv.enc = gob.NewEncoder(kv.logFile)\n\n// go kv.logBackground()\n\n os.Remove(servers[me])\n l, e := net.Listen(Network, servers[me]);\n if e != nil {\n log.Fatal(\"listen error: \", e);\n }\n kv.l = l\n\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n go func() {\n for kv.dead == false {\n conn, err := kv.l.Accept()\n if err == nil && kv.dead == false {\n if kv.unreliable && (rand.Int63() % 1000) < 100 {\n // discard the request.\n conn.Close()\n } else if kv.unreliable && (rand.Int63() % 1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n DPrintf(\"shutdown: %v\\n\", err)\n }\n go rpcs.ServeConn(conn)\n } else {\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && kv.dead == false {\n DPrintf(\"ShardKV(%v) accept: %v\\n\", me, err.Error())\n kv.Kill()\n }\n }\n }()\n\n go func() {\n for kv.dead == false {\n kv.tick()\n time.Sleep(250 * time.Millisecond)\n }\n }()\n\n return kv\n}", "func (c *QueueController) checkAndUpdateServiceHealth(exitCode errors.ExitCode) {\n\tvar svcStatusErr error\n\tmarkUnhealthy := false\n\tif c.isCriticalError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"critical error (%d) occurred. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif c.isPersistentError(exitCode) {\n\t\tsvcStatusErr = fmt.Errorf(\"errors (%d) occurred multiple times in a row. Marking worker unhealthy\", exitCode)\n\t\tmarkUnhealthy = true\n\t}\n\tif markUnhealthy {\n\t\tsvcStatus := c.statusManager.svcStatus\n\t\tsvcStatus.IsHealthy = false\n\t\tsvcStatus.Error = svcStatusErr\n\t\tc.statusManager.UpdateService(svcStatus)\n\t\tc.inv.stat.Gauge(stats.WorkerUnhealthy).Update(1)\n\t}\n}", "func (kss *keyspaceState) onHealthCheck(th *TabletHealth) {\n\t// we only care about health events on the primary\n\tif th.Target.TabletType != topodatapb.TabletType_PRIMARY {\n\t\treturn\n\t}\n\n\tkss.mu.Lock()\n\tdefer kss.mu.Unlock()\n\n\tsstate := kss.shards[th.Target.Shard]\n\n\t// if we've never seen this shard before, we need to allocate a shardState for it, unless\n\t// we've received a _not serving_ shard event for a shard which we don't know about yet,\n\t// in which case we don't need to keep track of it. we'll start tracking it if/when the\n\t// shard becomes healthy again\n\tif sstate == nil {\n\t\tif !th.Serving {\n\t\t\treturn\n\t\t}\n\n\t\tsstate = &shardState{target: th.Target}\n\t\tkss.shards[th.Target.Shard] = sstate\n\t}\n\n\t// if the shard went from serving to not serving, or the other way around, the keyspace\n\t// is undergoing an availability event\n\tif sstate.serving != th.Serving {\n\t\tsstate.serving = th.Serving\n\t\tkss.consistent = false\n\t}\n\n\t// if the primary for this shard has been externally reparented, we're undergoing a failover,\n\t// which is considered an availability event. update this shard to point it to the new tablet\n\t// that acts as primary now\n\tif th.PrimaryTermStartTime != 0 && th.PrimaryTermStartTime > sstate.externallyReparented {\n\t\tsstate.externallyReparented = th.PrimaryTermStartTime\n\t\tsstate.currentPrimary = th.Tablet.Alias\n\t\tkss.consistent = false\n\t}\n\n\tkss.ensureConsistentLocked()\n}", "func (i *Instance) initConnSafe() (conn redis.Conn) {\n\tconn = i.pool.Get()\n\tif err := conn.Err(); err != nil {\n\t\tlog.WithFields(logrus.Fields{\"key\": i.Key, \"url\": i.URL, \"err\": err}).Error(\"Initializing Redis Connection Failed.\")\n\t\ti.ConnActive = false\n\t\treturn\n\t}\n\ti.ConnActive = true\n\treturn conn\n}", "func (s *instanceSettings) Dispose() {\n\ts.client.Close()\n}", "func (s *instanceSettings) Dispose() {\n\ts.client.Close()\n}", "func (elasticCluster *ElasticCluster) createType() error {\n\n\tmappingPath, err := path.GetPath(elasticCluster.MappingPath)\n\tif err != nil {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Error(\"get mapping path error\")\n\t\treturn err\n\t}\n\t//加载mapping file\n\tvar mapping map[string]interface{}\n\tif err := jsonUtil.Unmarshal(&mapping, mappingPath); err != nil {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Error(\"unmarshal mapping file error\")\n\t\treturn err\n\t}\n\n\t//client赋值\n\tclient := elasticCluster.Client\n\n\t//检测index是否存在\n\tindexExist, err := client.IndexExists().Index([]string{elasticCluster.Index}).Do(context.Background())\n\tif err != nil {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Error(\"check index exist error\")\n\t\treturn err\n\t}\n\n\tif !indexExist {\n\t\t//index不存在创建index\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Warn(\"index not exist,create...\")\n\t\tresult, err := client.CreateIndex(elasticCluster.Index).Do(context.Background())\n\t\tif err != nil {\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\tIndex: elasticCluster.Index,\n\t\t\t}).Error(\"create index error\")\n\t\t\treturn err\n\t\t}\n\t\tif result.Acknowledged && result.ShardsAcknowledged {\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\tIndex: elasticCluster.Index,\n\t\t\t}).Info(\"create index success\")\n\t\t} else {\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\tIndex: elasticCluster.Index,\n\t\t\t}).Error(\"create index error\")\n\t\t\treturn errors.New(\"Acknowledged or ShardsAcknowledged is false when create index\")\n\t\t}\n\t} else {\n\t\t//index存在,打印日志\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Info(\"index already exist\")\n\t}\n\t//创建type\n\tresult, err := client.PutMapping().Index(elasticCluster.Index).Type(elasticCluster.TypeAlias).\n\t\tBodyJson(mapping).Do(context.Background())\n\tif err != nil {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Error(\"put mapping error\")\n\t\treturn err\n\t}\n\tif result.Acknowledged {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Info(\"put mapping success\")\n\t} else {\n\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\tIndex: elasticCluster.Index,\n\t\t}).Error(\"put mapping error\")\n\t\treturn errors.New(\"Acknowledged is false when put mapping\")\n\t}\n\n\treturn nil\n}", "func (mc *mgmtClient) recover(ctx context.Context) error {\n\tmc.clientMu.Lock()\n\tdefer mc.clientMu.Unlock()\n\n\tctx, span := mc.startSpanFromContext(ctx, string(tracing.SpanNameRecover))\n\tdefer span.End()\n\n\tif mc.rpcLink != nil {\n\t\tif err := mc.rpcLink.Close(ctx); err != nil {\n\t\t\ttab.For(ctx).Debug(fmt.Sprintf(\"Error while closing old link in recovery: %s\", err.Error()))\n\t\t}\n\t\tmc.rpcLink = nil\n\t}\n\n\tif _, err := mc.getLinkWithoutLock(ctx); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sm *ShardMaster) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&sm.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&sm.unreliable, 0)\n\t}\n}", "func (sm *ShardMaster) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&sm.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&sm.unreliable, 0)\n\t}\n}", "func (sm *ShardMaster) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&sm.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&sm.unreliable, 0)\n\t}\n}", "func (sm *ShardMaster) setunreliable(what bool) {\n\tif what {\n\t\tatomic.StoreInt32(&sm.unreliable, 1)\n\t} else {\n\t\tatomic.StoreInt32(&sm.unreliable, 0)\n\t}\n}", "func (a *adapter) checkKvStoreReadiness(ctx context.Context) {\n\t// dividing the live probe interval by 2 to get updated status every 30s\n\ttimeout := a.config.LiveProbeInterval / 2\n\tkvStoreChannel := make(chan bool, 1)\n\n\t// Default true - we are here only after we already had a KV store connection\n\tkvStoreChannel <- true\n\tfor {\n\t\ttimeoutTimer := time.NewTimer(timeout)\n\t\tselect {\n\t\tcase liveliness := <-kvStoreChannel:\n\t\t\tif !liveliness {\n\t\t\t\t// kv-store not reachable or down, updating the status to not ready state\n\t\t\t\tprobe.UpdateStatusFromContext(ctx, kvService, probe.ServiceStatusNotReady)\n\t\t\t\ttimeout = a.config.NotLiveProbeInterval\n\t\t\t} else {\n\t\t\t\t// kv-store is reachable , updating the status to running state\n\t\t\t\tprobe.UpdateStatusFromContext(ctx, kvService, probe.ServiceStatusRunning)\n\t\t\t\ttimeout = a.config.LiveProbeInterval / 2\n\t\t\t}\n\t\t\t// Check if the timer has expired or not\n\t\t\tif !timeoutTimer.Stop() {\n\t\t\t\t<-timeoutTimer.C\n\t\t\t}\n\t\tcase <-timeoutTimer.C:\n\t\t\t// Check the status of the kv-store\n\t\t\tlogger.Info(ctx, \"kv-store liveliness-recheck\")\n\t\t\tif a.kvClient.IsConnectionUp(ctx) {\n\t\t\t\tkvStoreChannel <- true\n\t\t\t} else {\n\t\t\t\tkvStoreChannel <- false\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *Engine) becomeMaster() {\n\te.syncClient.disable()\n\te.notifier.SetSource(config.SourceServer)\n\n\tif err := e.lbInterface.Up(); err != nil {\n\t\tlog.Fatalf(\"Failed to bring LB interface up: %v\", err)\n\t}\n}", "func (p *Pool) checkStableConn(cn *ClientConn) bool {\n\tnow := time.Now()\n\n\tif p.opt.IdleTimeout > 0 && now.Sub(cn.timeUsed) >= p.opt.IdleTimeout {\n\t\t_ = p.CloseClient(cn)\n\t\treturn false\n\t}\n\n\tif p.opt.MaxConnLifeTime > 0 && now.Sub(cn.timeInitiated) >= p.opt.MaxConnLifeTime {\n\t\t_ = p.CloseClient(cn)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *Client) startHeartbeat() {\n\tif log.V(2) {\n\t\tlog.Infof(\"client %s starting heartbeat\", c.Addr())\n\t}\n\t// On heartbeat failure, remove this client from cache. A new\n\t// client to this address will be created on the next call to\n\t// NewClient().\n\tfor {\n\t\ttime.Sleep(heartbeatInterval)\n\t\tif err := c.heartbeat(); err != nil {\n\t\t\tlog.Infof(\"client %s heartbeat failed: %v; recycling...\", c.Addr(), err)\n\t\t\tc.Close()\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (mdb MongoDBConnection) startCleansing() {\n\tlog.Println(\"Looking for old Documents to Cleanse...\")\n\tmdb.session = mdb.GetSession()\n\tdefer mdb.session.Close()\n\tdb := mdb.session.DB(\"dockmaster\").C(\"containers\")\n\tagents := []Agent{}\n\titer := db.Find(nil).Iter()\n\titer.All(&agents)\n\tnow := time.Now()\n\t//time.Now stays in CET even after time.Now().UTC(). Which means this is needed to force it to UTC.\n\tdate := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), now.Nanosecond(), time.UTC)\n\tfor _, a := range agents {\n\t\tcompareNow := a.CreatedAt.Add(time.Second * time.Duration(a.ExpireAfterSeconds)).UTC()\n\t\tif compareNow.Unix() < date.Unix() {\n\t\t\tlog.Println(\"Cleansing Old Document:\", a)\n\t\t\tdb.Remove(bson.M{\"agentid\": a.AgentID})\n\t\t}\n\t}\n}" ]
[ "0.5503901", "0.54657996", "0.5461893", "0.5347205", "0.533372", "0.53300923", "0.53172255", "0.52724683", "0.5252208", "0.5247467", "0.5227067", "0.522519", "0.52239615", "0.52063066", "0.51999575", "0.51520795", "0.5131202", "0.50661063", "0.50554746", "0.5055353", "0.5036482", "0.50302786", "0.5011965", "0.5009494", "0.5005774", "0.4960603", "0.49515644", "0.4926851", "0.49079007", "0.48985127", "0.4874014", "0.48735896", "0.48700884", "0.48549473", "0.4848375", "0.4836926", "0.4817367", "0.47960573", "0.47903806", "0.47837794", "0.47429246", "0.47361714", "0.47252283", "0.47212383", "0.4720888", "0.47171006", "0.47086617", "0.47034568", "0.47029552", "0.46940205", "0.46923688", "0.46823794", "0.46789375", "0.46767256", "0.4666813", "0.46357378", "0.46343392", "0.46340108", "0.46293765", "0.4624313", "0.46067423", "0.46016338", "0.46002704", "0.45955533", "0.45868146", "0.4580721", "0.4580561", "0.45785287", "0.45768252", "0.45751193", "0.4574243", "0.45705217", "0.4568451", "0.45663399", "0.45597142", "0.45568335", "0.45490345", "0.45460635", "0.45420748", "0.4537464", "0.45343727", "0.45322853", "0.45307323", "0.45264322", "0.4522304", "0.4520025", "0.4519185", "0.45149598", "0.45149598", "0.45106822", "0.4508981", "0.450836", "0.450836", "0.450836", "0.450836", "0.4504725", "0.45029795", "0.45014146", "0.4499361", "0.44988066" ]
0.5889378
0
newStatusService creates a new StatusService.
func newStatusService(log zerolog.Logger) *statusService { return &statusService{ log: log, outputActuals: make(chan api.Output, 8), sensorActuals: make(chan api.Sensor, 8), switchActuals: make(chan api.Switch, 8), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewServiceStatus() *ServiceStatus {\n\tthis := ServiceStatus{}\n\treturn &this\n}", "func newService(namespace, name string) *v1.Service {\n\treturn &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labelMap(),\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: labelMap(),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{Name: \"port-1338\", Port: 1338, Protocol: \"TCP\", TargetPort: intstr.FromInt(1338)},\n\t\t\t\t{Name: \"port-1337\", Port: 1337, Protocol: \"TCP\", TargetPort: intstr.FromInt(1337)},\n\t\t\t},\n\t\t},\n\t}\n\n}", "func NewStatus(s int, m string) StatusObject {\n\treturn StatusObject{Status: s, Message: m}\n}", "func newStatus(v *version.V) (s *status, err error) {\n\tsocket := os.Getenv(\"NOTIFY_SOCKET\")\n\tif len(socket) == 0 {\n\t\t// If the notify socket is unset or empty, then return a nil\n\t\t// status where state changes do nothing.\n\t\treturn nil, nil\n\t}\n\n\t// Precompute the version JSON.\n\tjsonver, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, PrecomputeVersionJSONError{Err: err}\n\t}\n\n\treturn &status{\n\t\tsocket: socket,\n\t\tmsg: message{Version: (*json.RawMessage)(&jsonver)},\n\t}, nil\n}", "func newService(repo Repository) Service {\n\n\tif repo == nil {\n\t\treturn nil\n\t}\n\treturn &service{repo}\n}", "func newService(serviceName string) *Service {\n\treturn &Service{\n\t\tpluginDir: serverless.PluginDir,\n\t\tname: serviceName,\n\t\tinterf: nil,\n\t}\n}", "func newService(cr *argoprojv1a1.ArgoCD) *corev1.Service {\n\treturn &corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func newService() *service {\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\treturn &service{\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func newService(m *influxdatav1alpha1.Influxdb) *corev1.Service {\n\tls := labelsForInfluxdb(m.Name)\n\n\treturn &corev1.Service{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"Service\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: m.Name + \"-svc\",\n\t\t\tNamespace: m.Namespace,\n\t\t\tLabels: ls,\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: ls,\n\t\t\tType: \"ClusterIP\",\n\t\t\tPorts: newServicePorts(m),\n\t\t},\n\t}\n}", "func newService(c *onet.Context) (onet.Service, error) {\n\ts := &ServiceState{\n\t\tServiceProcessor: onet.NewServiceProcessor(c),\n\t}\n\thelloMsg := network.RegisterMessage(HelloMsg{})\n\tstopMsg := network.RegisterMessage(StopProtocol{})\n\tconnMsg := network.RegisterMessage(ConnectionRequest{})\n\tdisconnectMsg := network.RegisterMessage(DisconnectionRequest{})\n\n\tc.RegisterProcessorFunc(helloMsg, s.HandleHelloMsg)\n\tc.RegisterProcessorFunc(stopMsg, s.HandleStop)\n\tc.RegisterProcessorFunc(connMsg, s.HandleConnection)\n\tc.RegisterProcessorFunc(disconnectMsg, s.HandleDisconnection)\n\n\tif err := s.tryLoad(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn s, nil\n}", "func NewStatusWebService(\n\tbootstrapCSSPath, bootstrapCSSHash string,\n\tregistry *ServingRangeRegistry) *StatusWebService {\n\treturn &StatusWebService{\n\t\tregistry: registry,\n\t\tbootstrapCSSPath: bootstrapCSSPath,\n\t\tbootstrapCSSHash: bootstrapCSSHash,\n\t}\n}", "func (r *ReconcileNameService) newService(nameService *rocketmqv1beta1.NameService) *corev1.Service {\n\treturn &corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: nameService.Name,\n\t\t\tNamespace: nameService.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tName: nameService.GetName(),\n\t\t\t\t\tKind: nameService.Kind,\n\t\t\t\t\tAPIVersion: nameService.APIVersion,\n\t\t\t\t\tUID: nameService.GetUID(),\n\t\t\t\t\tController: &(share.BoolTrue),\n\t\t\t\t\tBlockOwnerDeletion: &(share.BoolTrue),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tClusterIP: \"None\",\n\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName: \"cluster\",\n\t\t\t\t\tPort: cons.NameServiceMainContainerPort,\n\t\t\t\t\tTargetPort: intstr.FromInt(cons.NameServiceMainContainerPort),\n\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t},\n\t\t\t},\n\t\t\tSelector: map[string]string{\n\t\t\t\t\"app\": nameService.Name,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewService(r Repository, l listing.Service, v validating.Service, mineRate int64) Service {\n\treturn &service{r, l, v, mineRate}\n}", "func NewStatus(name, description string) *Status {\n\treturn &Status{name: name, description: description}\n}", "func NewService() *Service {\n\treturn &Service{grpc_health.NewServer()} // nolint: govet\n}", "func NewStatus(l *log.Logger, client *client.Client, db *db.Database) *Status {\n\treturn &Status{l, client, db}\n}", "func NewService(serviceName string) *ServiceObject {\n\tserviceObject := ServiceObject{}\n\tserviceObject.serviceName = serviceName\n\tserviceObject.serviceStatusHandle = 0\n\tserviceObject.serviceExit = make(chan bool)\n\treturn &serviceObject\n}", "func NewService() Service {\n\treturn Service{}\n}", "func NewService(repository todo.Repository) Service {\n\treturn &service{repository}\n}", "func NewStatus() *Status {\n\tthis := Status{}\n\treturn &this\n}", "func newService(kogitoApp *v1alpha1.KogitoApp, deploymentConfig *appsv1.DeploymentConfig) (service *corev1.Service) {\n\tif deploymentConfig == nil {\n\t\t// we can't create a service without a DC\n\t\treturn nil\n\t}\n\n\tports := buildServicePorts(deploymentConfig)\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tservice = &corev1.Service{\n\t\tObjectMeta: *deploymentConfig.ObjectMeta.DeepCopy(),\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: deploymentConfig.Spec.Selector,\n\t\t\tType: corev1.ServiceTypeClusterIP,\n\t\t\tPorts: ports,\n\t\t},\n\t}\n\n\tmeta.SetGroupVersionKind(&service.TypeMeta, meta.KindService)\n\taddDefaultMeta(&service.ObjectMeta, kogitoApp)\n\taddServiceLabels(&service.ObjectMeta, kogitoApp)\n\timportPrometheusAnnotations(deploymentConfig, service)\n\tservice.ResourceVersion = \"\"\n\treturn service\n}", "func new(c int, msg string) *Status {\n\treturn &Status{s: &spb.Status{Code: int32(c), Message: msg, Details: make([]*anypb.Any, 0)}}\n}", "func newStatus(source *goharborv1.HarborCluster) *status {\n\t// New with default status and conditions\n\ts := &status{\n\t\tcr: source,\n\t\tlocker: &sync.Mutex{},\n\t\tdata: &goharborv1.HarborClusterStatus{\n\t\t\tStatus: goharborv1.StatusProvisioning,\n\t\t\tRevision: time.Now().UnixNano(),\n\t\t\tConditions: make([]goharborv1.HarborClusterCondition, 0),\n\t\t},\n\t\tcollection: lcm.NewCRStatusCollection(),\n\t}\n\n\tif source != nil {\n\t\ts.data.Operator = source.Status.Operator\n\t}\n\n\t// Copy source status if it has been set before\n\tif source != nil && len(source.Status.Status) > 0 {\n\t\ts.data.Status = source.Status.Status\n\t\ts.data.Revision = source.Status.Revision\n\t\ts.data.Conditions = append(s.data.Conditions, source.Status.Conditions...)\n\t\ts.sourceRevision = source.Status.Revision // for comparison later\n\t}\n\n\treturn s\n}", "func NewService(config ServiceConfig) Service {\n\treturn Service{}\n}", "func NewService(r Repository) *Service {\n\treturn &Service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(r Repository) Service {\n\treturn &service{r}\n}", "func NewService(repository Repository) Service {\n\treturn &defaultService{repository}\n}", "func NewStatusHandler(services []string) status.StatusHandler {\n\tsvcs := defaultServices\n\tif len(services) > 0 {\n\t\tsvcs = services\n\t}\n\treturn &Status{monitoredServices: svcs}\n}", "func NewService(repository Repository) Service {\n\treturn &service{repository}\n}", "func NewService() Service {\n\treturn dateService{}\n}", "func NewService(r repository, e event) *Service {\n\treturn &Service{r, e}\n}", "func NewStatus(objects int) (Status, error) {\n\tif objects < 1 {\n\t\treturn Status{}, errors.New(\"Can't post less than 1 object\")\n\t}\n\n\tid, err := NewID()\n\tif err != nil {\n\t\treturn Status{}, err\n\t}\n\n\tcount := int64(objects)\n\treturn Status{ID: id, Status: \"pending\", TotalCount: count, PendingCount: count}, err\n}", "func NewService(r repository.Repository) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t}\n}", "func NewService(repo rel.Repository) *Service {\n\treturn &Service{repository: repo}\n}", "func newStatusView(gui *gocui.Gui) (controller *Status) {\n\tcontroller = new(Status)\n\n\t// populate main fields\n\tcontroller.name = \"status\"\n\tcontroller.gui = gui\n\tcontroller.helpKeys = make([]*key.Binding, 0)\n\tcontroller.requestedHeight = 1\n\n\treturn controller\n}", "func NewService() Service {\n\treturn Service{\n\t\trepo: newRepository(),\n\t}\n}", "func NewService(r Repository) *Service {\n\treturn &Service{repository: r}\n}", "func NewService(m map[string]interface{}) Service {\n\treturn m\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService() Service {\n\treturn &service{}\n}", "func NewService(dao impelementsModels) *HealthService {\n\treturn &HealthService{dao}\n}", "func New(code int, msg string) *Status {\n\tif code < 0 {\n\t\tpanic(fmt.Sprintf(\"status code must be greater than zero\"))\n\t}\n\n\testatus := add(code, msg)\n\n\treturn estatus\n}", "func New() *service {\n\treturn &service{}\n}", "func NewService(server string) (Service, error) {\n\tif strings.HasPrefix(server, \"ssh://\") {\n\t\treturn NewSSHService(server)\n\t}\n\n\tif strings.HasPrefix(server, \"mrt://\") {\n\t\treturn NewMarathonService(server)\n\t}\n\n\treturn nil, ErrServiceNotFound\n}", "func NewStatus(armed bool) Status {\n\treturn Status{\n\t\tarmed,\n\t}\n}", "func NewService(addr string) *Service {\n\treturn &Service{\n\t\taddr: addr,\n\t}\n}", "func NewStatus(opts ...Option) *Status {\n\tstatus := &Status{\n\t\tstatus: http.StatusServiceUnavailable,\n\t}\n\tfor _, opt := range opts {\n\t\topt(status)\n\t}\n\treturn status\n}", "func NewService(r Repository) *Service {\n\treturn &Service{repo: r}\n}", "func NewService(config Config) *Service {\n\n\treturn &Service{\n\t\tclient: NewClient(config),\n\t}\n}", "func NewStatus() StatusType {\n\treturn StatusType{Conditions: make([]Condition, 0, 3)}\n}", "func NewStatus(userID int, status, deskripsiStatus, keteranganStatus, lastUpdate string) (*Status, error) {\n\tparsedDate, err := time.Parse(\"2006-01-02 15:04\", lastUpdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstats := &Status{\n\t\tUserID: userID,\n\t\tStatus: status,\n\t\tDeskripsiStatus: deskripsiStatus,\n\t\tKeteranganStatus: keteranganStatus,\n\t\tLastUpdate: parsedDate,\n\t}\n\n\tif err := Dbm.Insert(stats); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn stats, err\n}", "func NewService(r *Repository) Service {\n\treturn &service{repo: r}\n}", "func newService(c *onet.Context) (onet.Service, error) {\n\ts := &Service{\n\t\tServiceProcessor: onet.NewServiceProcessor(c),\n\t}\n\ts.RegisterProcessorFunc(cosiSendRawID, s.HandleRaw)\n\t_, err := c.ProtocolRegister(protoName, s.NewDefaultProtocol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.RegisterHandlers(s.GenesisTx, s.Setup, s.TreesBLSCoSi, s.MemoryAllocated); err != nil {\n\t\treturn nil, errors.New(\"Couldn't register messages\")\n\t}\n\n\ts.propagateF, s.mypi, err = propagate.NewPropagationFunc(c, \"Propagate\", s.propagateHandler, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.trees = make(map[onet.TreeID]*onet.Tree)\n\ts.coinToAtomic = make(map[string]int)\n\ts.atomicCoinReserved = make([]int32, 0)\n\n\tdb, bucketNameTx := s.GetAdditionalBucket([]byte(\"Tx\"))\n\t_, bucketNameLastTx := s.GetAdditionalBucket([]byte(\"LastTx\"))\n\ts.bucketNameTx = bucketNameTx\n\ts.bucketNameLastTx = bucketNameLastTx\n\ts.db = db\n\treturn s, nil\n}", "func NewService(r Repository) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t}\n}", "func NewService(r Repository) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t}\n}", "func NewService(r Repository) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t}\n}", "func NewService(r Repository) *Service {\n\treturn &Service{\n\t\trepo: r,\n\t}\n}", "func (client *Client) ServiceStatus(request *ServiceStatusRequest) (response *ServiceStatusResponse, err error) {\nresponse = CreateServiceStatusResponse()\nerr = client.DoAction(request, response)\nreturn\n}", "func NewService(m Model) Service {\n\treturn &service{m}\n}", "func NewService(r RepositoryAdder) Service {\n\treturn Service{r}\n}", "func (bc *ReconcileJenkinsInstance) newService(instanceName types.NamespacedName) (*corev1.Service, error) {\n\texists := false\n\n\t// get jenkins instance\n\tjenkinsInstance, err := bc.getJenkinsInstance(instanceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the service with the name specified in JenkinsInstance.spec\n\tservice, err := bc.getService(instanceName)\n\t// If the resource doesn't exist, we'll create it\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// If the Service is not controlled by this JenkinsInstance resource, we should log\n\t\t// a warning to the event recorder and ret\n\t\tif !metav1.IsControlledBy(service, jenkinsInstance) {\n\t\t\tmsg := fmt.Sprintf(MessageResourceExists, service.GetName())\n\t\t\tbc.Event(jenkinsInstance, corev1.EventTypeWarning, ErrResourceExists, msg)\n\t\t\treturn service, fmt.Errorf(msg)\n\t\t}\n\n\t\texists = true\n\t}\n\n\tlabels := map[string]string{\n\t\t\"app\": \"jenkinsci\",\n\t\t\"controller\": jenkinsInstance.GetName(),\n\t\t\"component\": string(jenkinsInstance.UID),\n\t}\n\n\tif exists {\n\t\tserviceCopy := service.DeepCopy()\n\t\tserviceCopy.Labels = labels\n\t\tserviceCopy.Spec.Ports = []corev1.ServicePort{\n\t\t\t{\n\t\t\t\tName: \"master\",\n\t\t\t\tProtocol: \"TCP\",\n\t\t\t\tPort: JenkinsMasterPort,\n\t\t\t\tNodePort: util.GetNodePort(service.Spec.Ports, \"master\"),\n\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\tIntVal: JenkinsMasterPort,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"agent\",\n\t\t\t\tProtocol: \"TCP\",\n\t\t\t\tPort: JenkinsAgentPort,\n\t\t\t\tNodePort: util.GetNodePort(service.Spec.Ports, \"agent\"),\n\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\tIntVal: JenkinsAgentPort,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tserviceCopy.Spec.Selector = map[string]string{\n\t\t\t\"component\": string(jenkinsInstance.UID),\n\t\t}\n\n\t\tif jenkinsInstance.Spec.Service != nil {\n\t\t\tserviceCopy.ObjectMeta.Annotations = jenkinsInstance.Spec.Service.Annotations\n\t\t\tif jenkinsInstance.Spec.Service.ServiceType != \"\" {\n\t\t\t\tserviceCopy.Spec.Type = jenkinsInstance.Spec.Service.ServiceType\n\t\t\t}\n\t\t}\n\n\t\tif reflect.DeepEqual(serviceCopy.Spec, service.Spec) {\n\t\t\treturn service, nil\n\t\t}\n\n\t\tglog.Info(\"updating service\")\n\t\terr = bc.Client.Update(context.TODO(), serviceCopy)\n\t\treturn serviceCopy, err\n\t} else {\n\t\tserviceName := jenkinsInstance.GetName()\n\t\tif jenkinsInstance.Spec.Service != nil && jenkinsInstance.Spec.Service.Name != \"\" {\n\t\t\tserviceName = jenkinsInstance.Spec.Service.Name\n\t\t}\n\n\t\tservice = &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: serviceName,\n\t\t\t\tNamespace: jenkinsInstance.GetNamespace(),\n\t\t\t\tLabels: labels,\n\t\t\t},\n\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"master\",\n\t\t\t\t\t\tProtocol: \"TCP\",\n\t\t\t\t\t\tPort: JenkinsMasterPort,\n\t\t\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: JenkinsMasterPort,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tNodePort: jenkinsInstance.Spec.Service.NodePort,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"agent\",\n\t\t\t\t\t\tProtocol: \"TCP\",\n\t\t\t\t\t\tPort: JenkinsAgentPort,\n\t\t\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\tIntVal: JenkinsAgentPort,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSelector: map[string]string{\n\t\t\t\t\t\"component\": string(jenkinsInstance.UID),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tif jenkinsInstance.Spec.Service != nil {\n\t\t\tservice.ObjectMeta.Annotations = jenkinsInstance.Spec.Service.Annotations\n\t\t\tif jenkinsInstance.Spec.Service.ServiceType != \"\" {\n\t\t\t\tservice.Spec.Type = jenkinsInstance.Spec.Service.ServiceType\n\t\t\t}\n\t\t}\n\n\t\terr = controllerutil.SetControllerReference(jenkinsInstance, service, bc.scheme)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = bc.Client.Create(context.TODO(), service)\n\t\treturn service, nil\n\t}\n}", "func NewService() (service.Service, error) {\n\treturn &Service{}, nil\n}", "func (r *ReconcileMongoDB) newService(m *dbaasv1alpha1.MongoDB, serviceName string) *corev1.Service {\n\tvar selector = make(map[string]string)\n\tselector[\"role\"] = \"mongodb\"\n\n\tservice := &corev1.Service{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"Service\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: serviceName,\n\t\t\tNamespace: m.Namespace,\n\t\t\tLabels: map[string]string{\"name\": serviceName},\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName: \"mongodb\",\n\t\t\t\t\tPort: 27017,\n\t\t\t\t\tTargetPort: intstr.FromInt(27107),\n\t\t\t\t},\n\t\t\t},\n\t\t\tClusterIP: \"None\",\n\t\t\tSelector: selector,\n\t\t},\n\t}\n\t// Set MongoDB instance as the owner and controller\n\tcontrollerutil.SetControllerReference(m, service, r.scheme)\n\treturn service\n}", "func NewService(r Repository) Service {\n\treturn &service{\n\t\trepo: r,\n\t}\n}", "func NewService(ctx context.Context) *Service {\n\treturn newService(ctx, repositoryCacheSize, repositoryCacheTTL)\n}", "func NewService(name, url string) Service {\n\treturn Service{\n\t\tName: name,\n\t\tURL: url,\n\t}\n}", "func NewService(repo *Repository) Service {\n\treturn &service{repo: repo}\n}", "func NewService(config Config) *Service {\n\treturn &Service{\n\t\tinstances: new(sync.Map),\n\t\tconfig: config,\n\t}\n}", "func NewService(name string) *Service {\n\treturn &Service{\n\t\tname: name,\n\t}\n}", "func NewService(c *config.Configs, e *config.ErrorMessage, r Repository, l glog.Logger) *Service {\n\treturn &Service{\n\t\tconf: c,\n\t\tem: e,\n\t\trepo: r,\n\t\tlogger: l,\n\t}\n}", "func New(r Repository, v *validator.Validate) *Service {\n\treturn &Service{r, v}\n}", "func NewService(cr cargo.Repository, lr location.Repository, rs routing.Service) Service {\n\treturn &service{\n\t\tcargoRepository: cr,\n\t\tlocationRepository: lr,\n\t\troutingService: rs,\n\t}\n}", "func New(repository repository.Repository) Service {\n\treturn &service{repository: repository}\n}", "func NewService(f func(interface{}) interface{}) *Service {\n\treturn &Service{\n\t\tInProgress: make(map[interface{}]bool),\n\t\tPendingReaders: make(map[interface{}][]chan interface{}),\n\t\tf: f,\n\t}\n}", "func (c PGClient) NewService(name string, binsIB int64, host string, port int, typeService string, runSTR string, projects []string, owner string) (err error) {\n\t_, err = c.DB.Query(\"select new_service_function($1,$2,$3,$4,$5,$6,$7,$8)\", name, binsIB, host, port, typeService, runSTR, pg.Array(projects), owner)\n\treturn err\n}", "func NewService(repository Repository) Service {\n\treturn &service{\n\t\trepository,\n\t\tvalidator.New(),\n\t}\n}", "func NewService(repo interfaces.IRepository) interfaces.IService {\n\treturn &Service{\n\t\trepo: repo,\n\t}\n}", "func NewService(ci CIServer, r Repository) *Service {\n\treturn &Service{ci, r}\n}", "func NewService(repo Repository) Service {\n\treturn &service{\n\t\trepo: repo,\n\t}\n}", "func NewService(repo Repository) Service {\n\treturn &service{\n\t\trepo: repo,\n\t}\n}", "func newJiraService(j *v1alpha1.Jira) error {\n\tsvc := &v1.Service{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Service\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: j.Name,\n\t\t\tNamespace: j.Namespace,\n\t\t\tOwnerReferences: ownerRef(j),\n\t\t\tLabels: jiraLabels(j),\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: jiraLabels(j),\n\t\t\tSessionAffinity: \"ClientIP\",\n\t\t\tType: \"NodePort\",\n\t\t\tPorts: servicePorts(j),\n\t\t},\n\t}\n\treturn createResource(j, svc)\n}", "func NewService(store Store) Service {\n\treturn &service{store: store}\n}", "func New() Service {\n\treturn &service{}\n}", "func New() Service {\n\treturn &service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService() *Service {\n\treturn &Service{}\n}", "func NewService(name string, service *Service) *Service {\n\tservice.Name = name\n\treturn service\n}" ]
[ "0.7384248", "0.68112874", "0.67704743", "0.65930367", "0.65732807", "0.6568152", "0.6567023", "0.65171105", "0.65164363", "0.64773387", "0.64598393", "0.64216363", "0.63724804", "0.6349199", "0.6314851", "0.631383", "0.6263678", "0.62375146", "0.62309384", "0.622677", "0.6180968", "0.61688477", "0.61561495", "0.6148869", "0.6101559", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.6099595", "0.60971135", "0.60865474", "0.6084521", "0.6083242", "0.60729766", "0.6064606", "0.6061894", "0.60617197", "0.60572284", "0.6035394", "0.6016465", "0.6008447", "0.60057503", "0.60057503", "0.60057503", "0.59919655", "0.598328", "0.59817594", "0.59794146", "0.5978565", "0.5977265", "0.5973383", "0.5971913", "0.5970418", "0.59625334", "0.595648", "0.595554", "0.59534717", "0.5943067", "0.5943067", "0.5943067", "0.5943067", "0.5940506", "0.5938823", "0.5935373", "0.59295523", "0.59293777", "0.59276783", "0.5922124", "0.5911898", "0.5908491", "0.59070176", "0.59070146", "0.5906203", "0.5899182", "0.5892007", "0.58918643", "0.58844006", "0.588053", "0.58644694", "0.58635795", "0.5859999", "0.5853313", "0.5852676", "0.5852676", "0.5850797", "0.58483964", "0.5847351", "0.5847351", "0.58454114", "0.58454114", "0.58454114", "0.58454114", "0.58441776" ]
0.80025476
0
Run the service until the given context is canceled
func (s *statusService) Run(ctx context.Context, nwControlClient api.NetworkControlServiceClient) error { log := s.log g, ctx := errgroup.WithContext(ctx) // Send output actuals g.Go(func() error { once := func() error { for { select { case msg := <-s.outputActuals: lctx, cancel := context.WithTimeout(ctx, setActualTimeout) _, err := nwControlClient.SetOutputActual(lctx, &msg) cancel() if err != nil { log.Debug().Err(err).Msg("Send(Output) failed") return err } case <-ctx.Done(): return nil } } } return utils.UntilCanceled(ctx, log, "sendOutputActuals", once) }) // Send sensor actuals g.Go(func() error { once := func() error { for { select { case msg := <-s.sensorActuals: lctx, cancel := context.WithTimeout(ctx, setActualTimeout) _, err := nwControlClient.SetSensorActual(lctx, &msg) cancel() if err != nil { log.Debug().Err(err).Msg("Send(Sensor) failed") return err } case <-ctx.Done(): return nil } } } return utils.UntilCanceled(ctx, log, "sendSensorActuals", once) }) // Send switch actuals g.Go(func() error { once := func() error { for { select { case msg := <-s.switchActuals: lctx, cancel := context.WithTimeout(ctx, setActualTimeout) _, err := nwControlClient.SetSwitchActual(lctx, &msg) cancel() if err != nil { log.Debug().Err(err).Msg("Send(Switch) failed") return err } case <-ctx.Done(): return nil } } } return utils.UntilCanceled(ctx, log, "sendSwitchActuals", once) }) return g.Wait() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func runUnlessCanceled(ctx context.Context, fn func() error) error {\n\tc := make(chan error, 1) // buffered, in case the request is canceled\n\tgo func() {\n\t\tc <- fn()\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-c:\n\t\treturn err\n\t}\n}", "func (w *watcher) waitForCancel() {\n\tselect {\n\tcase <-w.ctx.Done():\n\t\tw.Stop()\n\t}\n}", "func (k *k8sService) runUntilCancel() {\n\twatcher, err := k.strClient.CoreV1().Pods(defaultNS).Watch(metav1.ListOptions{})\n\tii := 0\n\tfor err != nil {\n\t\tselect {\n\t\tcase <-k.ctx.Done():\n\t\t\tk.Done()\n\t\t\tlog.Infof(\"k8sService main loop runUntilCancel canceled\")\n\t\t\treturn\n\t\tcase <-time.After(time.Second):\n\t\t\twatcher, err = k.strClient.CoreV1().Pods(defaultNS).Watch(metav1.ListOptions{})\n\t\t\tii++\n\t\t\tif ii%10 == 0 {\n\t\t\t\tlog.Errorf(\"Waiting for pod watch to succeed for %v seconds, last err: %v\", ii, err)\n\t\t\t}\n\t\t}\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-k.ctx.Done():\n\t\t\tlog.Infof(\"k8sService main loop runUntilCancel canceled\")\n\t\t\twatcher.Stop()\n\t\t\tk.Done()\n\t\t\treturn\n\t\tcase mod := <-k.modCh:\n\t\t\tlog.Infof(\"Deploying mod %v\", mod)\n\t\t\tk.deployModule(&mod)\n\t\tcase event, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\t// restart this routine.\n\t\t\t\tlog.Infof(\"k8sService error receiving on K8s Apiserver watch channel, restarting main loop\")\n\t\t\t\tgo k.runUntilCancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t\te := types.K8sPodEvent{\n\t\t\t\tPod: event.Object.(*v1.Pod),\n\t\t\t}\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added:\n\t\t\t\te.Type = types.K8sPodAdded\n\t\t\tcase watch.Deleted:\n\t\t\t\te.Type = types.K8sPodDeleted\n\t\t\tcase watch.Modified:\n\t\t\t\te.Type = types.K8sPodModified\n\t\t\t}\n\n\t\t\tif err := k.notify(e); err != nil {\n\t\t\t\tlog.Errorf(\"Failed to notify %+v with error: %v\", e, err)\n\t\t\t}\n\t\tcase <-time.After(interval):\n\t\t\tif k.isLeader {\n\t\t\t\tfoundModules, err := getModules(k.client)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"k8sService error getting modules from K8s ApiServer: %v\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmodulesToDeploy := make(map[string]protos.Module)\n\t\t\t\tfor name, module := range k8sModules {\n\t\t\t\t\tif module.Spec.Disabled {\n\t\t\t\t\t\t/*upon CMD restart disabled flag is set to true and pegasus deployment is deleted, allowing it to be redeployed */\n\t\t\t\t\t\tif _, found := foundModules[name]; found {\n\t\t\t\t\t\t\tdelete(foundModules, name)\n\t\t\t\t\t\t\tmodule.Spec.Disabled = false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := foundModules[name]; !ok {\n\t\t\t\t\t\tmodulesToDeploy[name] = module\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete(foundModules, name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tk.deployModules(modulesToDeploy)\n\t\t\t\tk.deleteModules(foundModules)\n\t\t\t}\n\t\t}\n\t}\n}", "func someHandler() {\n\t// Create the ctx\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// Do some stuff\n\tgo doStuff(ctx)\n\n\t// Cancel after 10 seconds\n\ttime.Sleep(10 * time.Second)\n\tcancel()\n\n\t// Waiting for doStuff to finish\n\t<-ch\n}", "func Stream(parent context.Context, out chan<- Value) error {\n cctx, cancel := context.WithCancel(parent) // HL\n\n go func() { // HL\n timer := time.AfterFunc(time.Second * 5, cancel) // HL\n }() // HL\n\n for {\n v, err := DoSomething(ctx)\n if err != nil {\n return err\n }\n select {\n case <- cctx.Done(): // HL\n //check if context is canceled\n return cctx.Err()\n case out <- v:\n }\n }\n}", "func (eth *Backend) run(ctx context.Context) {\n\tdone := ctx.Done()\n\twait := make(chan struct{})\n\t// Shut down the RPC client on ctx.Done().\n\tgo func() {\n\t\t<-done\n\t\teth.cancelRPCs()\n\t\teth.shutdown()\n\t\tclose(wait)\n\t}()\n\n\tblockPoll := time.NewTicker(blockPollInterval)\n\tdefer blockPoll.Stop()\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase <-blockPoll.C:\n\t\t\teth.poll(ctx)\n\t\tcase <-done:\n\t\t\tbreak out\n\t\t}\n\t}\n\t// Wait for the RPC client to shut down.\n\t<-wait\n}", "func (w *WaitTask) Cancel(_ *TaskContext) {\n\tw.cancelFunc()\n}", "func (h *Handler) cancel(c echo.Context) (e error) {\n\tctx := c.(*cuxs.Context)\n\tvar r cancelRequest\n\tvar id int64\n\tvar sr *model.SalesReturn\n\n\tif id, e = common.Decrypt(ctx.Param(\"id\")); e == nil {\n\t\tif sr, e = ShowSalesReturn(\"id\", id); e == nil {\n\t\t\tr.SR = sr\n\t\t\tif e = ctx.Bind(&r); e == nil {\n\t\t\t\tif e = CancelSalesReturn(sr); e == nil {\n\t\t\t\t\tif e = UpdateExpense(sr); e == nil {\n\t\t\t\t\t\tctx.Data(sr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\te = echo.ErrNotFound\n\t\t}\n\t}\n\n\treturn ctx.Serve(e)\n}", "func handlerRequestWithCancelation(w http.ResponseWriter, r *http.Request) {\n\tlongRunningCalculation := func(ctx context.Context) {\n\t\tfor i := 0; ; i++ {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done(): // HL\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tfmt.Printf(\"Worker %d \\n\", i)\n\t\t\t}\n\t\t}\n\t}\n\n\t// the context is canceled when the ServeHTTP method returns // HL\n\tgo longRunningCalculation(r.Context()) // HL\n\n\t// give some time for longRunningCalculation to do some work\n\ttime.Sleep(5 * time.Second)\n\n\tio.WriteString(w, \"bazinga!\")\n\treturn\n}", "func (c *Context) Stop() {\n\tlog.Printf(\"[WARN] terraform: Stop called, initiating interrupt sequence\")\n\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\t// If we're running, then stop\n\tif c.runContextCancel != nil {\n\t\tlog.Printf(\"[WARN] terraform: run context exists, stopping\")\n\n\t\t// Tell the hook we want to stop\n\t\tc.sh.Stop()\n\n\t\t// Stop the context\n\t\tc.runContextCancel()\n\t\tc.runContextCancel = nil\n\t}\n\n\t// Grab the condition var before we exit\n\tif cond := c.runCond; cond != nil {\n\t\tcond.Wait()\n\t}\n\n\tlog.Printf(\"[WARN] terraform: stop complete\")\n}", "func runWithContext(fun func(ctx context.Context) error) (context.CancelFunc, chan error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(done)\n\t\tdone <- fun(ctx)\n\t}()\n\n\treturn cancel, done\n}", "func CanceledContext() context.Context {\n\tdateline := time.Now().Add(time.Duration(1) * time.Millisecond)\n\tctx, cancel := context.WithDeadline(context.Background(), dateline)\n\tdefer cancel()\n\ttime.Sleep(time.Duration(2) * time.Millisecond)\n\treturn ctx\n}", "func cancelled(ctx context.Context) bool {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn true\n\tdefault:\n\t}\n\treturn false\n}", "func TestClient_contextCancellation(t *testing.T) {\n\tdefer leaktest.Check(t)()\n\n\tstarted := make(chan struct{})\n\tstopped := make(chan struct{})\n\tcpipe, spipe := channel.Direct()\n\tsrv := NewServer(hmap{\n\t\t\"Hang\": Handler(func(ctx context.Context, _ *Request) (any, error) {\n\t\t\tclose(started) // signal that the method handler is running\n\t\t\tselect {\n\t\t\tcase <-stopped:\n\t\t\t\tt.Log(\"Server unblocked by client completing\")\n\t\t\t\treturn true, nil\n\t\t\tcase <-time.After(10 * time.Second):\n\t\t\t\tt.Error(\"Server timed out before completion\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}),\n\t}, nil).Start(spipe)\n\tc := NewClient(cpipe, nil)\n\tdefer func() {\n\t\tc.Close()\n\t\tsrv.Wait()\n\t}()\n\n\t// Start a call that will hang around until a timer expires or an explicit\n\t// cancellation is received.\n\tctx, cancel := context.WithCancel(context.Background())\n\treq, err := c.req(ctx, \"Hang\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"c.req(Hang) failed: %v\", err)\n\t}\n\trsps, err := c.send(ctx, jmessages{req})\n\tif err != nil {\n\t\tt.Fatalf(\"c.send(Hang) failed: %v\", err)\n\t}\n\n\t// Wait for the handler to start so that we don't race with calling the\n\t// handler on the server side, then cancel the context client-side.\n\t<-started\n\tcancel()\n\n\t// The call should fail client side, in the usual way for a cancellation.\n\trsp := rsps[0]\n\trsp.wait()\n\tclose(stopped)\n\tif err := rsp.Error(); err != nil {\n\t\tif err.Code != Cancelled {\n\t\t\tt.Errorf(\"Response error for %q: got %v, want %v\", rsp.ID(), err, Cancelled)\n\t\t}\n\t} else {\n\t\tt.Errorf(\"Response for %q: unexpectedly succeeded\", rsp.ID())\n\t}\n}", "func (r *TokenBucketLimiter) Wait(ctx context.Context) (err error) {\n\tok, err := r.Take(ctx)\n\tslog.Debug(\"r.Take\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\treturn nil\n\t}\n\n\tdeadline, ok := ctx.Deadline()\n\tminWaitTime := r.interval\n\tslog.Debug(\"minWaitTime:%v\", minWaitTime)\n\tif ok {\n\t\tif deadline.Before(time.Now().Add(minWaitTime)) {\n\t\t\tslog.Debug(\"can't get token before %v\", deadline)\n\t\t\treturn fmt.Errorf(\"can't get token before %v\", deadline)\n\t\t}\n\t}\n\n\tfor {\n\t\tslog.Debug(\"---for---\")\n\t\ttimer := time.NewTimer(minWaitTime)\n\t\tselect {\n\t\t// 执行的代码\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"context timeout\")\n\t\tcase <-timer.C:\n\t\t\tok, err := r.Take(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func propagateCancellation(\n\tctx context.Context,\n\tallDone chan struct{},\n\tc CancellableRoundTripper,\n\treq *http.Request) {\n\t// If the context is not cancellable, there is nothing interesting we can do.\n\tcancelChan := ctx.Done()\n\tif cancelChan == nil {\n\t\treturn\n\t}\n\n\t// If the user closes allDone before the context is cancelled, we can return\n\t// immediately.\n\tselect {\n\tcase <-allDone:\n\t\treturn\n\n\tcase <-cancelChan:\n\t}\n\n\t// The context has been cancelled. Repeatedly cancel the HTTP request as\n\t// described above until the user closes allDone.\n\tfor {\n\t\tc.CancelRequest(req)\n\n\t\tselect {\n\t\tcase <-allDone:\n\t\t\treturn\n\n\t\tcase <-time.After(10 * time.Millisecond):\n\t\t}\n\t}\n}", "func (i *DeleteOrUpdateInvTask) Cancel(_ *taskrunner.TaskContext) {}", "func (_m *MockCompletableFuture[T]) Cancel() {\n\t_m.Called()\n}", "func cancellation() {\n\tduration := 150 * time.Millisecond\n\tctx, cancel := context.WithTimeout(context.Background(), duration)\n\tdefer cancel()\n\n\tch := make(chan string, 1)\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)\n\t\tch <- \"data\"\n\t}()\n\n\tselect {\n\tcase d := <-ch:\n\t\tfmt.Println(\"work complete\", d)\n\n\tcase <-ctx.Done():\n\t\tfmt.Println(\"work cancelled\")\n\t}\n\n\ttime.Sleep(time.Second)\n\tfmt.Println(\"-------------------------------------------------\")\n}", "func Test_Listen_ContextCanceled(t *testing.T) {\n\tconsumerGroup := &mocks.ConsumerGroup{}\n\n\tconsumerGroup.On(\"Consume\", mock.Anything, mock.Anything, mock.Anything).\n\t\tRun(func(args mock.Arguments) {\n\t\t\tctx := args.Get(0).(context.Context)\n\t\t\t<-ctx.Done()\n\t\t}).\n\t\tReturn(nil)\n\n\ttested := listener{consumerGroup: consumerGroup}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tcancel()\n\n\terr := tested.Listen(ctx)\n\n\tassert.Equal(t, context.Canceled, err)\n\tconsumerGroup.AssertExpectations(t)\n}", "func (h *Handler) handleStop(id string) {\n\th.subCancellations.Cancel(id)\n\th.sendComplete(id)\n}", "func (t *Task) Stopping() <-chan struct{} {\n\treturn t.ctx.Done()\n}", "func cancelCheck(ctx context.Context, pipelineId uuid.UUID, cancelChannel chan bool, cacheService cache.Cache) {\n\tticker := time.NewTicker(500 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\tcase _ = <-ticker.C:\n\t\t\tcancel, err := cacheService.GetValue(ctx, pipelineId, cache.Canceled)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif cancel.(bool) {\n\t\t\t\tcancelChannel <- true\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (h *EventHandler) Stop() {\n\th.ctx.Done()\n}", "func sleepUntilCtxDone(d time.Duration, ctx context.Context) (abort bool) {\n\tif ctx == nil {\n\t\ttime.Sleep(d)\n\t\treturn false\n\t}\n\n\tselect {\n\tcase <-time.After(d):\n\t\treturn false\n\tcase <-ctx.Done():\n\t\treturn true\n\t}\n}", "func (t *task) run(ctx context.Context) {\n\tgo func() {\n\t\tresult, err := t.handler(ctx, t.request)\n\t\tt.resultQ <- Response{Result: result, Err: err} // out channel is buffered by 1\n\t\tt.running = false\n\t\tclose(t.resultQ)\n\t}()\n}", "func (f *failoverStatus) cancel() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.timer != nil {\n\t\tf.timer.Stop()\n\t}\n}", "func contextDone(ctx context.Context, env string) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\terr := ctx.Err()\n\t\tswitch err {\n\t\tcase context.Canceled:\n\t\t\treturn ErrQueryCanceled(env)\n\t\tcase context.DeadlineExceeded:\n\t\t\treturn ErrQueryTimeout(env)\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (g *GRPC) Stop() {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tif g == nil {\n\t\treturn\n\t}\n\n\tfor _, cancel := range g.cancelFuncs {\n\t\tcancel()\n\t}\n\n\tg.serv.GracefulStop()\n\n\tg.lis = nil\n}", "func pollWithContext(ctx context.Context, timeout time.Duration, pollFn func() (success bool, err error)) error {\n\tstart := time.Now()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn context.Canceled\n\t\tcase <-time.After(500 * time.Millisecond):\n\t\t\tsuccess, err := pollFn()\n\t\t\tif err != nil || success {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif time.Since(start) > timeout {\n\t\t\t\treturn ErrTimeout\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *context) Cancel() {\n\tc.cancel()\n}", "func (e *AutoResetEvent) WaitContext(ctx context.Context) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-e.c:\n\t\treturn nil\n\t}\n}", "func (m *Manager) Run() error {\n\tfor range m.ctx.Done() {\n\t\tm.cancelDiscoverers()\n\t\treturn m.ctx.Err()\n\t}\n\treturn nil\n}", "func (k *xyzProvider) Cancel(context.Context, *pbempty.Empty) (*pbempty.Empty, error) {\n\t// TODO\n\treturn &pbempty.Empty{}, nil\n}", "func (a *serverApp) run(ctx context.Context) error {\n\tgo func() { // shutdown on context cancellation\n\t\t<-ctx.Done()\n\t\ta.restSrv.Shutdown()\n\t}()\n\n\ta.restSrv.Run(a.HTTPPort)\n\n\tclose(a.terminated)\n\n\treturn nil\n}", "func main() {\n\tctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10 * time.Second))\n\tdefer cancel()\n\tmsg, err := do(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(msg)\n}", "func (_m *AsyncBR) Cancel() {\n\t_m.Called()\n}", "func WaitFor(ctx context.Context, diff time.Duration) {\n\ttimer := time.NewTimer(diff)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\t\treturn\n\tcase <-ctx.Done():\n\t\treturn\n\t}\n}", "func (s *server) stoppableContext(ctx context.Context) context.Context {\n\ts.stopMu.Lock()\n\tdefer s.stopMu.Unlock()\n\n\tstoppable, cancel := context.WithCancel(ctx)\n\tgo mergeStop(stoppable, cancel, s.stopCh)\n\treturn stoppable\n}", "func (o *Options) run(ctx context.Context, controllerCtx *Context, lock resourcelock.Interface, restConfig *rest.Config, burstRestConfig *rest.Config) {\n\trunContext, runCancel := context.WithCancel(ctx) // so we can cancel internally on errors or TERM\n\tdefer runCancel()\n\tshutdownContext, shutdownCancel := context.WithCancel(context.Background()) // extends beyond ctx\n\tdefer shutdownCancel()\n\tpostMainContext, postMainCancel := context.WithCancel(context.Background()) // extends beyond ctx\n\tdefer postMainCancel()\n\tlaunchedMain := false\n\n\tch := make(chan os.Signal, 1)\n\tdefer func() { signal.Stop(ch) }()\n\tsignal.Notify(ch, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tsig := <-ch\n\t\tklog.Infof(\"Shutting down due to %s\", sig)\n\t\trunCancel()\n\t\tsig = <-ch\n\t\tklog.Fatalf(\"Received shutdown signal twice, exiting: %s\", sig)\n\t}()\n\n\tresultChannel := make(chan asyncResult, 1)\n\tresultChannelCount := 0\n\n\tinformersDone := postMainContext.Done()\n\t// FIXME: would be nice if there was a way to collect these.\n\tcontrollerCtx.CVInformerFactory.Start(informersDone)\n\tcontrollerCtx.OpenshiftConfigInformerFactory.Start(informersDone)\n\tcontrollerCtx.OpenshiftConfigManagedInformerFactory.Start(informersDone)\n\tcontrollerCtx.InformerFactory.Start(informersDone)\n\n\tallSynced := controllerCtx.CVInformerFactory.WaitForCacheSync(informersDone)\n\tfor _, synced := range allSynced {\n\t\tif !synced {\n\t\t\tklog.Fatalf(\"Caches never synchronized: %v\", postMainContext.Err())\n\t\t}\n\t}\n\n\tresultChannelCount++\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tvar firstError error\n\t\tleaderelection.RunOrDie(postMainContext, leaderelection.LeaderElectionConfig{\n\t\t\tLock: lock,\n\t\t\tReleaseOnCancel: true,\n\t\t\tLeaseDuration: o.leaderElection.LeaseDuration.Duration,\n\t\t\tRenewDeadline: o.leaderElection.RenewDeadline.Duration,\n\t\t\tRetryPeriod: o.leaderElection.RetryPeriod.Duration,\n\t\t\tCallbacks: leaderelection.LeaderCallbacks{\n\t\t\t\tOnStartedLeading: func(_ context.Context) { // no need for this passed-through postMainContext, because goroutines we launch inside will use runContext\n\t\t\t\t\tlaunchedMain = true\n\t\t\t\t\tif o.ListenAddr != \"\" {\n\t\t\t\t\t\tresultChannelCount++\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tdefer utilruntime.HandleCrash()\n\t\t\t\t\t\t\terr := cvo.RunMetrics(postMainContext, shutdownContext, o.ListenAddr, o.ServingCertFile, o.ServingKeyFile)\n\t\t\t\t\t\t\tresultChannel <- asyncResult{name: \"metrics server\", error: err}\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t\tif err := controllerCtx.CVO.InitializeFromPayload(runContext, restConfig, burstRestConfig); err != nil {\n\t\t\t\t\t\tif firstError == nil {\n\t\t\t\t\t\t\tfirstError = err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tklog.Infof(\"Failed to initialize from payload; shutting down: %v\", err)\n\t\t\t\t\t\tresultChannel <- asyncResult{name: \"payload initialization\", error: firstError}\n\t\t\t\t\t}\n\n\t\t\t\t\tresultChannelCount++\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tdefer utilruntime.HandleCrash()\n\t\t\t\t\t\terr := controllerCtx.CVO.Run(runContext, shutdownContext)\n\t\t\t\t\t\tresultChannel <- asyncResult{name: \"main operator\", error: err}\n\t\t\t\t\t}()\n\n\t\t\t\t\tresultChannelCount++\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tdefer utilruntime.HandleCrash()\n\t\t\t\t\t\terr := controllerCtx.StopOnFeatureGateChange.Run(runContext, runCancel)\n\t\t\t\t\t\tresultChannel <- asyncResult{name: \"stop-on-techpreview-change controller\", error: err}\n\t\t\t\t\t}()\n\n\t\t\t\t\tif controllerCtx.AutoUpdate != nil {\n\t\t\t\t\t\tresultChannelCount++\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tdefer utilruntime.HandleCrash()\n\t\t\t\t\t\t\terr := controllerCtx.AutoUpdate.Run(runContext, 2)\n\t\t\t\t\t\t\tresultChannel <- asyncResult{name: \"auto-update controller\", error: err}\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tOnStoppedLeading: func() {\n\t\t\t\t\tklog.Info(\"Stopped leading; shutting down.\")\n\t\t\t\t\trunCancel()\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tresultChannel <- asyncResult{name: \"leader controller\", error: firstError}\n\t}()\n\n\tvar shutdownTimer *time.Timer\n\tfor resultChannelCount > 0 {\n\t\tklog.Infof(\"Waiting on %d outstanding goroutines.\", resultChannelCount)\n\t\tif shutdownTimer == nil { // running\n\t\t\tselect {\n\t\t\tcase <-runContext.Done():\n\t\t\t\tklog.Info(\"Run context completed; beginning two-minute graceful shutdown period.\")\n\t\t\t\tshutdownTimer = time.NewTimer(2 * time.Minute)\n\t\t\t\tif !launchedMain { // no need to give post-main extra time if main never ran\n\t\t\t\t\tpostMainCancel()\n\t\t\t\t}\n\t\t\tcase result := <-resultChannel:\n\t\t\t\tresultChannelCount--\n\t\t\t\tif result.error == nil {\n\t\t\t\t\tklog.Infof(\"Collected %s goroutine.\", result.name)\n\t\t\t\t} else {\n\t\t\t\t\tklog.Errorf(\"Collected %s goroutine: %v\", result.name, result.error)\n\t\t\t\t\trunCancel() // this will cause shutdownTimer initialization in the next loop\n\t\t\t\t}\n\t\t\t\tif result.name == \"main operator\" {\n\t\t\t\t\tpostMainCancel()\n\t\t\t\t}\n\t\t\t}\n\t\t} else { // shutting down\n\t\t\tselect {\n\t\t\tcase <-shutdownTimer.C: // never triggers after the channel is stopped, although it would not matter much if it did because subsequent cancel calls do nothing.\n\t\t\t\tpostMainCancel()\n\t\t\t\tshutdownCancel()\n\t\t\t\tshutdownTimer.Stop()\n\t\t\tcase result := <-resultChannel:\n\t\t\t\tresultChannelCount--\n\t\t\t\tif result.error == nil {\n\t\t\t\t\tklog.Infof(\"Collected %s goroutine.\", result.name)\n\t\t\t\t} else {\n\t\t\t\t\tklog.Errorf(\"Collected %s goroutine: %v\", result.name, result.error)\n\t\t\t\t}\n\t\t\t\tif result.name == \"main operator\" {\n\t\t\t\t\tpostMainCancel()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tklog.Info(\"Finished collecting operator goroutines.\")\n}", "func (p *googleCloudProvider) Cancel(context.Context, *empty.Empty) (*empty.Empty, error) {\n\treturn &empty.Empty{}, nil\n}", "func (p *googleCloudProvider) Cancel(context.Context, *empty.Empty) (*empty.Empty, error) {\n\treturn &empty.Empty{}, nil\n}", "func (r Retrier) Do(ctx context.Context, run func() error) error {\n\tcooldown := r.Cooldown()\n\n\tfor {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\t// nolint:wrapcheck // no meaningful information can be added to this error\n\t\t\treturn err\n\t\t}\n\n\t\terr := run()\n\t\tif err != nil {\n\t\t\t// check to see if it's temporary.\n\t\t\tvar tempErr TemporaryError\n\t\t\tif ok := errors.As(err, &tempErr); ok && tempErr.Temporary() {\n\t\t\t\tdelay, err := cooldown() // nolint:govet // the shadow is intentional\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn pkgerrors.Wrap(err, \"sleeping during retry\")\n\t\t\t\t}\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// since it's not temporary, it can't be retried, so...\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (drc *DummyRegistryClient) Cancel() {}", "func (h *Handler) WithContext(ctx context.Context) {\n\tgo func() {\n\t\t<-ctx.Done()\n\t\th.terminating = true\n\t}()\n}", "func (n *notifier) serviceLoop() {\n\tn.lock.Lock()\n\tdefer n.lock.Unlock()\n\tfor {\n\t\tfor n.desired == n.current {\n\t\t\tn.cond.Wait()\n\t\t}\n\t\tif n.current != n.id && n.desired == n.id {\n\t\t\tn.service.Validate(n.desired, n.current)\n\t\t\tn.service.Start()\n\t\t} else if n.current == n.id && n.desired != n.id {\n\t\t\tn.service.Stop()\n\t\t}\n\t\tn.current = n.desired\n\t}\n}", "func (c *Context) Stop() {\n\tc.stopChannel <- struct{}{}\n}", "func (h *ProxyHealth) stop() {\n\tif h.cancel != nil {\n\t\th.cancel <- struct{}{}\n\t\tclose(h.cancel)\n\t\th.cancel = nil\n\t}\n}", "func (s *ServerStatistics) cancel() {\n\ts.blacklisted.Store(false)\n\ts.backoffUntil.Store(time.Time{})\n\tselect {\n\tcase s.interrupt <- struct{}{}:\n\tdefault:\n\t}\n}", "func runInterruptedJob(c *C, d *ddl, job *model.Job, doneCh chan error) {\n\tctx := mock.NewContext()\n\tctx.Store = d.store\n\n\tvar (\n\t\thistory *model.Job\n\t\terr error\n\t)\n\n\terr = d.doDDLJob(ctx, job)\n\tif errors.Is(err, context.Canceled) {\n\t\tendlessLoopTime := time.Now().Add(time.Minute)\n\t\tfor history == nil {\n\t\t\t// imitate doDDLJob's logic, quit only find history\n\t\t\thistory, _ = d.getHistoryDDLJob(job.ID)\n\t\t\tif history != nil {\n\t\t\t\terr = history.Error\n\t\t\t}\n\t\t\ttime.Sleep(10 * testLease)\n\t\t\tif time.Now().After(endlessLoopTime) {\n\t\t\t\terr = errors.New(\"runInterruptedJob may enter endless loop\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tdoneCh <- err\n}", "func (g *Group) execute(\n\tfn func(context.Context) error,\n) {\n\tdefer g.wg.Done()\n\n\terr := fn(g.ctx)\n\tif err == nil {\n\t\treturn\n\t}\n\n\tg.errM.Lock()\n\tdefer g.errM.Unlock()\n\n\tif g.err == nil || err != context.Canceled {\n\t\tg.err = multierr.Append(g.err, err)\n\t}\n\n\tg.cancel()\n}", "func (c *ConsumerManager) Stop(ctx context.Context) (err error) {\n\terrC := make(chan error)\n\n\tgo func() {\n\t\terrC <- c.stop()\n\t}()\n\n\tselect {\n\tcase err = <-errC:\n\tcase <-ctx.Done():\n\t\terr = ErrStopDeadlineExceeded\n\t}\n\n\treturn\n}", "func DoWithContext(ctx context.Context, do func(ctx context.Context) error, fallback func(err error)) (err error) {\n\terrorChannel := make(chan error)\n\tvar contextHasBeenDone = false\n\tgo func() {\n\t\terr := do(ctx)\n\t\tif contextHasBeenDone {\n\t\t\tif fallback != nil {\n\t\t\t\tfallback(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terrorChannel <- err\n\t}()\n\tselect {\n\tcase err = <-errorChannel:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\tcontextHasBeenDone = true\n\t\treturn ctx.Err()\n\t}\n}", "func (ctx *RenderContext) Cancel() {\n\tif ctx == nil {\n\t\treturn\n\t}\n\tctx.ShaExistCache = map[string]bool{}\n\tif ctx.cancelFn == nil {\n\t\treturn\n\t}\n\tctx.cancelFn()\n}", "func (s *service) Close() (err error) {\n\ts.ctxCancel()\n\treturn nil\n}", "func (sb *shardBuffer) wait(ctx context.Context, e *entry) (RetryDoneFunc, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\tsb.remove(e)\n\t\treturn nil, vterrors.Errorf(vterrors.Code(contextCanceledError), \"%v: %v\", contextCanceledError, ctx.Err())\n\tcase <-e.done:\n\t\treturn e.bufferCancel, e.err\n\t}\n}", "func (service *Service) Stop(context moleculer.BrokerContext) {\n\tif service.stopped != nil {\n\t\tgo service.stopped(context, (*service.schema))\n\t}\n}", "func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan struct{}) {\n\tstop := make(chan struct{})\n\twait := make(chan struct{})\n\n\t// get the runContext cancellation channel now, because releaseRun will\n\t// write to the runContext field.\n\tdone := c.runContext.Done()\n\n\tgo func() {\n\t\tdefer close(wait)\n\t\t// Wait for a stop or completion\n\t\tselect {\n\t\tcase <-done:\n\t\t\t// done means the context was canceled, so we need to try and stop\n\t\t\t// providers.\n\t\tcase <-stop:\n\t\t\t// our own stop channel was closed.\n\t\t\treturn\n\t\t}\n\n\t\t// If we're here, we're stopped, trigger the call.\n\n\t\t{\n\t\t\t// Copy the providers so that a misbehaved blocking Stop doesn't\n\t\t\t// completely hang Terraform.\n\t\t\twalker.providerLock.Lock()\n\t\t\tps := make([]ResourceProvider, 0, len(walker.providerCache))\n\t\t\tfor _, p := range walker.providerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.providerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\t// Call stop on all the provisioners\n\t\t\twalker.provisionerLock.Lock()\n\t\t\tps := make([]ResourceProvisioner, 0, len(walker.provisionerCache))\n\t\t\tfor _, p := range walker.provisionerCache {\n\t\t\t\tps = append(ps, p)\n\t\t\t}\n\t\t\tdefer walker.provisionerLock.Unlock()\n\n\t\t\tfor _, p := range ps {\n\t\t\t\t// We ignore the error for now since there isn't any reasonable\n\t\t\t\t// action to take if there is an error here, since the stop is still\n\t\t\t\t// advisory: Terraform will exit once the graph node completes.\n\t\t\t\tp.Stop()\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn stop, wait\n}", "func Run(fn func() error) {\n\tif err := fn(); err != nil && err != context.Canceled {\n\t\tfmt.Fprintf(os.Stderr, \"%+v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (w *FuncWaiter) Cancel() error {\n\tw.cancel <- struct{}{}\n\treturn nil\n}", "func (cx *Context) do(callback func(*C.JSAPIContext)) {\n\tif !cx.Valid {\n\t\tpanic(\"attempt to use a destroyed context\")\n\t}\n\tif cx.ptr != nil && C.JSAPI_ThreadCanAccessContext(cx.ptr) == C.JSAPI_OK {\n\t\tcallback(cx.ptr)\n\t\treturn\n\t}\n\tfn := &cxfn{\n\t\tcall: callback,\n\t\tdone: make(chan bool, 1),\n\t}\n\tcx.in <- fn\n\t<-fn.done\n}", "func (svc *Service) throw(event int, ctx interface{}) {\n\tfor _, l := range svc.list {\n\t\tl(event, ctx)\n\t}\n\n\tif event == roadrunner.EventServerFailure {\n\t\t// underlying rr grpc is dead\n\t\tsvc.Stop()\n\t}\n}", "func WaitForWithContext(\n\tctx context.Context,\n\tminTimeout, maxTimeout, defaultTimeout time.Duration,\n\tperiod time.Duration,\n\tf func() (bool, error),\n) error {\n\tvar timeout time.Duration\n\n\t// Check if the caller provided a deadline\n\td, ok := ctx.Deadline()\n\tif !ok {\n\t\ttimeout = defaultTimeout\n\t} else {\n\t\ttimeout = d.Sub(time.Now())\n\n\t\t// Determine if it is too short or too long\n\t\tif timeout < minTimeout || timeout > maxTimeout {\n\t\t\treturn status.Errorf(codes.InvalidArgument,\n\t\t\t\t\"Deadline must be between %v and %v; was: %v\", minTimeout, maxTimeout, timeout)\n\t\t}\n\t}\n\n\treturn WaitFor(timeout, period, f)\n}", "func (c *MockedHTTPContext) Cancel(err error) {\n\tif c.MockedCancel != nil {\n\t\tc.MockedCancel(err)\n\t}\n}", "func main() {\n\n\tstart := time.Now()\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(rand.Int63n(7))*time.Second)\n\tdefer func() {\n\t\tlog.Printf(\"ctx cancel: %-10s\", time.Since(start))\n\t\tcancel()\n\t}()\n\n\tRunner(ctx, start)\n}", "func (r *Reader) run() {\n\tdefer r.cancel()\n\tdefer close(r.done)\n\tdefer r.stmt.Close()\n\n\tvar err error\n\n\tfor err == nil {\n\t\terr = r.tick()\n\t}\n\n\tif err != context.Canceled {\n\t\tr.done <- err\n\t}\n}", "func testClientCancel(transport string, t *testing.T) {\n\tserver := newTestServer(\"service\", new(Service))\n\tdefer server.Stop()\n\n\t// What we want to achieve is that the context gets canceled\n\t// at various stages of request processing. The interesting cases\n\t// are:\n\t// - cancel during dial\n\t// - cancel while performing a HTTP request\n\t// - cancel while waiting for a response\n\t//\n\t// To trigger those, the times are chosen such that connections\n\t// are killed within the deadline for every other call (maxKillTimeout\n\t// is 2x maxCancelTimeout).\n\t//\n\t// Once a connection is dead, there is a fair chance it won't connect\n\t// successfully because the accept is delayed by 1s.\n\tmaxContextCancelTimeout := 300 * time.Millisecond\n\tfl := &flakeyListener{\n\t\tmaxAcceptDelay: 1 * time.Second,\n\t\tmaxKillTimeout: 600 * time.Millisecond,\n\t}\n\n\tvar client *Client\n\tswitch transport {\n\tcase \"ws\", \"http\":\n\t\tc, hs := httpTestClient(server, transport, fl)\n\t\tdefer hs.Close()\n\t\tclient = c\n\tcase \"ipc\":\n\t\tc, l := ipcTestClient(server, fl)\n\t\tdefer l.Close()\n\t\tclient = c\n\tdefault:\n\t\tpanic(\"unknown transport: \" + transport)\n\t}\n\n\t// These tests take a lot of time, run them all at once.\n\t// You probably want to run with -parallel 1 or comment out\n\t// the call to t.Parallel if you enable the logging.\n\tt.Parallel()\n\n\t// The actual test starts here.\n\tvar (\n\t\twg sync.WaitGroup\n\t\tnreqs = 10\n\t\tncallers = 6\n\t)\n\tcaller := func(index int) {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < nreqs; i++ {\n\t\t\tvar (\n\t\t\t\tctx context.Context\n\t\t\t\tcancel func()\n\t\t\t\ttimeout = time.Duration(rand.Int63n(int64(maxContextCancelTimeout)))\n\t\t\t)\n\t\t\tif index < ncallers/2 {\n\t\t\t\t// For half of the callers, create a context without deadline\n\t\t\t\t// and cancel it later.\n\t\t\t\tctx, cancel = context.WithCancel(context.Background())\n\t\t\t\ttime.AfterFunc(timeout, cancel)\n\t\t\t} else {\n\t\t\t\t// For the other half, create a context with a deadline instead. This is\n\t\t\t\t// different because the context deadline is used to set the socket write\n\t\t\t\t// deadline.\n\t\t\t\tctx, cancel = context.WithTimeout(context.Background(), timeout)\n\t\t\t}\n\t\t\t// Now perform a call with the context.\n\t\t\t// The key thing here is that no call will ever complete successfully.\n\t\t\terr := client.CallContext(ctx, nil, \"service_sleep\", 2*maxContextCancelTimeout)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(fmt.Sprint(\"got expected error:\", err))\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"no error for call with %v wait time\", timeout)\n\t\t\t}\n\t\t\tcancel()\n\t\t}\n\t}\n\twg.Add(ncallers)\n\tfor i := 0; i < ncallers; i++ {\n\t\tgo caller(i)\n\t}\n\twg.Wait()\n}", "func (hc *HCDummy) do(hcr chan (HCResultError)) context.CancelFunc {\n\n\tgo func() {\n\t\thcr <- HCResultError{\n\t\t\tres: hc.result,\n\t\t\terr: nil,\n\t\t}\n\t}()\n\treturn nil\n}", "func (t *ElapsedTimeout) Wait(context.Context) error { return nil }", "func (s *Runservice) etcdPingerLoop(ctx context.Context) {\n\tfor {\n\t\tif err := s.etcdPinger(ctx); err != nil {\n\t\t\tlog.Errorf(\"err: %+v\", err)\n\t\t}\n\n\t\tsleepCh := time.NewTimer(1 * time.Second).C\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-sleepCh:\n\t\t}\n\t}\n}", "func (r *ManagedServicePollRequest) StartContext(ctx context.Context) (response *ManagedServicePollResponse, err error) {\n\tresult, err := helpers.PollContext(ctx, r.interval, r.statuses, r.predicates, r.task)\n\tif result != nil {\n\t\tresponse = &ManagedServicePollResponse{\n\t\t\tresponse: result.(*ManagedServiceGetResponse),\n\t\t}\n\t}\n\treturn\n}", "func cancelworker(ctx context.Context, jobChan <-chan Job) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase job := <-jobChan:\n\t\t\tprocess(job)\n\t\t}\n\t}\n}", "func (s *Service) Do(ctx context.Context) error {\n\tlog.Printf(\"[INFO] starting youtube service\")\n\n\tif s.SkipShorts > 0 {\n\t\tlog.Printf(\"[DEBUG] skip youtube episodes shorter than %v\", s.SkipShorts)\n\t}\n\tfor _, f := range s.Feeds {\n\t\tlog.Printf(\"[INFO] youtube feed %+v\", f)\n\t}\n\n\ttick := time.NewTicker(s.CheckDuration)\n\tdefer tick.Stop()\n\n\tif err := s.procChannels(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to process channels\")\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-tick.C:\n\t\t\tif err := s.procChannels(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to process channels\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (ec *client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {\n\terr := ec.rateLimiter.Wait(ctx)\n\tif err != nil {\n\t\tatomic.AddInt64(&ec.rateLimitDroppedRequests, 1)\n\t\t// Context cancelled or deadline exceeded\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, ec.requestTimeout)\n\tdefer cancel()\n\treturn ec.rpcClient.CallContext(ctx, &result, method, args...)\n}", "func (o *observer) run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\twg := sync.WaitGroup{}\n\n\t// Run healthcheck loop\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.runHealthcheckLoopFn(ctx)\n\t}()\n\n\t// Continuously sync worker pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncWorkerPodsFn(ctx)\n\t}()\n\n\t// Continuously sync job pods\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\to.syncJobPodsFn(ctx)\n\t}()\n\n\t// Wait for an error or a completed context\n\tvar err error\n\tselect {\n\t// In essence, this comprises the Observer's \"healthcheck\" logic.\n\t// Whenever we receive an error on this channel, we cancel the context and\n\t// shut down. E.g., if one loop fails, everything fails.\n\t// This includes:\n\t// 1. an error pinging the Brigade API server endpoint\n\t// (Observer <-> API comms)\n\t// 2. an error pinging the K8s API server endpoint\n\t// (Observer <-> K8s comms)\n\t//\n\t// Note: Currently, errors updating or cleaning up worker or job statuses\n\t// are handled by o.errFn, which currently simply logs the error\n\tcase err = <-o.errCh:\n\t\tcancel() // Shut it all down\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\t}\n\n\t// Adapt wg to a channel that can be used in a select\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(3 * time.Second):\n\t\t// Probably doesn't matter that this is hardcoded. Relatively speaking, 3\n\t\t// seconds is a lot of time for things to wrap up.\n\t}\n\n\treturn err\n}", "func (m *Manager) doAsync(ctx context.Context, target string, arg interface{}, period, timeout time.Duration, ops ...interface{}) {\n\tlogger := logging.FromContext(ctx)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tm.mu.Lock()\n\t\t\tdefer m.mu.Unlock()\n\t\t\tm.keys.Delete(target)\n\t\t}()\n\t\tvar (\n\t\t\tresult bool\n\t\t\tinErr error\n\t\t)\n\t\terr := wait.PollImmediate(period, timeout, func() (bool, error) {\n\t\t\tresult, inErr = Do(ctx, m.transport, target, ops...)\n\t\t\t// Do not return error, which is from verifierError, as retry is expected until timeout.\n\t\t\treturn result, nil\n\t\t})\n\t\tif inErr != nil {\n\t\t\tlogger.Errorw(\"Unable to read sockstat\", zap.Error(inErr))\n\t\t}\n\t\tm.cb(arg, result, err)\n\t}()\n}", "func main() {\n\tlog.Println(\"begin main...\")\n\tparentCtx, cancelParent := context.WithCancel(context.Background())\n\n\tchildTimeoutCtx, _ := context.WithTimeout(parentCtx, time.Second*10)\n\n\ttime.AfterFunc(time.Second*2, func() {\n\t\tlog.Println(\"Cancel parent context after 2s\")\n\t\tcancelParent()\n\t})\n\n\tselect {\n\tcase <-childTimeoutCtx.Done():\n\t\tlog.Println(\"Child context done! Normally this will called after Child ctx timeout (10s)\")\n\t}\n\n\t// cancelParent()\n\t// for i:=0;i<15 ;i++ {\n\t// \tfmt.Println(\"...\")\n\t// \ttime.Sleep(time.Second)\n\t// }\n}", "func (d *DeferredConfirmation) WaitContext(ctx context.Context) (bool, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn false, ctx.Err()\n\tcase <-d.done:\n\t}\n\treturn d.ack, nil\n}", "func (t *task) run(ctx context.Context) {\n\tif !t.changeState(IsCreated, IsRunning) {\n\t\treturn // Prevent from running the same task twice\n\t}\n\n\t// Notify everyone of the completion/error state\n\tdefer close(t.done)\n\n\t// Execute the task\n\tstartedAt := now().UnixNano()\n\toutcomeCh := make(chan outcome, 1)\n\tgo func() {\n\t\tr, e := t.action(ctx)\n\t\toutcomeCh <- outcome{result: r, err: e}\n\t}()\n\n\tselect {\n\n\t// In case of a manual task cancellation, set the outcome and transition\n\t// to the cancelled state.\n\tcase <-t.cancel:\n\t\tt.duration = time.Nanosecond * time.Duration(now().UnixNano()-startedAt)\n\t\tt.outcome = outcome{err: errCancelled}\n\t\tt.changeState(IsRunning, IsCancelled)\n\t\treturn\n\n\t// In case of the context timeout or other error, change the state of the\n\t// task to cancelled and return right away.\n\tcase <-ctx.Done():\n\t\tt.duration = time.Nanosecond * time.Duration(now().UnixNano()-startedAt)\n\t\tt.outcome = outcome{err: ctx.Err()}\n\t\tt.changeState(IsRunning, IsCancelled)\n\t\treturn\n\n\t// In case where we got an outcome (happy path)\n\tcase o := <-outcomeCh:\n\t\tt.duration = time.Nanosecond * time.Duration(now().UnixNano()-startedAt)\n\t\tt.outcome = o\n\t\tt.changeState(IsRunning, IsCompleted)\n\t\treturn\n\t}\n}", "func TestLookupMethodsDoNotRunIfContextIsDone(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tcancel()\n\n\tif _, err := lookupDNS(ctx, nil, \"name\", \"ws\"); err == nil {\n\t\tt.Errorf(\"lookupDNS should not run if the context is canceled, got: %q.\", err)\n\t}\n\tif _, err := lookupHostMeta(ctx, nil, \"name\", \"ws\"); err != context.Canceled {\n\t\tt.Error(\"lookupHostMeta should not run if the context is canceled.\")\n\t}\n}", "func (ts *TimeService) Run() {\n\tfor {\n\t\tselect {\n\t\tcase <-ts.Dead:\n\t\t\tts.ReqChan <- Request{true, nil}\n\t\t\t// close(ts.ReqChan)\n\t\t\treturn\n\t\tcase req := <-ts.ReqChan:\n\t\t\tprocessingTime := time.Duration(ts.AvgResponseTime+1.0-rand.Float64()) * time.Second\n\t\t\ttime.Sleep(processingTime)\n\t\t\treq.RspChan <- time.Now()\n\t\t}\n\t}\n}", "func (s *ServiceManager) Run(routine func(ctx context.Context) error) (err error) {\n\ts.Start(routine)\n\treturn s.Wait()\n}", "func (c *Context) Canceled() <-chan struct{} {\n\tif c.Request == nil {\n\t\treturn nil\n\t}\n\treturn c.Request.Canceled()\n}", "func (c *Circuit) run(ctx context.Context, runFunc func(context.Context) error) (retErr error) {\n\tif runFunc == nil {\n\t\treturn nil\n\t}\n\tvar expectedDoneBy time.Time\n\tstartTime := c.now()\n\toriginalContext := ctx\n\n\tif !c.allowNewRun(startTime) {\n\t\t// Rather than make this inline, return a global reference (for memory optimization sake).\n\t\tc.CmdMetricCollector.ErrShortCircuit(startTime)\n\t\treturn errCircuitOpen\n\t}\n\n\tif c.ClosedToOpen.Prevent(startTime) {\n\t\treturn errCircuitOpen\n\t}\n\n\tcurrentCommandCount := c.concurrentCommands.Add(1)\n\tdefer c.concurrentCommands.Add(-1)\n\tif err := c.throttleConcurrentCommands(currentCommandCount); err != nil {\n\t\tc.CmdMetricCollector.ErrConcurrencyLimitReject(startTime)\n\t\treturn err\n\t}\n\n\t// Set timeout on the command if we have one\n\tif c.threadSafeConfig.Execution.ExecutionTimeout.Get() > 0 {\n\t\tvar timeoutCancel func()\n\t\texpectedDoneBy = startTime.Add(c.threadSafeConfig.Execution.ExecutionTimeout.Duration())\n\t\tctx, timeoutCancel = context.WithDeadline(ctx, expectedDoneBy)\n\t\tdefer timeoutCancel()\n\t}\n\n\tret := runFunc(ctx)\n\tendTime := c.now()\n\ttotalCmdTime := endTime.Sub(startTime)\n\trunFuncDoneTime := c.now()\n\t// See bad request documentation at https://github.com/Netflix/Hystrix/wiki/How-To-Use#error-propagation\n\t// This request had invalid input, but shouldn't be marked as an 'error' for the circuit\n\t// From documentation\n\t// -------\n\t// The HystrixBadRequestException is intended for use cases such as reporting illegal arguments or non-system\n\t// failures that should not count against the failure metrics and should not trigger fallback logic.\n\tif c.checkErrBadRequest(ret, runFuncDoneTime, totalCmdTime) {\n\t\treturn ret\n\t}\n\n\t// Even if there is no error (or if there is an error), if the request took too long it is always an error for the\n\t// circuit. Note that ret *MAY* actually be nil. In that case, we still want to return nil.\n\tif c.checkErrTimeout(expectedDoneBy, runFuncDoneTime, totalCmdTime) {\n\t\t// Note: ret could possibly be nil. We will still return nil, but the circuit will consider it a failure.\n\t\treturn ret\n\t}\n\n\t// The runFunc failed, but someone asked the original context to end. This probably isn't a failure of the\n\t// circuit: someone just wanted `Execute` to end early, so don't track it as a failure.\n\tif c.checkErrInterrupt(originalContext, ret, runFuncDoneTime, totalCmdTime) {\n\t\treturn ret\n\t}\n\n\tif c.checkErrFailure(ret, runFuncDoneTime, totalCmdTime) {\n\t\treturn ret\n\t}\n\n\t// The circuit works. Close it!\n\t// Note: Execute this *after* you check for timeouts so we can still track circuit time outs that happen to also return a\n\t// valid value later.\n\tc.checkSuccess(runFuncDoneTime, totalCmdTime)\n\treturn nil\n}", "func Cancel(w http.ResponseWriter, r *http.Request) {\n\terr := command.New(getFlags(r.URL.Query())).\n\t\tStopRunningCommand().\n\t\tError\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func TestTaskContext(t *testing.T) {\n\tt.Run(\"reflect external context\", func(t *testing.T) {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\ttask := Start(ctx, TaskFuncDoneErr)\n\n\t\tnotDone(task)\n\t\teq(nil, task.Err())\n\n\t\tcancel()\n\t\twaitDone(task)\n\t\teq(true, errors.Is(task.Err(), context.Canceled))\n\t})\n\n\tt.Run(\"wait on external context, override error\", func(t *testing.T) {\n\t\tsentinel := fmt.Errorf(`sentinel`)\n\n\t\tfun := func(ctx Task) error {\n\t\t\twaitDone(ctx)\n\t\t\treturn sentinel\n\t\t}\n\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\ttask := Start(ctx, fun)\n\n\t\tnotDone(task)\n\t\teq(nil, task.Err())\n\n\t\tcancel()\n\t\twaitDone(task)\n\t\teq(true, errors.Is(task.Err(), sentinel))\n\t})\n}", "func (c *context) Done() <-chan struct{} { return c.c.Done() }", "func (m *Manager) WaitUntilRunning() {\n\tfor {\n\t\tm.mu.Lock()\n\n\t\tif m.ctx != nil {\n\t\t\tm.mu.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tstarted := m.started\n\t\tm.mu.Unlock()\n\n\t\t// Block until we have been started.\n\t\t<-started\n\t}\n}", "func (f *Fetcher) Stop() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tf.cancel()\n}", "func (r Reflector) Run(ctx context.Context) error {\n\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\n\t// Grab all goroutines error into err\n\tvar err error\n\terrLock := sync.Mutex{}\n\twg := &sync.WaitGroup{}\n\n\t// Goroutine fetch events from API server and schedule them\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif gErr := r.runFetcher(ctx); gErr != nil {\n\t\t\terrLock.Lock()\n\t\t\terr = multierr.Append(err, gErr)\n\t\t\terrLock.Unlock()\n\t\t\tr.log.Errorw(\"Error during fetching events. Send signal to stop\", zap.Error(err))\n\t\t\tcancel()\n\t\t} else {\n\t\t\tr.log.Info(\"Event fetcher was stopped\")\n\t\t}\n\t}()\n\n\n\t// Handler. Can re-schedule event if temporary error happens\n\tfor i := 0; i < r.workersCount; i++ {\n\t\twg.Add(1)\n\t\tlog := r.log.With(\"WorkerID\", i)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tr.runProcessor(log)\n\t\t\tlog.Info(\"Worker was stopped\")\n\t\t}()\n\t}\n\tr.log.Infof(\"Start %d workers\", r.workersCount)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tr.log.Debug(\"Get cancel signal. Shutdown queue\")\n\t\tr.queue.ShutDown()\n\t}()\n\n\twg.Wait()\n\n\treturn err\n}", "func (c *Context) Cancel() {\n\tif c.cancel != nil {\n\t\tc.cancel()\n\t}\n}", "func (h *handler) Stop(ctx context.Context) {\n\th.closeOnce.Do(func() {\n\t\th.startClosingTime = h.clock.Time()\n\n\t\t// Must hold the locks here to ensure there's no race condition in where\n\t\t// we check the value of [h.closing] after the call to [Signal].\n\t\th.syncMessageQueue.Shutdown()\n\t\th.asyncMessageQueue.Shutdown()\n\t\tclose(h.closingChan)\n\n\t\t// TODO: switch this to use a [context.Context] with a cancel function.\n\t\t//\n\t\t// Don't process any more bootstrap messages. If a dispatcher is\n\t\t// processing a bootstrap message, stop. We do this because if we\n\t\t// didn't, and the engine was in the middle of executing state\n\t\t// transitions during bootstrapping, we wouldn't be able to grab\n\t\t// [h.ctx.Lock] until the engine finished executing state transitions,\n\t\t// which may take a long time. As a result, the router would time out on\n\t\t// shutting down this chain.\n\t\tstate := h.ctx.State.Get()\n\t\tbootstrapper, ok := h.engineManager.Get(state.Type).Get(snow.Bootstrapping)\n\t\tif !ok {\n\t\t\th.ctx.Log.Error(\"bootstrapping engine doesn't exists\",\n\t\t\t\tzap.Stringer(\"type\", state.Type),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tbootstrapper.Halt(ctx)\n\t})\n}", "func channelCancellation(stop <-chan struct{}) {\n\n\t// Create a cancel context for handling the stop signal.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// If a signal is received on the stop channel, cancel the\n\t// context. This will propagate the cancel into the p.Run\n\t// function below.\n\tgo func() {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t}\n\t}()\n\n\t// Imagine a function that is performing an I/O operation that is\n\t// cancellable.\n\tfunc(ctx context.Context) error {\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, \"https://www.ardanlabs.com/blog/index.xml\", nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}(ctx)\n}", "func waitForShutdown(ctx context.Context, service *PortService, logger *logrus.Logger) {\n\t<-ctx.Done()\n\tservice.grpcServer.GracefulStop()\n\tlogger.Infoln(\"grpc service stopped\")\n\tservice.dbSession.Close()\n\tlogger.Infoln(\"db session closed\")\n}", "func (_m *Manager) WaitStop() {\n\t_m.Called()\n}", "func (s *ServiceManager) Wait() (err error) {\n\tcases := s.buildSelectCases()\n\n\t// waits for the ServiceManager to confirm running state\n\t<-s.waitForRunning\n\t// waitForRunning will never be used again, discard memory\n\tclose(s.waitForRunning)\n\ts.waitForRunning = nil\n\n\trunning := true\n\tfor running {\n\t\t// chosen is the index of the selected case\n\t\t// recv is the value obtained, which will always be a SignalControl function\n\t\t// ok = false if the channel is closed\n\t\tchosen, recv, ok := reflect.Select(cases)\n\t\tif !ok {\n\t\t\t// not OK: channel was closed, remove from the list as we'll never receive any messages on it\n\t\t\t// It makes no sense to listen to it any more\n\t\t\tl := 0\n\t\t\ts.mu.Lock()\n\t\t\ts.removeSignaler(chosen)\n\t\t\tl = len(s.signalers)\n\t\t\ts.mu.Unlock()\n\t\t\tif l == 0 {\n\t\t\t\t// we're out of channels, stop the for loop\n\t\t\t\t// We'll need to wait for the server to end-itself. Closing channels does not stop the service,\n\t\t\t\t// but only the means of stopping that service\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// we need to re-build the missing cases as now one is missing\n\t\t\tcases = s.buildSelectCases()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Channel was not closed, we received a message\n\t\tswitch chanType := recv.Interface().(type) {\n\t\tcase SignalControl:\n\t\t\t// Our signal was OK, channel is not closed. Let's see what it says:\n\t\t\tswitch chanType(s) {\n\t\t\tcase GracefulRestart:\n\t\t\t\t// We need to gracefully restart\n\t\t\t\t// Trigger cancelling the context\n\t\t\t\t// We copy the value and set it to nil here to avoid having the inner go-routine call cancel a second time\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateRestarting\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\tcase GracefulStop:\n\t\t\t\t// We need to stop the service\n\t\t\t\trunning = false\n\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.state = StateDying\n\t\t\t\tif s.cancelFunc != nil {\n\t\t\t\t\ts.cancelFunc()\n\t\t\t\t\ts.cancelFunc = nil\n\t\t\t\t}\n\t\t\t\ts.mu.Unlock()\n\n\t\t\t\t// We're stopping, we need to wait for the goroutine to signal that it completed\n\t\t\t\terr = <-s.waitForIteratorDone\n\t\t\t}\n\t\tcase error:\n\t\t\t// This means our routine completed and is no longer running\n\t\t\trunning = false\n\t\t\ts.setState(StateDying)\n\n\t\t\t// The main service routine ended so we CANNOT wait for the goroutine to signal that it completed as it's already done\n\t\t\t// this also means that the context has already cleaned itself up, so no need to call s.cancelFunc\n\t\t\t// chanType could be nil, meaning no error\n\t\t\terr = chanType\n\n\t\t}\n\t}\n\n\t// Recover goroutine leak, if any\n\ts.cancelSignalers()\n\n\ts.setState(StateDead)\n\n\tclose(s.waitForIteratorDone)\n\n\treturn\n}", "func CtxCancelIfCanceled(f context.CancelFunc, ctxCanceler context.Context) chan struct{} {\n\tquitCh := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-quitCh:\n\t\tcase <-ctxCanceler.Done():\n\t\t\tf()\n\t\t}\n\t}()\n\treturn quitCh\n}", "func (s *DeterminationWithContext) WhileRunning(do func(context.Context) error) error {\n\treturn s.whilerunning(func() error {\n\t\tselect {\n\t\tcase <-s.sctx.Done():\n\t\t\treturn ErrRunnerIsClosing\n\t\tdefault:\n\t\t\treturn do(s.sctx)\n\t\t}\n\t})\n}", "func (c *authorizer) runSafely(ctx context.Context, e *otto.Otto, script string, timeout time.Duration) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif e == errTimeout {\n\t\t\t\terr = errTimeout\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\te.Interrupt = make(chan func(), 1)\n\n\t// @check for a timeout and if not there, set the default\n\tif timeout <= 0 {\n\t\ttimeout = NewDefaultConfig().Timeout\n\t}\n\n\t// @step: setup a timer and done channel\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif err := ctx.Err(); err != nil {\n\t\t\t\te.Interrupt <- func() {\n\t\t\t\t\tpanic(errTimeout)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t_, err = e.Run(script)\n\n\treturn err\n}", "func main() {\n\t// example with cancel\n\t// create gen function\n\tgen := func(ctx context.Context) <-chan int {\n\t\tout := make(chan int)\n\n\t\t// start a go routine to send data\n\t\tgo func() {\n\t\t\tn := 0\n\t\t\tfor { // run forever until ctx cancel\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase out <- n:\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn out\n\t}\n\n\t// create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\t// now we consume\n\tfor n := range gen(ctx) {\n\t\tfmt.Println(n)\n\t\tif n == 5 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// context with deadline\n\n\t// test other functions\n\tfunc1()\n\tfunc2()\n\tfunc3()\n\tfunc4timeout()\n}", "func getContext() (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(context.Background(), contextTimeoutS*time.Second)\n}" ]
[ "0.6193103", "0.6120287", "0.57976997", "0.57190824", "0.5682836", "0.55433846", "0.5509649", "0.5504925", "0.54945695", "0.5489741", "0.54321957", "0.53894144", "0.5374803", "0.53302985", "0.53238547", "0.53223896", "0.53171813", "0.5277856", "0.5247848", "0.5227462", "0.52219874", "0.5219245", "0.5205896", "0.5185294", "0.5181693", "0.51765", "0.5176352", "0.51751137", "0.5146381", "0.5130962", "0.51236296", "0.5113114", "0.509418", "0.50810146", "0.5077245", "0.50634515", "0.505643", "0.5055427", "0.50495994", "0.5038089", "0.50335914", "0.50335914", "0.5032998", "0.50115937", "0.50110406", "0.5009974", "0.5006021", "0.5003502", "0.4993243", "0.49889538", "0.49715984", "0.49576232", "0.49570677", "0.49490002", "0.49456185", "0.4943101", "0.4934511", "0.4930492", "0.49242082", "0.49161085", "0.4913516", "0.49121976", "0.4908531", "0.48978087", "0.48960513", "0.48814237", "0.48703614", "0.48576674", "0.48474103", "0.4841563", "0.48400664", "0.48370525", "0.48271924", "0.4827079", "0.48225456", "0.48214358", "0.48170006", "0.48147723", "0.48117688", "0.48104405", "0.4808066", "0.48073316", "0.48065618", "0.48032308", "0.47976393", "0.47954723", "0.479183", "0.47717664", "0.47586453", "0.47580248", "0.47520614", "0.47496223", "0.47492996", "0.47484082", "0.47456092", "0.47430027", "0.4740501", "0.47372097", "0.4731323", "0.4729497", "0.47284406" ]
0.0
-1
GetLocal returns a kubernetes client with the local configuration. It will detect if KUBECONFIG is defined.
func GetLocal() (*kubernetes.Clientset, *rest.Config, string, error) { if client == nil { var err error clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: ""}}) namespace, _, err = clientConfig.Namespace() if err != nil { return nil, nil, "", err } config, err = clientConfig.ClientConfig() if err != nil { return nil, nil, "", err } client, err = kubernetes.NewForConfig(config) if err != nil { return nil, nil, "", err } } return client, config, namespace, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetLocalKubeClient() (*kubernetes.Clientset, *rest.Config, error) {\n\tconfigPath, err := EnsureLocalPath(\n\t\tos.Getenv(constants.EnvKubeConfig), defaults.KubeConfigDir, defaults.KubeConfigFile)\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\n\tclient, config, err := GetKubeClient(configPath)\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\n\treturn client, config, nil\n}", "func getConfigForLocalCluster() (*rest.Config, error) {\n\tremoteSecretPath := kialiconfig.Get().Deployment.RemoteSecretPath\n\tif remoteSecret, readErr := GetRemoteSecret(remoteSecretPath); readErr == nil {\n\t\tlog.Debugf(\"Using remote secret for local cluster config found at: [%s]. Kiali must be running outside the kube cluster.\", remoteSecretPath)\n\t\treturn clientcmd.NewDefaultClientConfig(*remoteSecret, nil).ClientConfig()\n\t} else {\n\t\tlog.Debugf(\"Unable to read remote secret. It may or may not exist. Error: %v. Falling back to in cluster config\", readErr)\n\t\t// Fallback to in cluster config\n\t\tincluster, err := rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error '%v' getting config for local cluster\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\treturn incluster, nil\n\t}\n}", "func GetClient() *rest.RESTClient {\n\tconfig, err := buildOutOfClusterConfig()\n\tif err != nil {\n\t\tlog.Warnf(\"Can not get kubernetes config: %v\", err)\n\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not get kubernetes config: %v\", err)\n\t\t}\n\t}\n\tconfig.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\tc, err := rest.UnversionedRESTClientFor(config)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot create REST client, try setting KUBECONFIG environment variable: %v\", err)\n\t}\n\treturn c\n}", "func GetClient() kubernetes.Interface {\n\tvar kubeClient kubernetes.Interface\n\t_, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tkubeClient = getClientOutOfCluster()\n\t} else {\n\t\tkubeClient = getClientInCluster()\n\t}\n\n\treturn kubeClient\n}", "func GetKubeClient(t testing.TB) *kube.Clientset {\n\tvar config *rest.Config\n\thost := os.Getenv(\"KUBERNETES_SERVICE_HOST\")\n\tif host != \"\" {\n\t\tvar err error\n\t\tconfig, err = rest.InClusterConfig()\n\t\trequire.NoError(t, err)\n\t} else {\n\t\t// Use kubectl binary to parse .kube/config and get address of current\n\t\t// cluster. Hopefully, once we upgrade to k8s.io/client-go, we will be able\n\t\t// to do this in-process with a library\n\t\t// First, figure out if we're talking to minikube or localhost\n\t\tcmd := exec.Command(\"kubectl\", \"config\", \"current-context\")\n\t\tcmd.Stderr = os.Stderr\n\t\tif context, err := cmd.Output(); err == nil {\n\t\t\tcontext = bytes.TrimSpace(context)\n\t\t\t// kubectl has a context -- not talking to localhost\n\t\t\t// Get cluster and user name from kubectl\n\t\t\tbuf := &bytes.Buffer{}\n\t\t\tcmd := BashCmd(strings.Join([]string{\n\t\t\t\t`kubectl config get-contexts \"{{.context}}\" | tail -n+2 | awk '{print $3}'`,\n\t\t\t\t`kubectl config get-contexts \"{{.context}}\" | tail -n+2 | awk '{print $4}'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"context\", string(context))\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes context info\")\n\t\t\tlines := strings.Split(buf.String(), \"\\n\")\n\t\t\tclustername, username := lines[0], lines[1]\n\n\t\t\t// Get user info\n\t\t\tbuf.Reset()\n\t\t\tcmd = BashCmd(strings.Join([]string{\n\t\t\t\t`cluster=\"$(kubectl config view -o json | jq -r '.users[] | select(.name == \"{{.user}}\") | .user' )\"`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"client-certificate\"]'`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"client-key\"]'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"user\", username)\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes user info\")\n\t\t\tlines = strings.Split(buf.String(), \"\\n\")\n\t\t\tclientCert, clientKey := lines[0], lines[1]\n\n\t\t\t// Get cluster info\n\t\t\tbuf.Reset()\n\t\t\tcmd = BashCmd(strings.Join([]string{\n\t\t\t\t`cluster=\"$(kubectl config view -o json | jq -r '.clusters[] | select(.name == \"{{.cluster}}\") | .cluster')\"`,\n\t\t\t\t`echo \"${cluster}\" | jq -r .server`,\n\t\t\t\t`echo \"${cluster}\" | jq -r '.[\"certificate-authority\"]'`,\n\t\t\t}, \"\\n\"),\n\t\t\t\t\"cluster\", clustername)\n\t\t\tcmd.Stdout = buf\n\t\t\trequire.NoError(t, cmd.Run(), \"couldn't get kubernetes cluster info: %s\", buf.String())\n\t\t\tlines = strings.Split(buf.String(), \"\\n\")\n\t\t\taddress, CAKey := lines[0], lines[1]\n\n\t\t\t// Generate config\n\t\t\tconfig = &rest.Config{\n\t\t\t\tHost: address,\n\t\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\t\tCertFile: clientCert,\n\t\t\t\t\tKeyFile: clientKey,\n\t\t\t\t\tCAFile: CAKey,\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\t// no context -- talking to localhost\n\t\t\tconfig = &rest.Config{\n\t\t\t\tHost: \"http://0.0.0.0:8080\",\n\t\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tk, err := kube.NewForConfig(config)\n\trequire.NoError(t, err)\n\treturn k\n}", "func GetClient() (*kubernetes.Clientset, error) {\n\tvar kubeConfig rest.Config\n\n\t// Set the Kubernetes configuration based on the environment\n\tif RunningInCluster() {\n\t\tconfig, err := rest.InClusterConfig()\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create in-cluster config: %v\", err)\n\t\t}\n\n\t\tkubeConfig = *config\n\t} else {\n\t\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\t\tconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\t\ttmpKubeConfig, err := config.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load local kube config: %v\", err)\n\t\t}\n\n\t\tkubeConfig = *tmpKubeConfig\n\t}\n\n\t// Create the Kubernetes client based on the configuration\n\treturn kubernetes.NewForConfig(&kubeConfig)\n}", "func getKubernetesClient() (kubernetes.Interface){\r\n\t// construct the path to resolve to `~/.kube/config`\r\n config, err := rest.InClusterConfig()\r\n if err != nil {\r\n kubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\r\n // kubeConfigPath := \"/etc/kubernetes/scheduler.conf\"\r\n\r\n //create the config from the path\r\n config, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\r\n if err != nil {\r\n log.Fatalf(\"getInClusterConfig: %v\", err)\r\n panic(\"Failed to load kube config\")\r\n }\r\n }\r\n\r\n // Same settings as the default scheduler\r\n config.QPS = 100\r\n config.Burst = 200\r\n\r\n // generate the client based off of the config\r\n client, err := kubernetes.NewForConfig(config)\r\n if err != nil {\r\n panic(\"Failed to create kube client\")\r\n }\r\n\r\n\tlog.Info(\"Successfully constructed k8s client\")\r\n\treturn client\r\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (f ClientFactoryFunc) GetClient(kubeconfig []byte) (client.Client, string, error) {\n\treturn f(kubeconfig)\n}", "func getClient(kubeconfig *Kubeconfig) (*kubernetes.Clientset, error) {\n\t// Usually we don't need a client. But in this case, we _might_ if we're using detect.\n\t// So pass in nil if we get an error, then display the errors from trying to get a client\n\t// if it turns out we needed it.\n\tcfg, err := kubeconfig.Get()\n\tvar client *kubernetes.Clientset\n\n\tvar kubeError error\n\tif err == nil {\n\t\tclient, err = kubernetes.NewForConfig(cfg)\n\t\tif err != nil {\n\t\t\tkubeError = err\n\t\t}\n\t} else {\n\t\tkubeError = err\n\t}\n\n\treturn client, kubeError\n}", "func getKubernetesClient() kubernetes.Interface {\n\t// construct the path to resolve to `~/.kube/config`\n\tkubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\n\n\t// create the config from the path\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"getClusterConfig: %v\", err)\n\t}\n\n\t// generate the client based off of the config\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"getClusterConfig: %v\", err)\n\t}\n\n\tlog.Info(\"Successfully constructed k8s client\")\n\treturn client\n}", "func getClient(k8sconfig string) (*kubernetes.Clientset, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", k8sconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset, nil\n}", "func getK8sConfig(context string) clientcmd.ClientConfig {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif context != \"\" {\n\t\toverrides.CurrentContext = context\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n}", "func GetRemoteKubernetesClient(kubeconfig string) (*K8s, error) {\n\tlogger := utils.GetK8sAPILogger()\n\tif !TRACE_API {\n\t\tlogger.SetLevel(utils.Info)\n\t}\n\n\t// use the current context in kubeconfig\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// create the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn &K8s{\n\t\tAPI: clientset,\n\t\tLogger: logger,\n\t}, nil\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func GetClient() (*client.Client, error) {\n\tvar kubeConfig restclient.Config\n\n\t// Set the Kubernetes configuration based on the environment\n\tif _, err := os.Stat(\"/var/run/secrets/kubernetes.io/serviceaccount/token\"); err == nil {\n\t\tconfig, err := restclient.InClusterConfig()\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to create in-cluster config: %v.\", err)\n\t\t}\n\n\t\tkubeConfig = *config\n\t} else {\n\t\tkubeConfig = restclient.Config{\n\t\t\tHost: os.Getenv(\"KUBE_HOST\"),\n\t\t}\n\n\t\tif kubeConfig.Host == \"\" {\n\t\t\treturn nil, fmt.Errorf(ErrNeedsKubeHostSet)\n\t\t}\n\t}\n\n\t// Create the Kubernetes client based on the configuration\n\treturn client.New(&kubeConfig)\n}", "func (c config) Client(env string) (kubeClient, error) {\n\treturn c.clp(env)\n}", "func createKubeClient() (kubernetes.Interface, error) {\n\tif mockedController {\n\t\treturn fake.NewSimpleClientset(), nil\n\t}\n\tkubeconfig, ok := os.LookupEnv(EnvLiqoKConfig)\n\tif !ok || kubeconfig == \"\" {\n\t\treturn nil, errors.New(\"no kubeconfig provided\")\n\t}\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(cfg)\n}", "func getClientConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}", "func getConfig(serverURL, kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig == \"\" {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\t// If we have an explicit indication of where the kubernetes config lives, read that.\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(serverURL, kubeconfig)\n\t}\n\t// If not, try the in-cluster config.\n\tif c, err := rest.InClusterConfig(); err == nil {\n\t\treturn c, nil\n\t}\n\t// If no in-cluster config, try the default location in the user's home directory.\n\tif usr, err := user.Current(); err == nil {\n\t\tif c, err := clientcmd.BuildConfigFromFlags(\"\", filepath.Join(usr.HomeDir, \".kube\", \"config\")); err == nil {\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"could not create a valid kubeconfig\")\n}", "func Client() (*ClientK8s, error) {\n\tcfg, err := CreateConfig(option.OperatorConfig.K8sAPIServerURL,\n\t\toption.OperatorConfig.KubeCfgPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ClientK8s{Interface: c}, nil\n}", "func shouldUseKubeLocalProxy(cf *CLIConf, kubectlArgs []string) (*clientcmdapi.Config, kubeconfig.LocalProxyClusters, bool) {\n\t// When failed to load profile, assume this CLI command is not running\n\t// against Teleport clusters.\n\tprofile, err := cf.GetProfile()\n\tif err != nil {\n\t\treturn nil, nil, false\n\t}\n\n\tif !profile.RequireKubeLocalProxy() {\n\t\treturn nil, nil, false\n\t}\n\n\t// Skip \"kubectl config\" commands.\n\tvar kubeconfigLocation, selectedContext string\n\tif len(kubectlArgs) > 0 {\n\t\tkubectlCommand := makeKubectlCobraCommand()\n\t\tif isKubectlConfigCommand(kubectlCommand, kubectlArgs) {\n\t\t\treturn nil, nil, false\n\t\t}\n\n\t\tkubeconfigLocation, selectedContext = extractKubeConfigAndContextFromCommand(kubectlCommand, kubectlArgs)\n\t}\n\n\t// Nothing to do if cannot load original kubeconfig.\n\tdefaultConfig, err := kubeconfig.Load(kubeconfigLocation)\n\tif err != nil {\n\t\treturn nil, nil, false\n\t}\n\n\t// Prepare Teleport kube cluster based on selected context.\n\tkubeCluster, found := kubeconfig.FindTeleportClusterForLocalProxy(defaultConfig, kubeClusterAddrFromProfile(profile), selectedContext)\n\tif !found {\n\t\treturn nil, nil, false\n\t}\n\treturn defaultConfig, kubeconfig.LocalProxyClusters{kubeCluster}, true\n}", "func getKubeClient(context string) (*rest.Config, kubernetes.Interface, error) {\n\tconfig, err := configForContext(context)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not get Kubernetes client: %s\", err)\n\t}\n\treturn config, client, nil\n}", "func GetKubernetesClient() ClientSets {\n\t// construct the path to resolve to `~/.kube/config`\n\tkubeConfigPath := os.Getenv(\"HOME\") + \"/.kube/config\"\n\n\t// create the config from the path\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig config: %v\", err))\n\n\t}\n\n\tfmt.Println(\"Successfully constructed config\")\n\n\t// generate the client based off of the config\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig originalClient: %v\", err))\n\t}\n\n\tfmt.Println(\"Successfully constructed k8s client\")\n\n\n\tcustomClient, err := netsys_client.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"GetClusterConfig customClient: %v\", err))\n\t}\n\n\tfmt.Println(\"Successfully constructed custom client\")\n\n\treturn ClientSets{\n\t\tOriginalClient: client,\n\t\tNetsysClient: customClient,\n\t}\n}", "func LoadClient(kubeconfigPath string) (*k8s.Client, error) {\n\n if(kubeconfigPath == \"\") {\n log.Info(\"Using in-cluster configuration\")\n return k8s.NewInClusterClient()\n } else {\n data, err := ioutil.ReadFile(kubeconfigPath)\n if err != nil {\n return nil, fmt.Errorf(\"read kubeconfig: %v\", err)\n }\n\n // Unmarshal YAML into a Kubernetes config object.\n var config k8s.Config\n if err := yaml.Unmarshal(data, &config); err != nil {\n return nil, fmt.Errorf(\"unmarshal kubeconfig: %v\", err)\n }\n return k8s.NewClient(&config)\n }\n}", "func (c *Client) IsLocalKubernetes() bool {\n\treturn c.IsKubernetes\n}", "func getKubernetesClient(context, kubeConfigPath string) (kubernetes.Interface, error) {\n\tconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeConfigPath},\n\t\t&clientcmd.ConfigOverrides{\n\t\t\tCurrentContext: context,\n\t\t}).ClientConfig()\n\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create client config: %w\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(\"failed to create kubernetes clientset: %w\", err)\n\t}\n\n\treturn clientset, nil\n}", "func getKubeClient(context string, kubeconfig string) (*rest.Config, kubernetes.Interface, error) {\n\tconfig, err := configForContext(context, kubeconfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not get Kubernetes client: %s\", err)\n\t}\n\treturn config, client, nil\n}", "func GetConfig() *rest.Config {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.ExplicitPath = KubeConfigPath()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tconfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides).ClientConfig()\n\tif err != nil {\n\t\tlog.Warnf(\"could not open %v Error %v\", loadingRules.ExplicitPath, err)\n\t}\n\treturn config\n}", "func (aip *AzureInfrastructureProvider) GetKubeConfig(request entities.ClusterRequest) (entities.InfrastructureOperation, derrors.Error) {\n\treturn NewManagementOperation(aip.credentials, request, entities.GetKubeConfig, aip.config)\n}", "func Client(kubeConfig string) *kubernetes.Clientset {\n\tvar config *rest.Config\n\tvar clientSet *kubernetes.Clientset\n\tvar err error\n\tif os.Getenv(\"KUBERNETES_SERVICE_HOST\") != \"\" && os.Getenv(\"KUBERNETES_SERVICE_PORT\") != \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tclientSet, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeConfig)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tclientSet, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\treturn clientSet\n}", "func getClusterConfig(inCluster bool) (*rest.Config, error) {\n\tif inCluster {\n\t\treturn rest.InClusterConfig()\n\t}\n\tconfigFile := getKubeConfigFile()\n\n\tif len(configFile) > 0 {\n\n\t\tlog.Infof(\"Reading config from file: %v\", configFile)\n\t\t// use the current context in kubeconfig\n\t\t// This is very useful for running locally.\n\t\tclientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: configFile},\n\t\t\t&clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: \"\"}})\n\n\t\trawConfig, err := clientConfig.RawConfig()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := modifyGcloudCommand(&rawConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig, err := clientConfig.ClientConfig()\n\t\treturn config, err\n\t}\n\n\t// Work around https://github.com/kubernetes/kubernetes/issues/40973\n\t// See https://github.com/coreos/etcd-operator/issues/731#issuecomment-283804819\n\tif len(os.Getenv(\"KUBERNETES_SERVICE_HOST\")) == 0 {\n\t\taddrs, err := net.LookupHost(\"kubernetes.default.svc\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif err := os.Setenv(\"KUBERNETES_SERVICE_HOST\", addrs[0]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(os.Getenv(\"KUBERNETES_SERVICE_PORT\")) == 0 {\n\t\tif err := os.Setenv(\"KUBERNETES_SERVICE_PORT\", \"443\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tconfig, err := rest.InClusterConfig()\n\treturn config, err\n}", "func getKubeClient(dnsAddress string) (*kubernetes.Clientset, *rest.Config, error) {\n\terr := httplib.InGravity(dnsAddress)\n\tif err != nil {\n\t\tlogrus.Infof(\"Not in Gravity: %v.\", err)\n\t\treturn utils.GetLocalKubeClient()\n\t}\n\t// Resolve the API server address in advance.\n\thost, err := utils.ResolveAddr(dnsAddress, fmt.Sprintf(\"%v:%v\",\n\t\tconstants.APIServerDomainName, defaults.APIServerSecurePort))\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\tkubeClient, kubeConfig, err := httplib.GetClusterKubeClient(dnsAddress,\n\t\thttplib.WithHost(fmt.Sprintf(\"https://%v\", host)))\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\treturn kubeClient, kubeConfig, nil\n}", "func newKubeClient(kubeConfig, apiServerURL string, requestTimeout time.Duration) (kubernetes.Interface, managednodeClientset.Interface, apiextensionClientset.Interface, error) {\n\tglog.Infof(\"Instantiating new Kubernetes client\")\n\n\tconfig, err := getRestConfig(kubeConfig, apiServerURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tconfig.Timeout = requestTimeout * time.Second\n\n\tconfig.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn instrumented_http.NewTransport(rt, &instrumented_http.Callbacks{\n\t\t\tPathProcessor: func(path string) string {\n\t\t\t\tparts := strings.Split(path, \"/\")\n\t\t\t\treturn parts[len(parts)-1]\n\t\t\t},\n\t\t})\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tnodeManagerClientset, err := managednodeClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nil, nil, err\n\t}\n\n\tapiExtensionClient, err := apiextensionClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nodeManagerClientset, nil, err\n\t}\n\n\tglog.Infof(\"Created Kubernetes client %s\", config.Host)\n\n\treturn client, nodeManagerClientset, apiExtensionClient, err\n}", "func New() (kubernetes.Interface, error) {\n\tcs, err := getClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func (c *ConfigManager) GetLocalConfig(component, componentID string) *LocalConfig {\n\tc.RLock()\n\tdefer c.RUnlock()\n\tif lcs, ok := c.LocalCfgs[component]; ok {\n\t\tif lc, ok := lcs[componentID]; ok {\n\t\t\treturn lc\n\t\t}\n\t}\n\treturn nil\n}", "func getKubeClient(context string) (*rest.Config, kubernetes.Interface, error) {\n\tconfig, err := getK8sConfig(context).ClientConfig()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not get Kubernetes config for context %q: %s\", context, err)\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not get Kubernetes client: %s\", err)\n\t}\n\treturn config, client, nil\n}", "func Client() (*kubernetes.Clientset, error) {\n\n\t// manually use ~/.kube/config for now\n\tkubeConfigFilePath := filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")\n\t// fmt.Println(kubeConfigFilePath)\n\tfmt.Printf(\"\\n\\nKubeConfig Path: %s\\n\\n\", kubeConfigFilePath)\n\n\tkubeConfigFile, err := ioutil.ReadFile(kubeConfigFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientSet, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientSet, err\n\n}", "func determineConfig() (*rest.Config, error) {\n\tkubeconfigPath := os.Getenv(\"KUBECONFIG\")\n\tvar config *rest.Config\n\tvar err error\n\n\t// determine whether to use in cluster config or out of cluster config\n\t// if kubeconfigPath is not specified, default to in cluster config\n\t// otherwise, use out of cluster config\n\tif kubeconfigPath == \"\" {\n\t\tlog.Info(\"Using in cluster k8s config\")\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tlog.Info(\"Using out of cluster k8s config: \", kubeconfigPath)\n\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"determine Kubernetes config failed\")\n\t}\n\n\treturn config, nil\n}", "func GetClientConfig(kubeConfig string) (*rest.Config, error) {\n\tif kubeConfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeConfig)\n\t}\n\treturn rest.InClusterConfig()\n\n}", "func GetClientToK8s() (*K8sClient, error) {\n\tvar kubeconfig string\n\tif kubeConfigPath := os.Getenv(\"KUBECONFIG\"); kubeConfigPath != \"\" {\n\t\tkubeconfig = kubeConfigPath // CI process\n\t} else {\n\t\tkubeconfig = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\") // Development environment\n\t}\n\n\tvar config *rest.Config\n\n\t_, err := os.Stat(kubeconfig)\n\tif err != nil {\n\t\t// In cluster configuration\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// Out of cluster configuration\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar client = &K8sClient{ClientSet: clientset, Config: config}\n\treturn client, nil\n}", "func getKubeClient(kubeConfig, kubeContext string) (*rest.Config, *clientset.Clientset, error) {\n\tconfig, err := configForContext(kubeConfig, kubeContext)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not load Kubernetes configuration (%s)\", err)\n\t}\n\n\tclient, err := clientset.NewForConfig(config)\n\treturn nil, client, err\n}", "func GetKubernetesClient(logger logrus.FieldLogger, config *viper.Viper, inCluster bool, kubeConfigPath string) (kubernetes.Interface, metricsClient.Interface, error) {\n\tvar err error\n\tl := logger.WithFields(logrus.Fields{\n\t\t\"operation\": \"configureKubernetesClient\",\n\t})\n\tvar conf *rest.Config\n\tif inCluster {\n\t\tl.Debug(\"starting with incluster configuration\")\n\t\tconf, err = rest.InClusterConfig()\n\t} else {\n\t\tl.Debug(\"starting outside Kubernetes cluster\")\n\t\tconf, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigPath)\n\t}\n\tconf.Timeout = config.GetDuration(\"extensions.kubernetesClient.timeout\")\n\tconf.RateLimiter = nil\n\tconf.Burst = config.GetInt(\"extensions.kubernetesClient.burst\")\n\tconf.QPS = float32(config.GetInt(\"extensions.kubernetesClient.qps\"))\n\tif err != nil {\n\t\tl.WithError(err).Error(\"start Kubernetes failed\")\n\t\treturn nil, nil, err\n\t}\n\tl.Debug(\"connecting to Kubernetes...\")\n\tclientset, err := kubernetesExtensions.NewForConfig(conf)\n\tif err != nil {\n\t\tl.WithError(err).Error(\"connection to Kubernetes failed\")\n\t\treturn nil, nil, err\n\t}\n\tmetricsClientset, err := metricsClient.NewForConfig(conf)\n\tif err != nil {\n\t\tl.WithError(err).Error(\"connection to Kubernetes Metrics Server failed\")\n\t\treturn nil, nil, err\n\t}\n\n\tl.Info(\"successfully connected to Kubernetes\")\n\treturn clientset, metricsClientset, nil\n}", "func (wrapper *clusterWorkflowTemplateInterfaceWrapper) Get(name string) (*wfv1.ClusterWorkflowTemplate, error) {\n\treturn wrapper.clientset.Get(name, metav1.GetOptions{})\n}", "func (l *RemoteProvider) GetKubeClient() *mesherykube.Client {\n\treturn l.KubeClient\n}", "func newKubeClientConfig() (*client.Config, error) {\n\tvar (\n\t\tconfig *client.Config\n\t\terr error\n\t\tapiServerURL string\n\t)\n\t// If the user specified --kube-apiserver-url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tapiServerURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif apiServerURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube-apiserver-url was provided.\n\t\tconfig = &client.Config{\n\t\t\tHost: apiServerURL,\n\t\t\tVersion: \"v1\",\n\t\t}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube-apiserver-url and --kubecfg-file\n\t\t// 2) just --kubecfg-file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &clientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = apiServerURL // might be \"\", but that is OK\n\t\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tglog.Infof(\"Using %s for kubernetes API server\", config.Host)\n\tglog.Infof(\"Using kubernetes API version %s\", config.Version)\n\n\treturn config, nil\n}", "func getKubeClient() (kubernetes.Interface, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeletKubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeClient, err := kubernetes.NewForConfig(restclient.AddUserAgent(config, programName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubeClient, nil\n}", "func getClient() *kubernetes.Clientset {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn clientset\n}", "func (kr *KRun) K8SClient(ctx context.Context) error {\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\terr := kr.initUsingKubeConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = kr.initInCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif kr.VendorInit != nil {\n\t\terr = kr.VendorInit(ctx, kr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif kr.Client != nil {\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"not found\")\n}", "func GetClient(config Config) (*client.Client, error) {\n\topts := []client.Option{\n\t\tclient.WithNamespace(config.GetNamespace()),\n\t\tclient.WithScope(config.GetScope()),\n\t}\n\tmember := config.GetMember()\n\thost := config.GetHost()\n\tif host != \"\" {\n\t\topts = append(opts, client.WithPeerHost(config.GetHost()))\n\t\topts = append(opts, client.WithPeerPort(config.GetPort()))\n\t\tfor _, s := range serviceRegistry.services {\n\t\t\tservice := func(service cluster.Service) func(peer.ID, *grpc.Server) {\n\t\t\t\treturn func(id peer.ID, server *grpc.Server) {\n\t\t\t\t\tservice(cluster.NodeID(id), server)\n\t\t\t\t}\n\t\t\t}(s)\n\t\t\topts = append(opts, client.WithPeerService(service))\n\t\t}\n\t}\n\tif member != \"\" {\n\t\topts = append(opts, client.WithMemberID(config.GetMember()))\n\t} else if host != \"\" {\n\t\topts = append(opts, client.WithMemberID(config.GetHost()))\n\t}\n\n\treturn client.New(config.GetController(), opts...)\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}", "func GetClientConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}", "func GetClientConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}", "func (c *Config) Client() klient.Client {\n\tif c.client != nil {\n\t\treturn c.client\n\t}\n\n\tclient, err := klient.NewWithKubeConfigFile(c.kubeconfig)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"envconfig: client failed: %w\", err).Error())\n\t}\n\tc.client = client\n\treturn c.client\n}", "func getClientInCluster() kubernetes.Interface {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlogger.Fatalf(\"Can not get kubernetes config: %v\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Can not create kubernetes client: %v\", err)\n\t}\n\n\treturn clientset\n}", "func GetClient(restConfig *restclient.Config) *kubernetes.Clientset {\n\tclientset, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn clientset\n}", "func GetKubernetesClient() (*K8s, error) {\n\tlogger := utils.GetK8sAPILogger()\n\tif !TRACE_API {\n\t\tlogger.SetLevel(utils.Info)\n\t}\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tlogger.Trace(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn &K8s{\n\t\tAPI: clientset,\n\t\tLogger: logger,\n\t}, nil\n}", "func (ctrl *AgentController) getDashboardConfigLocal() bool {\n\tif !ctrl.Connected() || !ctrl.ValidConfiguration() {\n\t\treturn false\n\t}\n\tc := ctrl.kubeClient\n\tdashConf := ctrl.agentConf.dashboard\n\tvar nodePortNo, masterIP string\n\tfound := false\n\t/*search for a LiqoDash Service of type NodePort*/\n\tservL, err := c.CoreV1().Services(dashConf.namespace).List(context.TODO(), metav1.ListOptions{\n\t\tLabelSelector: \"app=\" + dashConf.label,\n\t})\n\tif err != nil || len(servL.Items) < 1 {\n\t\treturn false\n\t}\n\tservice := servL.Items[0]\n\tif service.Spec.Type != corev1.ServiceTypeNodePort {\n\t\treturn false\n\t}\n\tports := service.Spec.Ports\n\tfor i := range ports {\n\t\tport := ports[i]\n\t\tif port.Name == \"https\" {\n\t\t\tnodePortNo = fmt.Sprint(port.NodePort)\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\t/*A valid port has been found.\n\tFor the local connection, the master node IP address will be used.*/\n\tif found {\n\t\tfound = false\n\t\tnodeL, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: masterNodeLabel,\n\t\t})\n\t\tif err == nil && len(nodeL.Items) > 0 {\n\t\t\tfor _, addr := range nodeL.Items[0].Status.Addresses {\n\t\t\t\tif addr.Type == corev1.NodeInternalIP {\n\t\t\t\t\tmasterIP = addr.Address\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif found {\n\t\t/*having found both address and port, it is possible to set\n\t\tthe two env vars*/\n\t\tif err = os.Setenv(EnvLiqoDashHost, fmt.Sprintf(\n\t\t\t\"https://%s\", masterIP)); err == nil {\n\t\t\tif err = os.Setenv(EnvLiqoDashPort, nodePortNo); err == nil {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func NewClient() (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tinCluster := os.Getenv(\"IN_CLUSTER\")\n\tif inCluster == \"true\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\thome := homedir.HomeDir()\n\t\tp := filepath.Join(home, \".kube\", \"config\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", p)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func getKubeConfig(configPath string, overrides clientcmd.ConfigOverrides) *rest.Config {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.ExplicitPath = configPath\n\tclientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, &overrides, os.Stdin)\n\n\trestConfig, err := clientConfig.ClientConfig()\n\tCheckError(err)\n\treturn restConfig\n}", "func (s stdClientProvider) Client(env string) (kubeClient, error) {\n\tif s.overrideClientProvider != nil {\n\t\treturn s.overrideClientProvider(env)\n\t}\n\topts, err := s.connectOpts(env)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"get client\")\n\t}\n\trem, err := s.config.Client(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rem, nil\n}", "func (c *Config) Client() (*KubeProviderClient, error) {\n\tif c.Endpoint == \"\" {\n\t\treturn nil, errors.New(\"endpoint is required\")\n\t}\n\tkubeProClient := &KubeProviderClient{}\n\tkubeConfig := &client.Config{\n\t\tHost: c.Endpoint,\n\t\tVersion: c.Version,\n\t}\n\n\tif len(c.User) > 0 {\n\t\tkubeConfig.Username = c.User\n\t}\n\n\tif len(c.Password) > 0 {\n\t\tkubeConfig.Password = c.Password\n\t}\n\n\tif len(c.Version) > 0 {\n\t\tkubeConfig.Version = c.Version\n\t} else {\n\t\tkubeConfig.Version = DefaultVersion\n\t}\n\n\tkubeProClient.Version = kubeConfig.Version\n\n\tif len(c.Namespace) > 0 {\n\t\tkubeProClient.Namespace = c.Namespace\n\t} else {\n\t\tkubeProClient.Namespace = DefaultNamespace\n\t}\n\n\tkubeProClient.KubeClient = client.NewOrDie(kubeConfig)\n\n\tlog.Printf(\"[INFO] Kubernetes Client configured with endpoint: '%s'\", c.Endpoint)\n\n\treturn kubeProClient, nil\n}", "func GetKubeClient(configPath string) (client *kubernetes.Clientset, config *rest.Config, err error) {\n\tif configPath == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", configPath)\n\t}\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\n\tclient, err = kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, trace.Wrap(err)\n\t}\n\treturn client, config, nil\n}", "func NewClient(inClusterConfig bool, kubeconfig string) (kubernetes.Interface, error) {\n\tvar k8sconfig *rest.Config\n\tif inClusterConfig {\n\t\tvar err error\n\t\tk8sconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"kubeconfig in-cluster configuration error. %+v\", err)\n\t\t}\n\t} else {\n\t\tvar kubeconfig string\n\t\t// Try to fallback to the `KUBECONFIG` env var\n\t\tif kubeconfig == \"\" {\n\t\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t\t}\n\t\t// If the `KUBECONFIG` is empty, default to home dir default kube config path\n\t\tif kubeconfig == \"\" {\n\t\t\thome, err := homedir.Dir()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"kubeconfig unable to get home dir. %+v\", err)\n\t\t\t}\n\t\t\tkubeconfig = filepath.Join(home, \".kube\", \"config\")\n\t\t}\n\t\tvar err error\n\t\t// This will simply use the current context in the kubeconfig\n\t\tk8sconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"kubeconfig out-of-cluster configuration (%s) error. %+v\", kubeconfig, err)\n\t\t}\n\t}\n\n\t// Create the clientset\n\tclientset, err := kubernetes.NewForConfig(k8sconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kubernetes new client error. %+v\", err)\n\t}\n\treturn clientset, nil\n}", "func getKubernetesClient() (*kubernetes.Clientset, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func KubeConfig() (*rest.Config, error) {\n\tlocation := os.Getenv(\"KUBECONFIG\")\n\tif location == \"\" {\n\t\tlocation = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")\n\t}\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", location)\n\tif err != nil {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn config, nil\n}", "func getLocalClient() *redis.Client {\n\treturn redis.NewClient(&redis.Options{\n\t\tAddr: constants.Env.RedisURL,\n\t\tOnConnect: func(conn *redis.Conn) error {\n\t\t\tlogger.Info(\"Redis\", \"successfully connected to redis.\", nil)\n\t\t\treturn nil\n\t\t},\n\t\tMaxRetries: maxRetries,\n\t\tMaxRetryBackoff: maxRetryBackOff,\n\t})\n}", "func GetKubeConfig(clusterName string, region string) (*rest.Config, error) {\n\tif clusterName == \"\" {\n\t\terr := errors.New(\"Cluster name is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\tif region == \"\" {\n\t\terr := errors.New(\"Region is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\ts, err := session.NewSession(&aws.Config{Region: aws.String(region)})\n\tsvc := eks.New(s)\n\tinput := &eks.DescribeClusterInput{\n\t\tName: aws.String(clusterName),\n\t}\n\n\tclusterInfo, err := svc.DescribeCluster(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tlog.Error().Err(aerr).Str(\"code\", aerr.Code()).Msg(\"Failed to describe cluster\")\n\t\t} else {\n\t\t\tlog.Error().Err(err).Msg(\"Failed to describe cluster\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tca, err := base64.StdEncoding.DecodeString(*clusterInfo.Cluster.CertificateAuthority.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgen, err := token.NewGenerator(false, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttkn, err := gen.Get(*clusterInfo.Cluster.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rest.Config{\n\t\tHost: *clusterInfo.Cluster.Endpoint,\n\t\tBearerToken: tkn.Token,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tCAData: ca,\n\t\t},\n\t}, nil\n}", "func loadConfig() (*rest.Config, error) {\n\tif len(os.Getenv(\"KUBECONFIG\")) > 0 {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", os.Getenv(\"KUBECONFIG\"))\n\t}\n\tif c, err := rest.InClusterConfig(); err == nil {\n\t\treturn c, nil\n\t}\n\tif usr, err := user.Current(); err == nil {\n\t\tif c, err := clientcmd.BuildConfigFromFlags(\n\t\t\t\"\", filepath.Join(usr.HomeDir, \".kube\", \"config\")); err == nil {\n\t\t\treturn c, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not locate a kubeconfig\")\n}", "func newKubeClient() kubernetes.Interface {\n\tvar kubeconfig string\n\tif _, err := os.Stat(clientcmd.RecommendedHomeFile); err == nil {\n\t\tkubeconfig = clientcmd.RecommendedHomeFile\n\t}\n\tlog.Debugf(\"use config file %s\", kubeconfig)\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"build config failed: %v\", err)\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize kubernetes client failed: %v\", err)\n\t}\n\tlog.Infof(\"Connected to cluster at %s\", config.Host)\n\n\treturn client\n}", "func GetKubernetesConfig() (*k8srest.Config, error) {\n\thost := config.GetLearnerKubeURL()\n\tvar c *k8srest.Config\n\tvar err error\n\tif host == \"\" {\n\t\tc, err = k8srest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tc = &k8srest.Config{\n\t\t\tHost: host,\n\t\t\tTLSClientConfig: k8srest.TLSClientConfig{\n\t\t\t\tCAFile: config.GetLearnerKubeCAFile(),\n\t\t\t},\n\t\t}\n\t\ttoken := config.GetLearnerKubeToken()\n\t\tif token == \"\" {\n\t\t\ttokenFileContents := config.GetFileContents(config.GetLearnerKubeTokenFile())\n\t\t\tif tokenFileContents != \"\" {\n\t\t\t\ttoken = tokenFileContents\n\t\t\t}\n\t\t}\n\t\tif token == \"\" {\n\t\t\tc.TLSClientConfig.KeyFile = config.GetLearnerKubeKeyFile()\n\t\t\tc.TLSClientConfig.CertFile = config.GetLearnerKubeCertFile()\n\t\t} else {\n\t\t\tc.BearerToken = token\n\t\t}\n\t}\n\treturn c, nil\n}", "func getK8sAPIClient() *kubernetes.Clientset {\n\tconfig, err := getInClusterConfig()\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to use in-cluster configuration, will \"+\n\t\t\t\"attempt out-of-cluster authentication. Error: %v\", err.Error())\n\t\tconfig, err = getClusterConfig()\n\t\tif err != nil {\n\t\t\tlogrus.Fatalf(\"Failed to use the out-of-cluster \"+\n\t\t\t\t\"authentication too, error: %v\", err.Error())\n\t\t}\n\t}\n\n\t// Create the client object from in-cluster configuration\n\tlogrus.Debug(\"Creating the k8s client object\")\n\tclientset, err := kubernetes.NewForConfig(&config)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Failed to create the K8s client \"+\n\t\t\t\"authentication too, error: %v\", err.Error())\n\t}\n\treturn clientset\n}", "func getKubeConfig() (*rest.Config, error) {\n\t// Try to get in-cluster config first.\n\tconfig, err := rest.InClusterConfig()\n\tif err == nil {\n\t\treturn config, nil\n\t}\n\n\t// Try to get out-of-cluster config then, can be failed.\n\tconfigPath := os.Getenv(\"KUBECONFIG\")\n\tif configPath == \"\" {\n\t\tconfigPath = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")\n\t}\n\treturn clientcmd.BuildConfigFromFlags(\"\", configPath)\n}", "func Client() (*k8s.Clientset, error) {\n\tconfig, err := getConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn k8s.NewForConfig(config)\n}", "func (k *proxy) GetConfig() (*rest.Config, error) {\n\tconfig, err := k.configLoadingRules.Load()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load Kubeconfig\")\n\t}\n\n\tconfigOverrides := &clientcmd.ConfigOverrides{\n\t\tCurrentContext: k.kubeconfig.Context,\n\t\tTimeout: k.timeout.String(),\n\t}\n\trestConfig, err := clientcmd.NewDefaultClientConfig(*config, configOverrides).ClientConfig()\n\tif err != nil {\n\t\tif strings.HasPrefix(err.Error(), \"invalid configuration:\") {\n\t\t\treturn nil, errors.New(strings.Replace(err.Error(), \"invalid configuration:\", \"invalid kubeconfig file; clusterctl requires a valid kubeconfig file to connect to the management cluster:\", 1))\n\t\t}\n\t\treturn nil, err\n\t}\n\trestConfig.UserAgent = fmt.Sprintf(\"clusterctl/%s (%s)\", version.Get().GitVersion, version.Get().Platform)\n\n\t// Set QPS and Burst to a threshold that ensures the controller runtime client/client go doesn't generate throttling log messages\n\trestConfig.QPS = 20\n\trestConfig.Burst = 100\n\n\treturn restConfig, nil\n}", "func (p *Provider) GetConfigFile() (*kubernetes.Clientset, string, error) {\n\tsDec, err := base64.StdEncoding.DecodeString(p.Config)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"Error decoding k8 config: %s\", err)\n\t}\n\tconfigFile, err := ioutil.TempFile(\"\", \"k8-config\")\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"Error creating tmp file: %s\", err)\n\t}\n\terr = ioutil.WriteFile(configFile.Name(), sDec, 0400)\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error writing to tmp file: %s\", err)\n\t}\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", configFile.Name())\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error reading k8 config: %s\", err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error creating k8 client: %s\", err)\n\t}\n\treturn clientset, configFile.Name(), nil\n}", "func GetClientToK8s() (*kubernetes.Clientset, error) {\n\tvar kubeconfig string\n\tif kubeConfigPath := os.Getenv(\"KUBECONFIG\"); kubeConfigPath != \"\" {\n\t\tkubeconfig = kubeConfigPath // CI process\n\t} else {\n\t\tkubeconfig = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\") // Development environment\n\t}\n\n\tvar config *rest.Config\n\n\t_, err := os.Stat(kubeconfig)\n\tif err != nil {\n\t\t// In cluster configuration\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// Out of cluster configuration\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, nil\n}", "func Client() (*kubernetes.Clientset, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tconfig, err = getKubeConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset, nil\n}", "func IsLocalKubernetes(context string) bool {\n\treturn context == minikubeContext || context == dockerDesktopContext || context == dockerForDesktopContext\n}", "func GetKubeConfigClient() (*rest.Config, *k8s.Clientset, error) {\n\tconfig, err := getConfig()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclient, err := k8s.NewForConfig(config)\n\tif err != nil {\n\t\treturn config, nil, err\n\t}\n\treturn config, client, nil\n}", "func MustNewKubeClient() kubernetes.Interface {\n\tcfg, err := InClusterConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn kubernetes.NewForConfigOrDie(cfg)\n}", "func loadKubernetesConfig() (*rest.Config, error) {\n\tkubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\tclientcmd.NewDefaultClientConfigLoadingRules(),\n\t\t&clientcmd.ConfigOverrides{},\n\t)\n\n\tif cfg, err := kubeconfig.ClientConfig(); err == nil {\n\t\treturn cfg, nil\n\t}\n\n\treturn rest.InClusterConfig()\n}", "func initKubeConfig(kcLocation string) *rest.Config {\n\n\tif kcLocation != \"\" {\n\t\tkubeConfig, err := clientcmd.BuildConfigFromFlags(\"\", kcLocation)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"unable to build rest config based on provided path to kubeconfig file %s\", err.Error())\n\t\t}\n\t\treturn kubeConfig\n\t}\n\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tglog.Fatal(\"cannot find Service Account in pod to build in-cluster rest config\")\n\t}\n\n\treturn kubeConfig\n}", "func getClientSetOut() *kubernetes.Clientset {\n // Getting deploymentsClient object\n home := homedir.HomeDir();\n abspath := filepath.Join(home, \".kube\", \"config\")\n config, err := clientcmd.BuildConfigFromFlags(\"\", abspath)\n if err != nil {\n panic(err)\n }\n clientset, err := kubernetes.NewForConfig(config)\n if err != nil {\n panic(err)\n }\n\n return clientset\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func New(kubeconfig string) (*Instance, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\n\tif len(kubeconfig) > 0 {\n\t\tlogrus.Debugf(\"using kubeconfig: %s to create k8s client\", kubeconfig)\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tlogrus.Debugf(\"will use in-cluster config to create k8s client\")\n\t\tcfg, err = rest.InClusterConfig()\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Instance{\n\t\tkubeClient: kubeClient,\n\t\tk8sOps: core.Instance(),\n\t}, nil\n}", "func NewLocalClusterConfig() (*ClusterConfig, error) {\n\tclusterConfig := &ClusterConfig{}\n\n\tclusterConfig.OrgLabelName = os.Getenv(\"ORG_LABEL\")\n\tif clusterConfig.OrgLabelName == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing required ORG_LABEL environment variable\")\n\t}\n\n\tclusterConfig.AppLabelName = os.Getenv(\"APP_NAME_LABEL\")\n\tif clusterConfig.OrgLabelName == \"\" {\n\t\treturn nil, fmt.Errorf(\"Missing required APP_NAME_LABEL environment variable\")\n\t}\n\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\tconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\ttmpKubeConfig, err := config.ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load local kube config: %v\", err)\n\t}\n\n\t// creates the clientset\n\tclusterConfig.Client, err = kubernetes.NewForConfig(tmpKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clusterConfig, nil\n}", "func GetKubeConfig() (*rest.Config, error) {\n\tk8sconfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn k8sconfig, nil\n}", "func NewForConfig(config clientcmd.ClientConfig) (client *Client, err error) {\n\tif config == nil {\n\t\t// initialize client-go clients\n\t\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\t\tconfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\t}\n\n\tclient = new(Client)\n\tclient.KubeConfig = config\n\n\tclient.KubeClientConfig, err = client.KubeConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, errorMsg)\n\t}\n\n\tclient.KubeClient, err = kubernetes.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Namespace, _, err = client.KubeConfig.Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.OperatorClient, err = operatorsclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.DynamicClient, err = dynamic.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.appsClient, err = appsclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.serviceCatalogClient, err = servicecatalogclienset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.discoveryClient, err = discovery.NewDiscoveryClientForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.checkIngressSupports = true\n\n\tclient.userClient, err = userclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.projectClient, err = projectclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.routeClient, err = routeclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func NewClient(options ClientOptions) Client {\n\tgenericInfo := generic{\n\t\tappName: options.LocalConfigProvider.GetApplication(),\n\t\tcomponentName: options.LocalConfigProvider.GetName(),\n\t\tlocalConfig: options.LocalConfigProvider,\n\t}\n\n\tif _, ok := options.LocalConfigProvider.(*config.LocalConfigInfo); ok {\n\t\treturn s2iClient{\n\t\t\tgeneric: genericInfo,\n\t\t\tclient: options.OCClient,\n\t\t}\n\t} else {\n\t\treturn kubernetesClient{\n\t\t\tgeneric: genericInfo,\n\t\t\tisRouteSupported: options.IsRouteSupported,\n\t\t\tclient: options.OCClient,\n\t\t}\n\t}\n}", "func New(t time.Duration, inCluster bool) (*KubeAPI, error) {\n\tvar api KubeAPI\n\tapi.Timeout = t\n\tapi.InCluster = inCluster\n\tvar err error\n\n\tif api.InCluster {\n\t\tapi.Config, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn &api, err\n\t\t}\n\t} else {\n\t\tkubeconfig := filepath.Join(homeDir(), \".kube\", \"config\")\n\t\tapi.Config, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\n\tapi.Client, err = kubernetes.NewForConfig(api.Config)\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\treturn &api, nil\n}", "func (d *deployer) getAKSKubeconfig() error {\n\tklog.Infof(\"Retrieving AKS cluster's kubeconfig\")\n\tclient, err := armcontainerservicev2.NewManagedClustersClient(subscriptionID, cred, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to new managed cluster client with sub ID %q: %v\", subscriptionID, err)\n\t}\n\n\tvar resp armcontainerservicev2.ManagedClustersClientListClusterUserCredentialsResponse\n\terr = wait.PollImmediate(1*time.Minute, 20*time.Minute, func() (done bool, err error) {\n\t\tresp, err = client.ListClusterUserCredentials(ctx, d.ResourceGroupName, d.ClusterName, nil)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"404 Not Found\") {\n\t\t\t\tklog.Infof(\"failed to list cluster user credentials for 1 minute, retrying\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, fmt.Errorf(\"failed to list cluster user credentials with resource group name %q, cluster ID %q: %v\", d.ResourceGroupName, d.ClusterName, err)\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubeconfigs := resp.CredentialResults.Kubeconfigs\n\tif len(kubeconfigs) == 0 {\n\t\treturn fmt.Errorf(\"failed to find a valid kubeconfig\")\n\t}\n\tkubeconfig := kubeconfigs[0]\n\tdestPath := fmt.Sprintf(\"%s/%s_%s.kubeconfig\", defaultKubeconfigDir, d.ResourceGroupName, d.ClusterName)\n\n\tif err := os.MkdirAll(defaultKubeconfigDir, os.ModePerm); err != nil {\n\t\treturn fmt.Errorf(\"failed to mkdir the default kubeconfig dir: %v\", err)\n\t}\n\tif err := os.WriteFile(destPath, kubeconfig.Value, 0666); err != nil {\n\t\treturn fmt.Errorf(\"failed to write kubeconfig to %s\", destPath)\n\t}\n\n\tklog.Infof(\"Succeeded in getting kubeconfig of cluster %q in resource group %q\", d.ClusterName, d.ResourceGroupName)\n\treturn nil\n}", "func TestKUBECONFIGEnvVar(t *testing.T) {\n\tt.Run(\"CurrentNamespace\", func(t *testing.T) {\n\t\t// KUBECONFIG can specify multiple config files. We should be able to\n\t\t// get the correct namespace for the context by parsing through all\n\t\t// kubeconfig files\n\t\tvar (\n\t\t\tcontext = \"workload\"\n\t\t\tkubeconfigContents = kubeconfig(\"does-not-exist\", \"some-ns\")\n\t\t)\n\n\t\tg := NewWithT(t)\n\t\tdir, err := os.MkdirTemp(\"\", \"clusterctl\")\n\t\tg.Expect(err).ToNot(HaveOccurred())\n\t\tdefer os.RemoveAll(dir)\n\t\tconfigFile := filepath.Join(dir, \".test-kubeconfig.yaml\")\n\t\tg.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0600)).To(Succeed())\n\n\t\tproxy := newProxy(\n\t\t\t// dont't give an explicit path but rather define the file in the\n\t\t\t// configLoadingRules precedence chain.\n\t\t\tKubeconfig{Path: \"\", Context: context},\n\t\t\tInjectKubeconfigPaths([]string{configFile}),\n\t\t)\n\t\tactualNS, err := proxy.CurrentNamespace()\n\t\tg.Expect(err).ToNot(HaveOccurred())\n\t\tg.Expect(actualNS).To(Equal(\"some-ns\"))\n\t})\n\n\tt.Run(\"GetConfig\", func(t *testing.T) {\n\t\t// KUBECONFIG can specify multiple config files. We should be able to\n\t\t// get the valid cluster context by parsing all the kubeconfig files.\n\t\tvar (\n\t\t\tcontext = \"workload\"\n\t\t\t// TODO: If we change current context to \"do-not-exist\", we get an\n\t\t\t// error. See https://github.com/kubernetes/client-go/issues/797\n\t\t\tkubeconfigContents = kubeconfig(\"management\", \"default\")\n\t\t\texpectedHost = \"https://kind-server:38790\"\n\t\t)\n\t\tg := NewWithT(t)\n\t\tdir, err := os.MkdirTemp(\"\", \"clusterctl\")\n\t\tg.Expect(err).ToNot(HaveOccurred())\n\t\tdefer os.RemoveAll(dir)\n\t\tconfigFile := filepath.Join(dir, \".test-kubeconfig.yaml\")\n\t\tg.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0600)).To(Succeed())\n\n\t\tproxy := newProxy(\n\t\t\t// dont't give an explicit path but rather define the file in the\n\t\t\t// configLoadingRules precedence chain.\n\t\t\tKubeconfig{Path: \"\", Context: context},\n\t\t\tInjectKubeconfigPaths([]string{configFile}),\n\t\t)\n\t\tconf, err := proxy.GetConfig()\n\t\tg.Expect(err).ToNot(HaveOccurred())\n\t\tg.Expect(conf).ToNot(BeNil())\n\t\t// asserting on the host of the cluster associated with the\n\t\t// context\n\t\tg.Expect(conf.Host).To(Equal(expectedHost))\n\t})\n}", "func newConfigManagedClient(mgr manager.Manager) (runtimeclient.Client, manager.Runnable, error) {\n\tcacheOpts := cache.Options{\n\t\tScheme: mgr.GetScheme(),\n\t\tMapper: mgr.GetRESTMapper(),\n\t\tNamespace: alibabacloudClient.KubeCloudConfigNamespace,\n\t}\n\n\tc, err := cache.New(mgr.GetConfig(), cacheOpts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclientOpts := runtimeclient.Options{\n\t\tScheme: mgr.GetScheme(),\n\t\tMapper: mgr.GetRESTMapper(),\n\t}\n\n\tcachedClient, err := cluster.DefaultNewClient(c, config.GetConfigOrDie(), clientOpts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn cachedClient, c, nil\n}", "func NewClient(masterURL, kubeconfig string) (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tconfig, err = rest.InClusterConfig()\n\tif err != nil {\n\t\tzap.S().Info(\"could not perform incluster config. falling back to KUBECONFIG\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)\n\t}\n\tif err != nil {\n\t\tzap.S().Error(\"could not authenticate to cluster\\n\")\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func (client *Client) KubeClientFromConfig() (*Client, error) {\n\tvar err error\n\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\n\tclient.Kubeconfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\tloadingRules,\n\t\tconfigOverrides)\n\n\tclient.Restconfig, err = client.Kubeconfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Restclientset, err = kubernetes.NewForConfig(client.Restconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func GetKubernetesKubeConfig() string {\n\treturn strings.TrimSpace(os.Getenv(\"CYPRESS_PARALLEL_API_K8S_KUBE_CONFIG\"))\n}" ]
[ "0.68772894", "0.66571736", "0.62547773", "0.61836654", "0.61829954", "0.61155695", "0.60316384", "0.60062593", "0.60062593", "0.59447306", "0.59329385", "0.5907784", "0.5879774", "0.5855774", "0.584891", "0.58347267", "0.58099914", "0.5803037", "0.5790073", "0.57865363", "0.5778026", "0.5767875", "0.576419", "0.5758545", "0.57476526", "0.5735614", "0.57275355", "0.57190424", "0.57137096", "0.57106245", "0.56556803", "0.56527424", "0.564848", "0.5646778", "0.563536", "0.56349117", "0.56290054", "0.56226206", "0.5620203", "0.5616378", "0.56108665", "0.55908626", "0.55810094", "0.5570977", "0.5568113", "0.5565858", "0.5564388", "0.556079", "0.5554835", "0.5549362", "0.5547551", "0.554658", "0.5542144", "0.5535206", "0.5535206", "0.55341727", "0.5529998", "0.5528792", "0.55199564", "0.55093664", "0.5509068", "0.5502279", "0.54984975", "0.5487849", "0.5477134", "0.54750925", "0.5473289", "0.5468739", "0.5456302", "0.5455923", "0.54471034", "0.5446661", "0.54410505", "0.5409059", "0.54058176", "0.5397113", "0.53876984", "0.53861636", "0.53824204", "0.53821725", "0.5377605", "0.53589576", "0.53580135", "0.5332346", "0.53295046", "0.5317387", "0.5310904", "0.5305517", "0.53038883", "0.52973175", "0.529397", "0.5286366", "0.52732766", "0.52715683", "0.5267123", "0.5258607", "0.52579355", "0.5251474", "0.5244259", "0.5230889" ]
0.7412165
0
String returns the string representation
func (s CreateMembersInput) String() string { return awsutil.Prettify(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (s CreateQuickConnectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponse) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Addshifttraderequest) String() string {\n \n \n \n \n o.AcceptableIntervals = []string{\"\"} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (i Info) String() string {\n\ts, _ := i.toJSON()\n\treturn s\n}", "func (o *Botversionsummary) String() string {\n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (s CreateDataLakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSolutionVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Adjustablelivespeakerdetection) String() string {\n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateRateBasedRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (s RestoreFromRecoveryPointOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateWaveOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponseResult) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienia) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (i *Info) String() string {\n\tb, _ := json.Marshal(i)\n\treturn string(b)\n}", "func (s ProcessingFeatureStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ExportProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r RoomOccupancies) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Coretype) String() string {\n \n \n \n \n \n o.ValidationFields = []string{\"\"} \n \n o.ItemValidationFields = []string{\"\"} \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateLayerOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Limitchangerequestdetails) String() string {\n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s NetworkPathComponentDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t Terms) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (s StartContactEvaluationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Interactionstatsalert) String() string {\n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Digitalcondition) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (r RoomOccupancy) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (d *Diagram) String() string { return toString(d) }", "func (o *Outboundroute) String() string {\n \n \n \n \n o.ClassificationTypes = []string{\"\"} \n \n \n o.ExternalTrunkBases = []Domainentityref{{}} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (p *Parms) String() string {\n\tout, _ := json.MarshalIndent(p, \"\", \"\\t\")\n\treturn string(out)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RUT) String() string {\n\treturn r.Format(DefaultFormatter)\n}", "func (s CreatePatchBaselineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Crossplatformpolicycreate) String() string {\n \n \n \n \n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s BotVersionLocaleDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestInitiated) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteMultiplexProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestReverted) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDocumentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateIntegrationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Commonruleconditions) String() string {\n o.Clauses = []Commonruleconditions{{}} \n o.Predicates = []Commonrulepredicate{{}} \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (t Test1s) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (o *Directrouting) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (s CreateContactFlowOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.7215058", "0.7215058", "0.72000957", "0.7199919", "0.7177383", "0.7166947", "0.7118059", "0.7087492", "0.70870787", "0.7079275", "0.70782894", "0.7067719", "0.7031721", "0.70269966", "0.7026298", "0.70251423", "0.7021565", "0.70164025", "0.701059", "0.7010184", "0.70022964", "0.6997043", "0.6996532", "0.6992619", "0.69909185", "0.69900763", "0.69862556", "0.6985364", "0.6975378", "0.69738907", "0.69624275", "0.6961772", "0.69603413", "0.69507927", "0.6946753", "0.69460964", "0.69460964", "0.6944943", "0.694029", "0.69369334", "0.69332623", "0.69287163", "0.692656", "0.6924643", "0.69216746", "0.69213074", "0.69181406", "0.6917802", "0.6911058", "0.69104654", "0.6909528", "0.690845", "0.690454", "0.6899065", "0.6896141", "0.6894107", "0.6894107", "0.6894107", "0.68921995", "0.68920684", "0.689124", "0.68893504", "0.688871", "0.6884391", "0.6882336", "0.6880731", "0.68767136", "0.68766147", "0.68766147", "0.68751997", "0.68735147", "0.68734384", "0.68731403", "0.6871602", "0.6869421", "0.68684965", "0.68677104", "0.68677104", "0.68677104", "0.68677104", "0.68673396", "0.68622416", "0.6862084", "0.6859391", "0.6857645", "0.6853781", "0.68523467", "0.6851581", "0.6846037", "0.6844023", "0.6843859", "0.68434954", "0.68419206", "0.68416274", "0.684033", "0.6839815", "0.68363225", "0.6835165", "0.68334675", "0.68327725", "0.6832733" ]
0.0
-1
MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s CreateMembersInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/json"), protocol.Metadata{}) if s.AccountDetails != nil { v := s.AccountDetails metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "AccountDetails", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService9TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s OutputService6TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRestApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.ApiKeySource) > 0 {\n\t\tv := s.ApiKeySource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.BinaryMediaTypes != nil {\n\t\tv := s.BinaryMediaTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"binaryMediaTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EndpointConfiguration != nil {\n\t\tv := s.EndpointConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"endpointConfiguration\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MinimumCompressionSize != nil {\n\t\tv := *s.MinimumCompressionSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"minimumCompressionSize\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Policy != nil {\n\t\tv := *s.Policy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateCanaryInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ArtifactS3Location != nil {\n\t\tv := *s.ArtifactS3Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ArtifactS3Location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Code != nil {\n\t\tv := s.Code\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Code\", v, metadata)\n\t}\n\tif s.ExecutionRoleArn != nil {\n\t\tv := *s.ExecutionRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExecutionRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FailureRetentionPeriodInDays != nil {\n\t\tv := *s.FailureRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FailureRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RunConfig != nil {\n\t\tv := s.RunConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RunConfig\", v, metadata)\n\t}\n\tif s.RuntimeVersion != nil {\n\t\tv := *s.RuntimeVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RuntimeVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schedule != nil {\n\t\tv := s.Schedule\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Schedule\", v, metadata)\n\t}\n\tif s.SuccessRetentionPeriodInDays != nil {\n\t\tv := *s.SuccessRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"SuccessRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"Tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcConfig != nil {\n\t\tv := s.VpcConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"VpcConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewayRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAccessPointInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ClientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FileSystemId != nil {\n\t\tv := *s.FileSystemId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FileSystemId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PosixUser != nil {\n\t\tv := s.PosixUser\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PosixUser\", v, metadata)\n\t}\n\tif s.RootDirectory != nil {\n\t\tv := s.RootDirectory\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RootDirectory\", v, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CorsConfiguration != nil {\n\t\tv := s.CorsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"corsConfiguration\", v, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImportInfo != nil {\n\t\tv := s.ImportInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"importInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService15TestShapeItemDetailShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ID != nil {\n\t\tv := *s.ID\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ID\", protocol.StringValue(v), metadata)\n\t}\n\t// Skipping Type XML Attribute.\n\treturn nil\n}", "func (s CreateProxySessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Capabilities != nil {\n\t\tv := s.Capabilities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Capabilities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ExpiryMinutes != nil {\n\t\tv := *s.ExpiryMinutes\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExpiryMinutes\", protocol.Int64Value(v), metadata)\n\t}\n\tif len(s.GeoMatchLevel) > 0 {\n\t\tv := s.GeoMatchLevel\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GeoMatchLevel\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.GeoMatchParams != nil {\n\t\tv := s.GeoMatchParams\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"GeoMatchParams\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.NumberSelectionBehavior) > 0 {\n\t\tv := s.NumberSelectionBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"NumberSelectionBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.ParticipantPhoneNumbers != nil {\n\t\tv := s.ParticipantPhoneNumbers\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"ParticipantPhoneNumbers\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.VoiceConnectorId != nil {\n\t\tv := *s.VoiceConnectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"voiceConnectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewaySpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.KeyValue != nil {\n\t\tv := *s.KeyValue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"keyValue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateSignalingChannelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChannelARN != nil {\n\t\tv := *s.ChannelARN\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ChannelARN\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CurrentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SingleMasterConfiguration != nil {\n\t\tv := s.SingleMasterConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SingleMasterConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateThingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AttributePayload != nil {\n\t\tv := s.AttributePayload\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"attributePayload\", v, metadata)\n\t}\n\tif s.BillingGroupName != nil {\n\t\tv := *s.BillingGroupName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingGroupName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingTypeName != nil {\n\t\tv := *s.ThingTypeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"thingTypeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingName != nil {\n\t\tv := *s.ThingName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"thingName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func encodeSchema(w io.Writer, s *schema.Schema) (err error) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tew := errWriter{w: w}\n\tif s.Description != \"\" {\n\t\tew.writeFormat(`\"description\": %q, `, s.Description)\n\t}\n\tew.writeString(`\"type\": \"object\", `)\n\tew.writeString(`\"additionalProperties\": false, `)\n\tew.writeString(`\"properties\": {`)\n\tvar required []string\n\tvar notFirst bool\n\tfor _, key := range sortedFieldNames(s.Fields) {\n\t\tfield := s.Fields[key]\n\t\tif notFirst {\n\t\t\tew.writeString(\", \")\n\t\t}\n\t\tnotFirst = true\n\t\tif field.Required {\n\t\t\trequired = append(required, fmt.Sprintf(\"%q\", key))\n\t\t}\n\t\tew.err = encodeField(ew, key, field)\n\t\tif ew.err != nil {\n\t\t\treturn ew.err\n\t\t}\n\t}\n\tew.writeString(\"}\")\n\tif s.MinLen > 0 {\n\t\tew.writeFormat(`, \"minProperties\": %s`, strconv.FormatInt(int64(s.MinLen), 10))\n\t}\n\tif s.MaxLen > 0 {\n\t\tew.writeFormat(`, \"maxProperties\": %s`, strconv.FormatInt(int64(s.MaxLen), 10))\n\t}\n\n\tif len(required) > 0 {\n\t\tew.writeFormat(`, \"required\": [%s]`, strings.Join(required, \", \"))\n\t}\n\treturn ew.err\n}", "func (s OutputService15TestShapeItemShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ItemDetail != nil {\n\t\tv := s.ItemDetail\n\t\tattrs := make([]protocol.Attribute, 0, 1)\n\n\t\tif len(s.ItemDetail.Type) > 0 {\n\n\t\t\tv := s.ItemDetail.Type\n\t\t\tattrs = append(attrs, protocol.Attribute{Name: \"xsi:type\", Value: v, Meta: protocol.Metadata{}})\n\t\t}\n\t\tmetadata := protocol.Metadata{Attributes: attrs, XMLNamespacePrefix: \"xsi\", XMLNamespaceURI: \"http://www.w3.org/2001/XMLSchema-instance\"}\n\t\te.SetFields(protocol.BodyTarget, \"ItemDetail\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIPSetInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Activate != nil {\n\t\tv := *s.Activate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"activate\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Location != nil {\n\t\tv := *s.Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorId != nil {\n\t\tv := *s.DetectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IpSetId != nil {\n\t\tv := *s.IpSetId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"ipSetId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Robot) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.FleetArn != nil {\n\t\tv := *s.FleetArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"fleetArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.GreenGrassGroupId != nil {\n\t\tv := *s.GreenGrassGroupId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"greenGrassGroupId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentJob != nil {\n\t\tv := *s.LastDeploymentJob\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentJob\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentTime != nil {\n\t\tv := *s.LastDeploymentTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentTime\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Status) > 0 {\n\t\tv := s.Status\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"status\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAliasInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FunctionVersion != nil {\n\t\tv := *s.FunctionVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FunctionVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RoutingConfig != nil {\n\t\tv := s.RoutingConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RoutingConfig\", v, metadata)\n\t}\n\tif s.FunctionName != nil {\n\t\tv := *s.FunctionName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"FunctionName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeInputDeviceOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionState) > 0 {\n\t\tv := s.ConnectionState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.DeviceSettingsSyncState) > 0 {\n\t\tv := s.DeviceSettingsSyncState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deviceSettingsSyncState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.HdDeviceSettings != nil {\n\t\tv := s.HdDeviceSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"hdDeviceSettings\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MacAddress != nil {\n\t\tv := *s.MacAddress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"macAddress\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.NetworkSettings != nil {\n\t\tv := s.NetworkSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"networkSettings\", v, metadata)\n\t}\n\tif s.SerialNumber != nil {\n\t\tv := *s.SerialNumber\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"serialNumber\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateImageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DistributionConfigurationArn != nil {\n\t\tv := *s.DistributionConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"distributionConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnhancedImageMetadataEnabled != nil {\n\t\tv := *s.EnhancedImageMetadataEnabled\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enhancedImageMetadataEnabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImageRecipeArn != nil {\n\t\tv := *s.ImageRecipeArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"imageRecipeArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ImageTestsConfiguration != nil {\n\t\tv := s.ImageTestsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"imageTestsConfiguration\", v, metadata)\n\t}\n\tif s.InfrastructureConfigurationArn != nil {\n\t\tv := *s.InfrastructureConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"infrastructureConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s VpcLink) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SecurityGroupIds != nil {\n\t\tv := s.SecurityGroupIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"securityGroupIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.SubnetIds != nil {\n\t\tv := s.SubnetIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"subnetIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcLinkId != nil {\n\t\tv := *s.VpcLinkId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkStatus) > 0 {\n\t\tv := s.VpcLinkStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.VpcLinkStatusMessage != nil {\n\t\tv := *s.VpcLinkStatusMessage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatusMessage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkVersion) > 0 {\n\t\tv := s.VpcLinkVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkVersion\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.AuthorizationScopes != nil {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestModels != nil {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PayloadFormatVersion != nil {\n\t\tv := *s.PayloadFormatVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"payloadFormatVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestTemplates != nil {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.TlsConfig != nil {\n\t\tv := s.TlsConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"tlsConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateOTAUpdateInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Files != nil {\n\t\tv := s.Files\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"files\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiKeyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Expires != nil {\n\t\tv := *s.Expires\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"expires\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.BackendEnvironmentArn != nil {\n\t\tv := *s.BackendEnvironmentArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"backendEnvironmentArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnablePullRequestPreview != nil {\n\t\tv := *s.EnablePullRequestPreview\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enablePullRequestPreview\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnvironmentVariables != nil {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PullRequestEnvironmentName != nil {\n\t\tv := *s.PullRequestEnvironmentName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"pullRequestEnvironmentName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseId != nil {\n\t\tv := *s.RouteResponseId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeResponseId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePackageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PackageDescription != nil {\n\t\tv := *s.PackageDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageName != nil {\n\t\tv := *s.PackageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageSource != nil {\n\t\tv := s.PackageSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PackageSource\", v, metadata)\n\t}\n\tif len(s.PackageType) > 0 {\n\t\tv := s.PackageType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdatePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (s OutputService11TestShapeOutputService11TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-false-bool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Integer != nil {\n\t\tv := *s.Integer\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-int\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.RFC822TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-true-bool\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OauthToken != nil {\n\t\tv := *s.OauthToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"oauthToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Repository != nil {\n\t\tv := *s.Repository\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"repository\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualNodeSpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Backends != nil {\n\t\tv := s.Backends\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"backends\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\tif s.ServiceDiscovery != nil {\n\t\tv := s.ServiceDiscovery\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"serviceDiscovery\", v, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s NetworkPathComponent) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ComponentId != nil {\n\t\tv := *s.ComponentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ComponentType != nil {\n\t\tv := *s.ComponentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Egress != nil {\n\t\tv := s.Egress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Egress\", v, metadata)\n\t}\n\tif s.Ingress != nil {\n\t\tv := s.Ingress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Ingress\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService13TestShapeTimeContainer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Bar != nil {\n\t\tv := *s.Bar\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"bar\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"unixTimestamp\", QuotedFormatTime: false}, metadata)\n\t}\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\treturn nil\n}", "func (s ImportComponentInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChangeDescription != nil {\n\t\tv := *s.ChangeDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"changeDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Data != nil {\n\t\tv := *s.Data\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"data\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.KmsKeyId != nil {\n\t\tv := *s.KmsKeyId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"kmsKeyId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.SemanticVersion != nil {\n\t\tv := *s.SemanticVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"semanticVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Uri != nil {\n\t\tv := *s.Uri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"uri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CodeReview) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CodeReviewArn != nil {\n\t\tv := *s.CodeReviewArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeReviewArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedTimeStamp != nil {\n\t\tv := *s.CreatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CreatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedTimeStamp != nil {\n\t\tv := *s.LastUpdatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"LastUpdatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Metrics != nil {\n\t\tv := s.Metrics\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Metrics\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Owner != nil {\n\t\tv := *s.Owner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Owner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProviderType) > 0 {\n\t\tv := s.ProviderType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProviderType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PullRequestId != nil {\n\t\tv := *s.PullRequestId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PullRequestId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RepositoryName != nil {\n\t\tv := *s.RepositoryName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RepositoryName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SourceCodeType != nil {\n\t\tv := s.SourceCodeType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SourceCodeType\", v, metadata)\n\t}\n\tif len(s.State) > 0 {\n\t\tv := s.State\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"State\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.StateReason != nil {\n\t\tv := *s.StateReason\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StateReason\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s PutObjectOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentSHA256 != nil {\n\t\tv := *s.ContentSHA256\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ContentSHA256\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ETag != nil {\n\t\tv := *s.ETag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ETag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StorageClass) > 0 {\n\t\tv := s.StorageClass\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StorageClass\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s GetRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation2Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceBackend) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ClientPolicy != nil {\n\t\tv := s.ClientPolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"clientPolicy\", v, metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PolicyDocument != nil {\n\t\tv := *s.PolicyDocument\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policyDocument\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBucketInput) MarshalFields(e protocol.FieldEncoder) error {\n\n\tif len(s.ACL) > 0 {\n\t\tv := s.ACL\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-acl\", v, metadata)\n\t}\n\tif s.GrantFullControl != nil {\n\t\tv := *s.GrantFullControl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-full-control\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantRead != nil {\n\t\tv := *s.GrantRead\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantReadACP != nil {\n\t\tv := *s.GrantReadACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWrite != nil {\n\t\tv := *s.GrantWrite\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWriteACP != nil {\n\t\tv := *s.GrantWriteACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ObjectLockEnabledForBucket != nil {\n\t\tv := *s.ObjectLockEnabledForBucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-bucket-object-lock-enabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Bucket != nil {\n\t\tv := *s.Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"Bucket\", protocol.StringValue(v), metadata)\n\t}\n\tif s.CreateBucketConfiguration != nil {\n\t\tv := s.CreateBucketConfiguration\n\n\t\tmetadata := protocol.Metadata{XMLNamespaceURI: \"http://s3.amazonaws.com/doc/2006-03-01/\"}\n\t\te.SetFields(protocol.PayloadTarget, \"CreateBucketConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Pipeline) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Activities) > 0 {\n\t\tv := s.Activities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"activities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreationTime != nil {\n\t\tv := *s.CreationTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.LastUpdateTime != nil {\n\t\tv := *s.LastUpdateTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdateTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ReprocessingSummaries) > 0 {\n\t\tv := s.ReprocessingSummaries\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"reprocessingSummaries\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s VirtualNodeRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualNodeName != nil {\n\t\tv := *s.VirtualNodeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualNodeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetIntrospectionSchemaInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IncludeDirectives != nil {\n\t\tv := *s.IncludeDirectives\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"includeDirectives\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s Source) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Etag != nil {\n\t\tv := *s.Etag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"etag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Bucket != nil {\n\t\tv := *s.S3Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Bucket\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Key != nil {\n\t\tv := *s.S3Key\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Key\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OTAUpdateInfo) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsIotJobArn != nil {\n\t\tv := *s.AwsIotJobArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsIotJobId != nil {\n\t\tv := *s.AwsIotJobId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.CreationDate != nil {\n\t\tv := *s.CreationDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ErrorInfo != nil {\n\t\tv := s.ErrorInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"errorInfo\", v, metadata)\n\t}\n\tif s.LastModifiedDate != nil {\n\t\tv := *s.LastModifiedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastModifiedDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.OtaUpdateArn != nil {\n\t\tv := *s.OtaUpdateArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OtaUpdateFiles != nil {\n\t\tv := s.OtaUpdateFiles\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"otaUpdateFiles\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.OtaUpdateStatus) > 0 {\n\t\tv := s.OtaUpdateStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateModelOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateJobInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.HopDestinations != nil {\n\t\tv := s.HopDestinations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"hopDestinations\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\t}\n\tif s.AccelerationSettings != nil {\n\t\tv := s.AccelerationSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accelerationSettings\", v, metadata)\n\t}\n\tif len(s.BillingTagsSource) > 0 {\n\t\tv := s.BillingTagsSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingTagsSource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tvar ClientRequestToken string\n\tif s.ClientRequestToken != nil {\n\t\tClientRequestToken = *s.ClientRequestToken\n\t} else {\n\t\tClientRequestToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientRequestToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientRequestToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.JobTemplate != nil {\n\t\tv := *s.JobTemplate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"jobTemplate\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Priority != nil {\n\t\tv := *s.Priority\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"priority\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Queue != nil {\n\t\tv := *s.Queue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"queue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Role != nil {\n\t\tv := *s.Role\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"role\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Settings != nil {\n\t\tv := s.Settings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"settings\", v, metadata)\n\t}\n\tif len(s.SimulateReservedQueue) > 0 {\n\t\tv := s.SimulateReservedQueue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"simulateReservedQueue\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.StatusUpdateInterval) > 0 {\n\t\tv := s.StatusUpdateInterval\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"statusUpdateInterval\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.UserMetadata != nil {\n\t\tv := s.UserMetadata\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"userMetadata\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateBrokerStorageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"currentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TargetBrokerEBSVolumeInfo != nil {\n\t\tv := s.TargetBrokerEBSVolumeInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targetBrokerEBSVolumeInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ClusterArn != nil {\n\t\tv := *s.ClusterArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"clusterArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CustomCodeSigning) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CertificateChain != nil {\n\t\tv := s.CertificateChain\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"certificateChain\", v, metadata)\n\t}\n\tif s.HashAlgorithm != nil {\n\t\tv := *s.HashAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"hashAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Signature != nil {\n\t\tv := s.Signature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signature\", v, metadata)\n\t}\n\tif s.SignatureAlgorithm != nil {\n\t\tv := *s.SignatureAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"signatureAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetMacieSessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\treturn nil\n}", "func (s MeshRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s Resource) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Attributes) > 0 {\n\t\tv := s.Attributes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"attributes\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Feature != nil {\n\t\tv := *s.Feature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"feature\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Type != nil {\n\t\tv := *s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GatewayRouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.GatewayRouteName != nil {\n\t\tv := *s.GatewayRouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"gatewayRouteName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s RouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteName != nil {\n\t\tv := *s.RouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualRouterName != nil {\n\t\tv := *s.VirtualRouterName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualRouterName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorModelVersion != nil {\n\t\tv := *s.DetectorModelVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AttachPolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Category) > 0 {\n\t\tv := s.Category\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"category\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MaxSizeInMB != nil {\n\t\tv := *s.MaxSizeInMB\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"maxSizeInMB\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Partner != nil {\n\t\tv := *s.Partner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"partner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SigningConfiguration != nil {\n\t\tv := s.SigningConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingConfiguration\", v, metadata)\n\t}\n\tif s.SigningImageFormat != nil {\n\t\tv := s.SigningImageFormat\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingImageFormat\", v, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (v *Service) Encode(sw stream.Writer) error {\n\tif err := sw.WriteStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 7, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 1, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.ThriftName); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.ParentID != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 4, Type: wire.TI32}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := v.ParentID.Encode(sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 5, Type: wire.TList}); err != nil {\n\t\treturn err\n\t}\n\tif err := _List_Function_Encode(v.Functions, sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 6, Type: wire.TI32}); err != nil {\n\t\treturn err\n\t}\n\tif err := v.ModuleID.Encode(sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.Annotations != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 8, Type: wire.TMap}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := _Map_String_String_Encode(v.Annotations, sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn sw.WriteStructEnd()\n}", "func (s Product) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ActivationUrl != nil {\n\t\tv := *s.ActivationUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ActivationUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Categories != nil {\n\t\tv := s.Categories\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Categories\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CompanyName != nil {\n\t\tv := *s.CompanyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CompanyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationTypes != nil {\n\t\tv := s.IntegrationTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"IntegrationTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.MarketplaceUrl != nil {\n\t\tv := *s.MarketplaceUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"MarketplaceUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductArn != nil {\n\t\tv := *s.ProductArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductName != nil {\n\t\tv := *s.ProductName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductSubscriptionResourcePolicy != nil {\n\t\tv := *s.ProductSubscriptionResourcePolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductSubscriptionResourcePolicy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AwsLambdaFunctionLayer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CodeSize != nil {\n\t\tv := *s.CodeSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeSize\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s HttpAuthorization) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Sigv4 != nil {\n\t\tv := s.Sigv4\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"sigv4\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PipelineName != nil {\n\t\tv := *s.PipelineName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"pipelineName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}" ]
[ "0.63479704", "0.6247795", "0.6195172", "0.61806905", "0.61683095", "0.61200184", "0.6099719", "0.6069325", "0.6064495", "0.60124534", "0.6009836", "0.59606516", "0.59526104", "0.5935234", "0.5928707", "0.59224474", "0.5910614", "0.59063023", "0.58990103", "0.5884719", "0.58780664", "0.58758223", "0.58740026", "0.5870821", "0.58704156", "0.58583754", "0.5851065", "0.5847724", "0.584571", "0.5837251", "0.583382", "0.5820691", "0.5819901", "0.58150333", "0.5815032", "0.58111376", "0.5804827", "0.5802364", "0.5802092", "0.578717", "0.5780785", "0.57765293", "0.5774867", "0.5773512", "0.57650334", "0.5761848", "0.5759235", "0.5758919", "0.5750916", "0.5749155", "0.5746686", "0.574606", "0.5741942", "0.5740067", "0.57334137", "0.57329136", "0.57288283", "0.5720536", "0.57199717", "0.5709697", "0.57026315", "0.57025653", "0.57011104", "0.56961375", "0.5694661", "0.569277", "0.56852376", "0.568256", "0.5678673", "0.56765914", "0.5675795", "0.56648564", "0.5661323", "0.5660928", "0.56593114", "0.5657954", "0.56536096", "0.565022", "0.5645035", "0.56447184", "0.56441903", "0.56391424", "0.56385344", "0.56368303", "0.5635701", "0.5635248", "0.56317043", "0.5625839", "0.5625511", "0.56232154", "0.56216896", "0.56216896", "0.56204224", "0.5616888", "0.56134516", "0.5612859", "0.56120634", "0.56104606", "0.56095034", "0.56052333", "0.5590397" ]
0.0
-1
String returns the string representation
func (s CreateMembersOutput) String() string { return awsutil.Prettify(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (s CreateQuickConnectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponse) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Addshifttraderequest) String() string {\n \n \n \n \n o.AcceptableIntervals = []string{\"\"} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (i Info) String() string {\n\ts, _ := i.toJSON()\n\treturn s\n}", "func (o *Botversionsummary) String() string {\n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (s CreateDataLakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSolutionVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Adjustablelivespeakerdetection) String() string {\n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateRateBasedRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (s RestoreFromRecoveryPointOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateWaveOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponseResult) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienia) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (i *Info) String() string {\n\tb, _ := json.Marshal(i)\n\treturn string(b)\n}", "func (s ProcessingFeatureStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ExportProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r RoomOccupancies) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Coretype) String() string {\n \n \n \n \n \n o.ValidationFields = []string{\"\"} \n \n o.ItemValidationFields = []string{\"\"} \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateLayerOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Limitchangerequestdetails) String() string {\n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s NetworkPathComponentDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t Terms) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (s StartContactEvaluationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Interactionstatsalert) String() string {\n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Digitalcondition) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (r RoomOccupancy) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (d *Diagram) String() string { return toString(d) }", "func (o *Outboundroute) String() string {\n \n \n \n \n o.ClassificationTypes = []string{\"\"} \n \n \n o.ExternalTrunkBases = []Domainentityref{{}} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (p *Parms) String() string {\n\tout, _ := json.MarshalIndent(p, \"\", \"\\t\")\n\treturn string(out)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RUT) String() string {\n\treturn r.Format(DefaultFormatter)\n}", "func (s CreatePatchBaselineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Crossplatformpolicycreate) String() string {\n \n \n \n \n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s BotVersionLocaleDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestInitiated) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteMultiplexProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestReverted) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDocumentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateIntegrationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Commonruleconditions) String() string {\n o.Clauses = []Commonruleconditions{{}} \n o.Predicates = []Commonrulepredicate{{}} \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (t Test1s) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (o *Directrouting) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (s CreateContactFlowOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.7215058", "0.7215058", "0.72000957", "0.7199919", "0.7177383", "0.7166947", "0.7118059", "0.7087492", "0.70870787", "0.7079275", "0.70782894", "0.7067719", "0.7031721", "0.70269966", "0.7026298", "0.70251423", "0.7021565", "0.70164025", "0.701059", "0.7010184", "0.70022964", "0.6997043", "0.6996532", "0.6992619", "0.69909185", "0.69900763", "0.69862556", "0.6985364", "0.6975378", "0.69738907", "0.69624275", "0.6961772", "0.69603413", "0.69507927", "0.6946753", "0.69460964", "0.69460964", "0.6944943", "0.694029", "0.69369334", "0.69332623", "0.69287163", "0.692656", "0.6924643", "0.69216746", "0.69213074", "0.69181406", "0.6917802", "0.6911058", "0.69104654", "0.6909528", "0.690845", "0.690454", "0.6899065", "0.6896141", "0.6894107", "0.6894107", "0.6894107", "0.68921995", "0.68920684", "0.689124", "0.68893504", "0.688871", "0.6884391", "0.6882336", "0.6880731", "0.68767136", "0.68766147", "0.68766147", "0.68751997", "0.68735147", "0.68734384", "0.68731403", "0.6871602", "0.6869421", "0.68684965", "0.68677104", "0.68677104", "0.68677104", "0.68677104", "0.68673396", "0.68622416", "0.6862084", "0.6859391", "0.6857645", "0.6853781", "0.68523467", "0.6851581", "0.6846037", "0.6844023", "0.6843859", "0.68434954", "0.68419206", "0.68416274", "0.684033", "0.6839815", "0.68363225", "0.6835165", "0.68334675", "0.68327725", "0.6832733" ]
0.0
-1
MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s CreateMembersOutput) MarshalFields(e protocol.FieldEncoder) error { if s.UnprocessedAccounts != nil { v := s.UnprocessedAccounts metadata := protocol.Metadata{} ls0 := e.List(protocol.BodyTarget, "UnprocessedAccounts", metadata) ls0.Start() for _, v1 := range v { ls0.ListAddFields(v1) } ls0.End() } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService9TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s OutputService6TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRestApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.ApiKeySource) > 0 {\n\t\tv := s.ApiKeySource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.BinaryMediaTypes != nil {\n\t\tv := s.BinaryMediaTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"binaryMediaTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EndpointConfiguration != nil {\n\t\tv := s.EndpointConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"endpointConfiguration\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MinimumCompressionSize != nil {\n\t\tv := *s.MinimumCompressionSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"minimumCompressionSize\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Policy != nil {\n\t\tv := *s.Policy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateCanaryInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ArtifactS3Location != nil {\n\t\tv := *s.ArtifactS3Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ArtifactS3Location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Code != nil {\n\t\tv := s.Code\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Code\", v, metadata)\n\t}\n\tif s.ExecutionRoleArn != nil {\n\t\tv := *s.ExecutionRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExecutionRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FailureRetentionPeriodInDays != nil {\n\t\tv := *s.FailureRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FailureRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RunConfig != nil {\n\t\tv := s.RunConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RunConfig\", v, metadata)\n\t}\n\tif s.RuntimeVersion != nil {\n\t\tv := *s.RuntimeVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RuntimeVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schedule != nil {\n\t\tv := s.Schedule\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Schedule\", v, metadata)\n\t}\n\tif s.SuccessRetentionPeriodInDays != nil {\n\t\tv := *s.SuccessRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"SuccessRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"Tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcConfig != nil {\n\t\tv := s.VpcConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"VpcConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewayRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAccessPointInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ClientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FileSystemId != nil {\n\t\tv := *s.FileSystemId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FileSystemId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PosixUser != nil {\n\t\tv := s.PosixUser\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PosixUser\", v, metadata)\n\t}\n\tif s.RootDirectory != nil {\n\t\tv := s.RootDirectory\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RootDirectory\", v, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CorsConfiguration != nil {\n\t\tv := s.CorsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"corsConfiguration\", v, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImportInfo != nil {\n\t\tv := s.ImportInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"importInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService15TestShapeItemDetailShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ID != nil {\n\t\tv := *s.ID\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ID\", protocol.StringValue(v), metadata)\n\t}\n\t// Skipping Type XML Attribute.\n\treturn nil\n}", "func (s CreateProxySessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Capabilities != nil {\n\t\tv := s.Capabilities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Capabilities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ExpiryMinutes != nil {\n\t\tv := *s.ExpiryMinutes\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExpiryMinutes\", protocol.Int64Value(v), metadata)\n\t}\n\tif len(s.GeoMatchLevel) > 0 {\n\t\tv := s.GeoMatchLevel\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GeoMatchLevel\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.GeoMatchParams != nil {\n\t\tv := s.GeoMatchParams\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"GeoMatchParams\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.NumberSelectionBehavior) > 0 {\n\t\tv := s.NumberSelectionBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"NumberSelectionBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.ParticipantPhoneNumbers != nil {\n\t\tv := s.ParticipantPhoneNumbers\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"ParticipantPhoneNumbers\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.VoiceConnectorId != nil {\n\t\tv := *s.VoiceConnectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"voiceConnectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewaySpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s UpdateSignalingChannelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChannelARN != nil {\n\t\tv := *s.ChannelARN\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ChannelARN\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CurrentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SingleMasterConfiguration != nil {\n\t\tv := s.SingleMasterConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SingleMasterConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.KeyValue != nil {\n\t\tv := *s.KeyValue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"keyValue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateThingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AttributePayload != nil {\n\t\tv := s.AttributePayload\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"attributePayload\", v, metadata)\n\t}\n\tif s.BillingGroupName != nil {\n\t\tv := *s.BillingGroupName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingGroupName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingTypeName != nil {\n\t\tv := *s.ThingTypeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"thingTypeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingName != nil {\n\t\tv := *s.ThingName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"thingName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func encodeSchema(w io.Writer, s *schema.Schema) (err error) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tew := errWriter{w: w}\n\tif s.Description != \"\" {\n\t\tew.writeFormat(`\"description\": %q, `, s.Description)\n\t}\n\tew.writeString(`\"type\": \"object\", `)\n\tew.writeString(`\"additionalProperties\": false, `)\n\tew.writeString(`\"properties\": {`)\n\tvar required []string\n\tvar notFirst bool\n\tfor _, key := range sortedFieldNames(s.Fields) {\n\t\tfield := s.Fields[key]\n\t\tif notFirst {\n\t\t\tew.writeString(\", \")\n\t\t}\n\t\tnotFirst = true\n\t\tif field.Required {\n\t\t\trequired = append(required, fmt.Sprintf(\"%q\", key))\n\t\t}\n\t\tew.err = encodeField(ew, key, field)\n\t\tif ew.err != nil {\n\t\t\treturn ew.err\n\t\t}\n\t}\n\tew.writeString(\"}\")\n\tif s.MinLen > 0 {\n\t\tew.writeFormat(`, \"minProperties\": %s`, strconv.FormatInt(int64(s.MinLen), 10))\n\t}\n\tif s.MaxLen > 0 {\n\t\tew.writeFormat(`, \"maxProperties\": %s`, strconv.FormatInt(int64(s.MaxLen), 10))\n\t}\n\n\tif len(required) > 0 {\n\t\tew.writeFormat(`, \"required\": [%s]`, strings.Join(required, \", \"))\n\t}\n\treturn ew.err\n}", "func (s OutputService15TestShapeItemShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ItemDetail != nil {\n\t\tv := s.ItemDetail\n\t\tattrs := make([]protocol.Attribute, 0, 1)\n\n\t\tif len(s.ItemDetail.Type) > 0 {\n\n\t\t\tv := s.ItemDetail.Type\n\t\t\tattrs = append(attrs, protocol.Attribute{Name: \"xsi:type\", Value: v, Meta: protocol.Metadata{}})\n\t\t}\n\t\tmetadata := protocol.Metadata{Attributes: attrs, XMLNamespacePrefix: \"xsi\", XMLNamespaceURI: \"http://www.w3.org/2001/XMLSchema-instance\"}\n\t\te.SetFields(protocol.BodyTarget, \"ItemDetail\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIPSetInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Activate != nil {\n\t\tv := *s.Activate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"activate\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Location != nil {\n\t\tv := *s.Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorId != nil {\n\t\tv := *s.DetectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IpSetId != nil {\n\t\tv := *s.IpSetId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"ipSetId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Robot) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.FleetArn != nil {\n\t\tv := *s.FleetArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"fleetArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.GreenGrassGroupId != nil {\n\t\tv := *s.GreenGrassGroupId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"greenGrassGroupId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentJob != nil {\n\t\tv := *s.LastDeploymentJob\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentJob\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentTime != nil {\n\t\tv := *s.LastDeploymentTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentTime\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Status) > 0 {\n\t\tv := s.Status\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"status\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeInputDeviceOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionState) > 0 {\n\t\tv := s.ConnectionState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.DeviceSettingsSyncState) > 0 {\n\t\tv := s.DeviceSettingsSyncState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deviceSettingsSyncState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.HdDeviceSettings != nil {\n\t\tv := s.HdDeviceSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"hdDeviceSettings\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MacAddress != nil {\n\t\tv := *s.MacAddress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"macAddress\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.NetworkSettings != nil {\n\t\tv := s.NetworkSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"networkSettings\", v, metadata)\n\t}\n\tif s.SerialNumber != nil {\n\t\tv := *s.SerialNumber\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"serialNumber\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAliasInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FunctionVersion != nil {\n\t\tv := *s.FunctionVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FunctionVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RoutingConfig != nil {\n\t\tv := s.RoutingConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RoutingConfig\", v, metadata)\n\t}\n\tif s.FunctionName != nil {\n\t\tv := *s.FunctionName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"FunctionName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateImageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DistributionConfigurationArn != nil {\n\t\tv := *s.DistributionConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"distributionConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnhancedImageMetadataEnabled != nil {\n\t\tv := *s.EnhancedImageMetadataEnabled\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enhancedImageMetadataEnabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImageRecipeArn != nil {\n\t\tv := *s.ImageRecipeArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"imageRecipeArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ImageTestsConfiguration != nil {\n\t\tv := s.ImageTestsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"imageTestsConfiguration\", v, metadata)\n\t}\n\tif s.InfrastructureConfigurationArn != nil {\n\t\tv := *s.InfrastructureConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"infrastructureConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s VpcLink) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SecurityGroupIds != nil {\n\t\tv := s.SecurityGroupIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"securityGroupIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.SubnetIds != nil {\n\t\tv := s.SubnetIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"subnetIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcLinkId != nil {\n\t\tv := *s.VpcLinkId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkStatus) > 0 {\n\t\tv := s.VpcLinkStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.VpcLinkStatusMessage != nil {\n\t\tv := *s.VpcLinkStatusMessage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatusMessage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkVersion) > 0 {\n\t\tv := s.VpcLinkVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkVersion\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.AuthorizationScopes != nil {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestModels != nil {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PayloadFormatVersion != nil {\n\t\tv := *s.PayloadFormatVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"payloadFormatVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestTemplates != nil {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.TlsConfig != nil {\n\t\tv := s.TlsConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"tlsConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateOTAUpdateInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Files != nil {\n\t\tv := s.Files\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"files\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiKeyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Expires != nil {\n\t\tv := *s.Expires\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"expires\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.BackendEnvironmentArn != nil {\n\t\tv := *s.BackendEnvironmentArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"backendEnvironmentArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnablePullRequestPreview != nil {\n\t\tv := *s.EnablePullRequestPreview\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enablePullRequestPreview\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnvironmentVariables != nil {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PullRequestEnvironmentName != nil {\n\t\tv := *s.PullRequestEnvironmentName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"pullRequestEnvironmentName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseId != nil {\n\t\tv := *s.RouteResponseId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeResponseId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePackageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PackageDescription != nil {\n\t\tv := *s.PackageDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageName != nil {\n\t\tv := *s.PackageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageSource != nil {\n\t\tv := s.PackageSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PackageSource\", v, metadata)\n\t}\n\tif len(s.PackageType) > 0 {\n\t\tv := s.PackageType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdatePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (s OutputService11TestShapeOutputService11TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-false-bool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Integer != nil {\n\t\tv := *s.Integer\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-int\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.RFC822TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-true-bool\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OauthToken != nil {\n\t\tv := *s.OauthToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"oauthToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Repository != nil {\n\t\tv := *s.Repository\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"repository\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualNodeSpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Backends != nil {\n\t\tv := s.Backends\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"backends\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\tif s.ServiceDiscovery != nil {\n\t\tv := s.ServiceDiscovery\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"serviceDiscovery\", v, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s NetworkPathComponent) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ComponentId != nil {\n\t\tv := *s.ComponentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ComponentType != nil {\n\t\tv := *s.ComponentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Egress != nil {\n\t\tv := s.Egress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Egress\", v, metadata)\n\t}\n\tif s.Ingress != nil {\n\t\tv := s.Ingress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Ingress\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s ImportComponentInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChangeDescription != nil {\n\t\tv := *s.ChangeDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"changeDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Data != nil {\n\t\tv := *s.Data\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"data\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.KmsKeyId != nil {\n\t\tv := *s.KmsKeyId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"kmsKeyId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.SemanticVersion != nil {\n\t\tv := *s.SemanticVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"semanticVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Uri != nil {\n\t\tv := *s.Uri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"uri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService13TestShapeTimeContainer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Bar != nil {\n\t\tv := *s.Bar\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"bar\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"unixTimestamp\", QuotedFormatTime: false}, metadata)\n\t}\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CodeReview) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CodeReviewArn != nil {\n\t\tv := *s.CodeReviewArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeReviewArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedTimeStamp != nil {\n\t\tv := *s.CreatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CreatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedTimeStamp != nil {\n\t\tv := *s.LastUpdatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"LastUpdatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Metrics != nil {\n\t\tv := s.Metrics\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Metrics\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Owner != nil {\n\t\tv := *s.Owner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Owner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProviderType) > 0 {\n\t\tv := s.ProviderType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProviderType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PullRequestId != nil {\n\t\tv := *s.PullRequestId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PullRequestId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RepositoryName != nil {\n\t\tv := *s.RepositoryName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RepositoryName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SourceCodeType != nil {\n\t\tv := s.SourceCodeType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SourceCodeType\", v, metadata)\n\t}\n\tif len(s.State) > 0 {\n\t\tv := s.State\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"State\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.StateReason != nil {\n\t\tv := *s.StateReason\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StateReason\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s PutObjectOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentSHA256 != nil {\n\t\tv := *s.ContentSHA256\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ContentSHA256\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ETag != nil {\n\t\tv := *s.ETag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ETag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StorageClass) > 0 {\n\t\tv := s.StorageClass\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StorageClass\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s GetRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation2Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceBackend) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ClientPolicy != nil {\n\t\tv := s.ClientPolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"clientPolicy\", v, metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PolicyDocument != nil {\n\t\tv := *s.PolicyDocument\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policyDocument\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBucketInput) MarshalFields(e protocol.FieldEncoder) error {\n\n\tif len(s.ACL) > 0 {\n\t\tv := s.ACL\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-acl\", v, metadata)\n\t}\n\tif s.GrantFullControl != nil {\n\t\tv := *s.GrantFullControl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-full-control\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantRead != nil {\n\t\tv := *s.GrantRead\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantReadACP != nil {\n\t\tv := *s.GrantReadACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWrite != nil {\n\t\tv := *s.GrantWrite\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWriteACP != nil {\n\t\tv := *s.GrantWriteACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ObjectLockEnabledForBucket != nil {\n\t\tv := *s.ObjectLockEnabledForBucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-bucket-object-lock-enabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Bucket != nil {\n\t\tv := *s.Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"Bucket\", protocol.StringValue(v), metadata)\n\t}\n\tif s.CreateBucketConfiguration != nil {\n\t\tv := s.CreateBucketConfiguration\n\n\t\tmetadata := protocol.Metadata{XMLNamespaceURI: \"http://s3.amazonaws.com/doc/2006-03-01/\"}\n\t\te.SetFields(protocol.PayloadTarget, \"CreateBucketConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Pipeline) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Activities) > 0 {\n\t\tv := s.Activities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"activities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreationTime != nil {\n\t\tv := *s.CreationTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.LastUpdateTime != nil {\n\t\tv := *s.LastUpdateTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdateTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ReprocessingSummaries) > 0 {\n\t\tv := s.ReprocessingSummaries\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"reprocessingSummaries\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s VirtualNodeRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualNodeName != nil {\n\t\tv := *s.VirtualNodeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualNodeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetIntrospectionSchemaInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IncludeDirectives != nil {\n\t\tv := *s.IncludeDirectives\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"includeDirectives\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s OTAUpdateInfo) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsIotJobArn != nil {\n\t\tv := *s.AwsIotJobArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsIotJobId != nil {\n\t\tv := *s.AwsIotJobId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.CreationDate != nil {\n\t\tv := *s.CreationDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ErrorInfo != nil {\n\t\tv := s.ErrorInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"errorInfo\", v, metadata)\n\t}\n\tif s.LastModifiedDate != nil {\n\t\tv := *s.LastModifiedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastModifiedDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.OtaUpdateArn != nil {\n\t\tv := *s.OtaUpdateArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OtaUpdateFiles != nil {\n\t\tv := s.OtaUpdateFiles\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"otaUpdateFiles\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.OtaUpdateStatus) > 0 {\n\t\tv := s.OtaUpdateStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s Source) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Etag != nil {\n\t\tv := *s.Etag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"etag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Bucket != nil {\n\t\tv := *s.S3Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Bucket\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Key != nil {\n\t\tv := *s.S3Key\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Key\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateModelOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateJobInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.HopDestinations != nil {\n\t\tv := s.HopDestinations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"hopDestinations\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\t}\n\tif s.AccelerationSettings != nil {\n\t\tv := s.AccelerationSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accelerationSettings\", v, metadata)\n\t}\n\tif len(s.BillingTagsSource) > 0 {\n\t\tv := s.BillingTagsSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingTagsSource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tvar ClientRequestToken string\n\tif s.ClientRequestToken != nil {\n\t\tClientRequestToken = *s.ClientRequestToken\n\t} else {\n\t\tClientRequestToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientRequestToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientRequestToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.JobTemplate != nil {\n\t\tv := *s.JobTemplate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"jobTemplate\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Priority != nil {\n\t\tv := *s.Priority\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"priority\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Queue != nil {\n\t\tv := *s.Queue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"queue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Role != nil {\n\t\tv := *s.Role\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"role\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Settings != nil {\n\t\tv := s.Settings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"settings\", v, metadata)\n\t}\n\tif len(s.SimulateReservedQueue) > 0 {\n\t\tv := s.SimulateReservedQueue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"simulateReservedQueue\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.StatusUpdateInterval) > 0 {\n\t\tv := s.StatusUpdateInterval\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"statusUpdateInterval\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.UserMetadata != nil {\n\t\tv := s.UserMetadata\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"userMetadata\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateBrokerStorageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"currentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TargetBrokerEBSVolumeInfo != nil {\n\t\tv := s.TargetBrokerEBSVolumeInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targetBrokerEBSVolumeInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ClusterArn != nil {\n\t\tv := *s.ClusterArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"clusterArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CustomCodeSigning) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CertificateChain != nil {\n\t\tv := s.CertificateChain\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"certificateChain\", v, metadata)\n\t}\n\tif s.HashAlgorithm != nil {\n\t\tv := *s.HashAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"hashAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Signature != nil {\n\t\tv := s.Signature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signature\", v, metadata)\n\t}\n\tif s.SignatureAlgorithm != nil {\n\t\tv := *s.SignatureAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"signatureAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetMacieSessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\treturn nil\n}", "func (s MeshRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s Resource) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Attributes) > 0 {\n\t\tv := s.Attributes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"attributes\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Feature != nil {\n\t\tv := *s.Feature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"feature\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Type != nil {\n\t\tv := *s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GatewayRouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.GatewayRouteName != nil {\n\t\tv := *s.GatewayRouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"gatewayRouteName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s RouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteName != nil {\n\t\tv := *s.RouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualRouterName != nil {\n\t\tv := *s.VirtualRouterName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualRouterName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorModelVersion != nil {\n\t\tv := *s.DetectorModelVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AttachPolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (v *Service) Encode(sw stream.Writer) error {\n\tif err := sw.WriteStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 7, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 1, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.ThriftName); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.ParentID != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 4, Type: wire.TI32}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := v.ParentID.Encode(sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 5, Type: wire.TList}); err != nil {\n\t\treturn err\n\t}\n\tif err := _List_Function_Encode(v.Functions, sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 6, Type: wire.TI32}); err != nil {\n\t\treturn err\n\t}\n\tif err := v.ModuleID.Encode(sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.Annotations != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 8, Type: wire.TMap}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := _Map_String_String_Encode(v.Annotations, sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn sw.WriteStructEnd()\n}", "func (s GetSigningPlatformOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Category) > 0 {\n\t\tv := s.Category\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"category\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MaxSizeInMB != nil {\n\t\tv := *s.MaxSizeInMB\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"maxSizeInMB\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Partner != nil {\n\t\tv := *s.Partner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"partner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SigningConfiguration != nil {\n\t\tv := s.SigningConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingConfiguration\", v, metadata)\n\t}\n\tif s.SigningImageFormat != nil {\n\t\tv := s.SigningImageFormat\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingImageFormat\", v, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Product) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ActivationUrl != nil {\n\t\tv := *s.ActivationUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ActivationUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Categories != nil {\n\t\tv := s.Categories\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Categories\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CompanyName != nil {\n\t\tv := *s.CompanyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CompanyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationTypes != nil {\n\t\tv := s.IntegrationTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"IntegrationTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.MarketplaceUrl != nil {\n\t\tv := *s.MarketplaceUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"MarketplaceUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductArn != nil {\n\t\tv := *s.ProductArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductName != nil {\n\t\tv := *s.ProductName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductSubscriptionResourcePolicy != nil {\n\t\tv := *s.ProductSubscriptionResourcePolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductSubscriptionResourcePolicy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AwsLambdaFunctionLayer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CodeSize != nil {\n\t\tv := *s.CodeSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeSize\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s HttpAuthorization) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Sigv4 != nil {\n\t\tv := s.Sigv4\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"sigv4\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PipelineName != nil {\n\t\tv := *s.PipelineName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"pipelineName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}" ]
[ "0.63487035", "0.6247174", "0.6194336", "0.618014", "0.6168986", "0.6121274", "0.6101091", "0.60709465", "0.6064383", "0.6013114", "0.6009643", "0.596077", "0.5953159", "0.59338963", "0.5928191", "0.59230846", "0.5908567", "0.59064555", "0.59002864", "0.5883836", "0.58787435", "0.58758366", "0.5874384", "0.5871449", "0.5871239", "0.5856992", "0.5849757", "0.58488786", "0.5843346", "0.5836478", "0.5834761", "0.5821758", "0.58201164", "0.5814471", "0.5813436", "0.58118814", "0.5804731", "0.58032274", "0.5802723", "0.5786969", "0.57824916", "0.577702", "0.5775129", "0.57730013", "0.57661", "0.57611525", "0.5759162", "0.5759137", "0.5752116", "0.57493204", "0.57477975", "0.5746127", "0.5742733", "0.5739661", "0.57325435", "0.5732392", "0.5728183", "0.57219046", "0.57206935", "0.57107663", "0.5702608", "0.57019746", "0.5701881", "0.569675", "0.5696084", "0.56929165", "0.5686287", "0.5682366", "0.5676836", "0.56768155", "0.5675934", "0.5665759", "0.5661479", "0.56607556", "0.5658633", "0.56579363", "0.56539637", "0.5650915", "0.5645314", "0.5644813", "0.5643945", "0.56386656", "0.563784", "0.5636651", "0.56361496", "0.5635233", "0.5632069", "0.5626496", "0.5626192", "0.5624139", "0.5622761", "0.5622761", "0.56204456", "0.5616667", "0.5613424", "0.56132764", "0.5612373", "0.56104285", "0.56100184", "0.56056297", "0.5588799" ]
0.0
-1
Send marshals and sends the CreateMembers API request.
func (r CreateMembersRequest) Send(ctx context.Context) (*CreateMembersResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &CreateMembersResponse{ CreateMembersOutput: r.Request.Data.(*CreateMembersOutput), response: &aws.Response{Request: r.Request}, } return resp, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r CreateMemberRequest) Send(ctx context.Context) (*CreateMemberResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &CreateMemberResponse{\n\t\tCreateMemberOutput: r.Request.Data.(*CreateMemberOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func ExampleMembersClient_BeginCreate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armblockchain.NewMembersClient(\"51766542-3ed7-4a72-a187-0c8ab644ddab\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := client.BeginCreate(ctx,\n\t\t\"contosemember1\",\n\t\t\"mygroup\",\n\t\t&armblockchain.MembersClientBeginCreateOptions{BlockchainMember: &armblockchain.Member{\n\t\t\tLocation: to.Ptr(\"southeastasia\"),\n\t\t\tProperties: &armblockchain.MemberProperties{\n\t\t\t\tConsortium: to.Ptr(\"ContoseConsortium\"),\n\t\t\t\tConsortiumManagementAccountPassword: to.Ptr(\"<consortiumManagementAccountPassword>\"),\n\t\t\t\tPassword: to.Ptr(\"<password>\"),\n\t\t\t\tValidatorNodesSKU: &armblockchain.MemberNodesSKU{\n\t\t\t\t\tCapacity: to.Ptr[int32](2),\n\t\t\t\t},\n\t\t\t\tProtocol: to.Ptr(armblockchain.BlockchainProtocolQuorum),\n\t\t\t},\n\t\t},\n\t\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (r StartMonitoringMembersRequest) Send(ctx context.Context) (*StartMonitoringMembersResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &StartMonitoringMembersResponse{\n\t\tStartMonitoringMembersOutput: r.Request.Data.(*StartMonitoringMembersOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func MembersAdd(w http.ResponseWriter, r *http.Request) {\n\tauth := service.GetSessionMember(r)\n\t// Parse form\n\tif err := r.ParseMultipartForm(setting.FileMaxSize); err != nil {\n\t\tLogger.Error(err.Error())\n\t}\n\n\t// Default avatar\n\tavatar := setting.SetDefaultAvatar().MemberAvatar\n\n\tmember := model.Member{}\n\tvar convertErr error\n\tvar teamList []int\n\n\tmember.LoginID = r.FormValue(\"loginID\")\n\tmember.Password = r.FormValue(\"password\")\n\tmember.Name = r.FormValue(\"name\")\n\tmember.RoleType, _ = strconv.Atoi(r.FormValue(\"role\"))\n\tmember.GenderType, convertErr = strconv.Atoi(r.FormValue(\"gender\"))\n\tmember.Comment = sql.NullString{String: r.FormValue(\"comment\"), Valid: true}\n\tmember.CompanyID, convertErr = strconv.Atoi(r.FormValue(\"company\"))\n\tmember.DepartmentID, convertErr = strconv.Atoi(r.FormValue(\"department\"))\n\tgithubAccount := r.FormValue(\"githubAccount\")\n\n\t// timestamp is time if user not input date\n\ttimestamp, _ := time.Parse(\"2006-01-02 15:04:05\", \"0001-01-01 00:00:00\")\n\tbirthdayInput, _ := time.Parse(\"01-02-2006\", r.FormValue(\"birthday\"))\n\tif birthdayInput == timestamp {\n\t\tmember.Birthday = mysql.NullTime{Time: birthdayInput, Valid: false}\n\t} else {\n\t\tmember.Birthday = mysql.NullTime{Time: birthdayInput, Valid: true}\n\t}\n\n\tfor _, value := range r.PostForm[\"team\"] {\n\t\tteamID, _ := strconv.Atoi(value)\n\t\tif teamID != 0 {\n\t\t\tteamList = append(teamList, teamID)\n\t\t}\n\t}\n\n\tif convertErr != nil {\n\t\tLogger.Error(convertErr.Error())\n\t}\n\n\tpasswordData := map[string]string{\n\t\t\"password\": member.Password,\n\t}\n\n\t// validate member data\n\tvalidateErr := model.ValidateMember(member, r.ContentLength)\n\n\tpasswordErr := model.ValidatePassword(passwordData)\n\tsnsAccountErr := model.ValidateSNSAccount(githubAccount)\n\n\t// if validate are ok\n\tif len(validateErr) == 0 && len(passwordErr) == 0 && len(snsAccountErr) == 0 {\n\n\t\t// get data of file uploaded\n\t\tfile, handler, err := r.FormFile(\"avatar\")\n\n\t\tif err == nil {\n\t\t\tavatar = handler.Filename\n\n\t\t\t//create temporary file to save image\n\t\t\ttempFile, err := ioutil.TempFile(setting.ImageBaseURL, \"*\"+avatar)\n\n\t\t\t//get path of image\n\t\t\tavatar = tempFile.Name()\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(err.Error())\n\t\t\t}\n\t\t\tdefer tempFile.Close()\n\n\t\t\t// read all of the contents of our uploaded file into a byte array\n\t\t\tfileBytes, err := ioutil.ReadAll(file)\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(err.Error())\n\t\t\t}\n\n\t\t\t// write this byte array to our temporary file\n\t\t\ttempFile.Write(fileBytes)\n\n\t\t\t// if app running on EC2\n\t\t\tif setting.UseS3Service() {\n\t\t\t\t// upload file to aws S3\n\t\t\t\tservice.UploadImageToS3(avatar, setting.MemberFolderType)\n\t\t\t\t// save path on S3 bucket\n\t\t\t\tavatar = setting.S3BucketURL + setting.S3MemberFolder + filepath.Base(avatar)\n\t\t\t}\n\t\t} else if err != http.ErrMissingFile {\n\t\t\tLogger.Error(err.Error())\n\t\t}\n\n\t\tmember.PictureURL = sql.NullString{String: avatar, Valid: true}\n\n\t\tmemberID := model.SaveMember(member)\n\t\tsns := model.SNS{\n\t\t\tMemberID: memberID,\n\t\t\tGithub: githubAccount,\n\t\t}\n\t\tmodel.SaveSNSAccount(sns)\n\n\t\t// get array of team of user\n\t\tfor _, teamID := range teamList {\n\t\t\tif !model.CheckTeamMemberExist(teamID, memberID) {\n\t\t\t\tmodel.SaveTeamMember(teamID, memberID)\n\t\t\t}\n\t\t}\n\t\thttp.Redirect(w, r, \"/admin/members\", 301)\n\t}\n\n\t// get all team, company and department to select\n\tallTeams := model.GetAllTeam()\n\tcompanies := model.GetAllCompany()\n\tdepartments := model.GetAllDepartment()\n\n\ttemplateData := map[string]interface{}{\n\t\t\"allTeams\": allTeams.List,\n\t\t\"companies\": companies,\n\t\t\"departments\": departments,\n\t\t\"validateError\": validateErr,\n\t\t\"passwordError\": passwordErr,\n\t\t\"snsAccountError\": snsAccountErr,\n\t\t\"member\": member,\n\t\t\"teamList\": teamList,\n\t\t\"snsAccount\": githubAccount,\n\t\t\"title\": \"Add Member\",\n\t\t\"auth\": auth,\n\t\t\"tab\": setting.MembersTab,\n\t}\n\n\ttmpl := template.Must(template.ParseFiles(\"template/admin_members/member_add.tmpl\", setting.AdminTemplate))\n\tif err := tmpl.ExecuteTemplate(w, \"base\", templateData); err != nil {\n\t\tLogger.Error(err.Error())\n\t}\n}", "func (r *PoolCNAMEMembersResource) Create(item PoolCNAMEMembersConfig) error {\n\tif err := r.c.ModQuery(\"POST\", BasePath+PoolCNAMEMembersEndpoint, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s CreateMembersInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Accounts != nil {\n\t\tv := s.Accounts\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Accounts\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.GraphArn != nil {\n\t\tv := *s.GraphArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GraphArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Message != nil {\n\t\tv := *s.Message\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Message\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (o *AssignUserToCustomerGroupUsingPATCH1Params) SetMembers(members *models.MemberListWsDTO) {\n\to.Members = members\n}", "func CreateListClusterMembersRequest() (request *ListClusterMembersRequest) {\n\trequest = &ListClusterMembersRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Edas\", \"2017-08-01\", \"ListClusterMembers\", \"/pop/v5/resource/cluster_member_list\", \"Edas\", \"openAPI\")\n\trequest.Method = requests.GET\n\treturn\n}", "func (b *ChatRequestBuilder) Members() *ChatMembersCollectionRequestBuilder {\n\tbb := &ChatMembersCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/members\"\n\treturn bb\n}", "func (c *Controller) CreateMembership(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t//connect to database\n\tdb, err := c.Session.Connect()\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Failed to connect, cannot reach database\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 400)\n\t\tc.Logger.Logging(req, 400)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\tauth := models.Authentication{Decoded: context.Get(req, \"decoded\")}\n\tok, err := auth.Authorize(db, 3)\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Failed to authorize, error during authorization\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 400)\n\t\tc.Logger.Logging(req, 400)\n\t\treturn\n\t}\n\tif !ok {\n\t\terror := models.RespError{Error: \"Failed to authorize, error during authorization. Make sure you have permissions to use this route.\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 401)\n\t\tc.Logger.Logging(req, 401)\n\t\treturn\n\t}\n\n\tparams := mux.Vars(req)\n\tid, err := strconv.Atoi(params[\"id\"])\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Id is required in route\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 400)\n\t\tc.Logger.Logging(req, 400)\n\t\treturn\n\t}\n\n\ttranstype := req.URL.Query().Get(\"type\")\n\tif transtype == \"\" {\n\t\ttranstype = \"Unknown\"\n\t}\n\n\tvar membership models.Membership\n\terr = json.NewDecoder(req.Body).Decode(&membership)\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Failed to parse request. Please make sure request is valid format\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 404)\n\t\tc.Logger.Logging(req, 404)\n\t\treturn\n\t}\n\n\tplayer := models.Player{Id: id}\n\terr = player.GetPlayer(db)\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Failed to find player\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 404)\n\t\tc.Logger.Logging(req, 404)\n\t\treturn\n\t}\n\tmembership.EmployeeID = auth.EmployeeID\n\tmembership.PlayerID = player.Id\n\tmembership.PlayTime = (membership.Amount / 10) * 3600\n\tmembership.ActiveDate = time.Now().Format(time.RFC3339)\n\tmembership.DeactiveDate = time.Now().AddDate(20, 0, 0).Format(time.RFC3339)\n\tmembership.Active = true\n\n\terr = membership.CreateMembership(db, transtype)\n\tif err != nil {\n\t\terror := models.RespError{Error: \"Failed to create membership for player\"}\n\t\tresp, _ := json.Marshal(error)\n\t\thttp.Error(w, string(resp), 404)\n\t\tc.Logger.Logging(req, 404)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tc.Logger.Logging(req, 200)\n\tjson.NewEncoder(w).Encode(membership)\n\treturn\n}", "func (o *PostAPI24PoliciesNfsMembersParams) SetMembers(members *models.PolicyMemberExportPost) {\n\to.Members = members\n}", "func (m *TeamItemRequestBuilder) Members()(*ifc923048eff969ef232f17cdaf6c11e18676c5c9e2918bc19001d30cbdc4b5c1.MembersRequestBuilder) {\n return ifc923048eff969ef232f17cdaf6c11e18676c5c9e2918bc19001d30cbdc4b5c1.NewMembersRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (s CreateMembersInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AccountDetails != nil {\n\t\tv := s.AccountDetails\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"AccountDetails\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func NewListMember(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\r\n\tvar listMember ListMember\r\n\r\n\tjson.NewDecoder(r.Body).Decode(&listMember)\r\n\r\n\t// listMember.UUID = listMember.UserID + listMember.ListID\r\n\tlistMember = CreateNewListMember(listMember.UserID, listMember.ListID, listMember.UserName)\r\n\t//prints the user json\r\n\t// db.Where(\"UUID = ?\", listMember.UUID).FirstOrCreate(&listMember)\r\n\r\n\tjson.NewEncoder(w).Encode(listMember)\r\n}", "func NewMembersAPI(name string, options ...Option) *MembersAPI {\n\topts := newOptions()\n\tfor _, option := range options {\n\t\toption(opts)\n\t}\n\n\treturn &MembersAPI{\n\t\tname: name,\n\t\tlogger: opts.logger,\n\t\tfileSystem: opts.fileSystem,\n\t\tclock: opts.clock,\n\t}\n}", "func (m *MembershipsClient) Create(ctx context.Context, userID, orgID, teamID *identity.ID) error {\n\tif orgID == nil {\n\t\treturn errors.New(\"invalid org\")\n\t}\n\tif userID == nil {\n\t\treturn errors.New(\"invalid user\")\n\t}\n\tif teamID == nil {\n\t\treturn errors.New(\"invalid team\")\n\t}\n\n\tmembershipBody := primitive.Membership{\n\t\tOwnerID: userID,\n\t\tOrgID: orgID,\n\t\tTeamID: teamID,\n\t}\n\n\tID, err := identity.NewMutable(&membershipBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmembership := apitypes.Membership{\n\t\tID: &ID,\n\t\tVersion: 1,\n\t\tBody: &membershipBody,\n\t}\n\n\treq, _, err := m.client.NewRequest(\"POST\", \"/memberships\", nil, membership, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = m.client.Do(ctx, req, nil, nil, nil)\n\treturn err\n}", "func (m memberUsecase) Create(ctx context.Context, name, phone string) (*models.Member, error) {\n\treturn m.memberRepos.Create(ctx, name, phone)\n}", "func (s CreateMembersOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Members != nil {\n\t\tv := s.Members\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Members\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.UnprocessedAccounts != nil {\n\t\tv := s.UnprocessedAccounts\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"UnprocessedAccounts\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (mock *MailgunMock) CreateMemberCalls() []struct {\n\tMerge bool\n\tAddr string\n\tPrototype mailgun.Member\n} {\n\tvar calls []struct {\n\t\tMerge bool\n\t\tAddr string\n\t\tPrototype mailgun.Member\n\t}\n\tlockMailgunMockCreateMember.RLock()\n\tcalls = mock.calls.CreateMember\n\tlockMailgunMockCreateMember.RUnlock()\n\treturn calls\n}", "func (s *FriendshipService) Create(params *FriendshipCreateParams) (*User, *http.Response, error) {\n\tuser := new(User)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"create.json\").QueryStruct(params).Receive(user, apiError)\n\treturn user, resp, relevantError(err, *apiError)\n}", "func (o *DashboardAllOfLinks) SetMembers(v string) {\n\to.Members = &v\n}", "func (m *ChatItemRequestBuilder) Members()(*i29250e65d3047fac7086c3da168f1dc97b716e57040772b108c92eb7e41e5082.MembersRequestBuilder) {\n return i29250e65d3047fac7086c3da168f1dc97b716e57040772b108c92eb7e41e5082.NewMembersRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *OrganizationManager) AddMembers(id string, memberIDs []string, opts ...RequestOption) (err error) {\n\tbody := struct {\n\t\tMembers []string `json:\"members\"`\n\t}{\n\t\tMembers: memberIDs,\n\t}\n\terr = m.Request(\"POST\", m.URI(\"organizations\", id, \"members\"), &body, opts...)\n\treturn\n}", "func CreateMember(t *testing.T, client *gophercloud.ServiceClient, lb *loadbalancers.LoadBalancer, pool *pools.Pool, subnetID, subnetCIDR string) (*pools.Member, error) {\n\tmemberName := tools.RandomString(\"TESTACCT-\", 8)\n\tmemberPort := tools.RandomInt(100, 1000)\n\tmemberWeight := tools.RandomInt(1, 10)\n\n\tcidrParts := strings.Split(subnetCIDR, \"/\")\n\tsubnetParts := strings.Split(cidrParts[0], \".\")\n\tmemberAddress := fmt.Sprintf(\"%s.%s.%s.%d\", subnetParts[0], subnetParts[1], subnetParts[2], tools.RandomInt(10, 100))\n\n\tt.Logf(\"Attempting to create member %s\", memberName)\n\n\tcreateOpts := pools.CreateMemberOpts{\n\t\tName: memberName,\n\t\tProtocolPort: memberPort,\n\t\tWeight: &memberWeight,\n\t\tAddress: memberAddress,\n\t\tSubnetID: subnetID,\n\t}\n\n\tt.Logf(\"Member create opts: %#v\", createOpts)\n\n\tmember, err := pools.CreateMember(client, pool.ID, createOpts).Extract()\n\tif err != nil {\n\t\treturn member, err\n\t}\n\n\tt.Logf(\"Successfully created member %s\", memberName)\n\n\tif err := WaitForLoadBalancerState(client, lb.ID, \"ACTIVE\"); err != nil {\n\t\treturn member, fmt.Errorf(\"Timed out waiting for loadbalancer to become active: %s\", err)\n\t}\n\n\tth.AssertEquals(t, member.Name, memberName)\n\n\treturn member, nil\n}", "func (mock *MailgunMock) CreateMemberListCalls() []struct {\n\tSubscribed *bool\n\tAddr string\n\tNewMembers []interface{}\n} {\n\tvar calls []struct {\n\t\tSubscribed *bool\n\t\tAddr string\n\t\tNewMembers []interface{}\n\t}\n\tlockMailgunMockCreateMemberList.RLock()\n\tcalls = mock.calls.CreateMemberList\n\tlockMailgunMockCreateMemberList.RUnlock()\n\treturn calls\n}", "func (c *Client) NewAddMemberRequest(ctx context.Context, path string, payload *AddMemberPayload) (*http.Request, error) {\n\tvar body bytes.Buffer\n\terr := c.Encoder.Encode(payload, &body, \"*/*\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\tif c.JWTSigner != nil {\n\t\tif err := c.JWTSigner.Sign(req); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn req, nil\n}", "func (s *Status) Members(args *structs.GenericRequest, reply *structs.ServerMembersResponse) error {\n\t// Check node read permissions\n\tif aclObj, err := s.srv.ResolveToken(args.AuthToken); err != nil {\n\t\treturn err\n\t} else if aclObj != nil && !aclObj.AllowNodeRead() {\n\t\treturn structs.ErrPermissionDenied\n\t}\n\n\tserfMembers := s.srv.Members()\n\tmembers := make([]*structs.ServerMember, len(serfMembers))\n\tfor i, mem := range serfMembers {\n\t\tmembers[i] = &structs.ServerMember{\n\t\t\tName: mem.Name,\n\t\t\tAddr: mem.Addr,\n\t\t\tPort: mem.Port,\n\t\t\tTags: mem.Tags,\n\t\t\tStatus: mem.Status.String(),\n\t\t\tProtocolMin: mem.ProtocolMin,\n\t\t\tProtocolMax: mem.ProtocolMax,\n\t\t\tProtocolCur: mem.ProtocolCur,\n\t\t\tDelegateMin: mem.DelegateMin,\n\t\t\tDelegateMax: mem.DelegateMax,\n\t\t\tDelegateCur: mem.DelegateCur,\n\t\t}\n\t}\n\t*reply = structs.ServerMembersResponse{\n\t\tServerName: s.srv.config.NodeName,\n\t\tServerRegion: s.srv.config.Region,\n\t\tServerDC: s.srv.config.Datacenter,\n\t\tMembers: members,\n\t}\n\treturn nil\n}", "func (o *UpdateRole) SetMembers(v []int32) {\n\to.Members = &v\n}", "func (o *PostAPI24PoliciesNfsMembersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.Authorization != nil {\n\n\t\t// header param Authorization\n\t\tif err := r.SetHeaderParam(\"Authorization\", *o.Authorization); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif o.XRequestID != nil {\n\n\t\t// header param X-Request-ID\n\t\tif err := r.SetHeaderParam(\"X-Request-ID\", *o.XRequestID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif o.Members != nil {\n\t\tif err := r.SetBodyParam(o.Members); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvaluesPolicyIds := o.PolicyIds\n\n\tjoinedPolicyIds := swag.JoinByFormat(valuesPolicyIds, \"csv\")\n\t// query array param policy_ids\n\tif err := r.SetQueryParam(\"policy_ids\", joinedPolicyIds...); err != nil {\n\t\treturn err\n\t}\n\n\tvaluesPolicyNames := o.PolicyNames\n\n\tjoinedPolicyNames := swag.JoinByFormat(valuesPolicyNames, \"csv\")\n\t// query array param policy_names\n\tif err := r.SetQueryParam(\"policy_names\", joinedPolicyNames...); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *ListMembersOutput) SetMembers(v []*MemberSummary) *ListMembersOutput {\n\ts.Members = v\n\treturn s\n}", "func CreateNewListMember(uID string, lID string, uName string) ListMember {\r\n\tvar listMember = ListMember{UserID: uID, ListID: lID, UUID: uID + lID, UserName: uName}\r\n\r\n\tdb.Where(\"UUID = ?\", listMember.UUID).FirstOrCreate(&listMember)\r\n\tfmt.Println(\"listmember list ID\", listMember.ListID)\r\n\t// str, _ := json.Marshal(listMember)\r\n\t//prints the user json\r\n\t// fmt.Println(\"listMember Created\", string(str))\r\n\tfmt.Println(\"listMember username \", listMember.UserName)\r\n\treturn listMember\r\n}", "func (g *GroupsService) AddMembers(group Group, users ...string) (bool, *Response, error) {\n\treturn g.memberAction(group, \"$add-members\", groupRequestBody(users...), nil)\n}", "func (s CreateMemberInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Account != nil {\n\t\tv := s.Account\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"account\", v, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (msg MsgAddMember) Type() string { return \"add_member\" }", "func (r CreateUserRequest) Send() (*CreateUserOutput, error) {\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*CreateUserOutput), nil\n}", "func (a *Client) PostProjectsProjectIDMembers(params *PostProjectsProjectIDMembersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostProjectsProjectIDMembersCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPostProjectsProjectIDMembersParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"PostProjectsProjectIDMembers\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/projects/{project_id}/members\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &PostProjectsProjectIDMembersReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*PostProjectsProjectIDMembersCreated)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for PostProjectsProjectIDMembers: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o *AssignUserToCustomerGroupUsingPATCH1Params) WithMembers(members *models.MemberListWsDTO) *AssignUserToCustomerGroupUsingPATCH1Params {\n\to.SetMembers(members)\n\treturn o\n}", "func (r *ChatMembersCollectionRequest) Add(ctx context.Context, reqObj *ConversationMember) (resObj *ConversationMember, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func (uc *UserMember) Start() {\n\n\tvar err error\n\n\tmn := &uc.MemberMaker\n\terr = mn.OpenAcc() // runs the node, opening acceptors\n\tif err == nil {\n\t\tgo func() {\n\t\t\tvar (\n\t\t\t\tcnx *xt.TcpConnection\n\t\t\t\tversion1 uint32\n\t\t\t\tversion2 uint32\n\t\t\t)\n\t\t\tcnx, version2, err = mn.SessionSetup(version1)\n\t\t\tif cnx != nil {\n\t\t\t\tdefer cnx.Close()\n\t\t\t}\n\t\t\t_ = version2 // not yet used\n\t\t\tif err == nil {\n\t\t\t\terr = mn.MemberAndOK()\n\t\t\t}\n\t\t\t// XXX MODIFY TO USE CLUSTER_ID PASSED TO UserMember\n\t\t\t// 2013-10-12 this is a join by cluster name\n\t\t\tif err == nil {\n\t\t\t\terr = mn.JoinAndReply()\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\terr = mn.GetAndMembers()\n\t\t\t}\n\t\t\t// DEBUG ====================================================\n\t\t\tvar nilMembers []int\n\t\t\tfor i := 0; i < len(uc.Members); i++ {\n\t\t\t\tif uc.Members[i] == nil {\n\t\t\t\t\tnilMembers = append(nilMembers, i)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(nilMembers) > 0 {\n\t\t\t\tfmt.Printf(\"UserMember.Start() after Get finds nil members: %v\\n\",\n\t\t\t\t\tnilMembers)\n\t\t\t}\n\t\t\t// END ======================================================\n\n\t\t\tif err == nil {\n\t\t\t\terr = mn.ByeAndAck()\n\t\t\t}\n\n\t\t\tmn.DoneCh <- err\n\t\t}()\n\t} else {\n\t\tmn.DoneCh <- err\n\t}\n}", "func ExampleSyncMembersClient_BeginCreateOrUpdate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armsql.NewSyncMembersClient(\"00000000-1111-2222-3333-444444444444\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := client.BeginCreateOrUpdate(ctx,\n\t\t\"syncgroupcrud-65440\",\n\t\t\"syncgroupcrud-8475\",\n\t\t\"syncgroupcrud-4328\",\n\t\t\"syncgroupcrud-3187\",\n\t\t\"syncmembercrud-4879\",\n\t\tarmsql.SyncMember{\n\t\t\tProperties: &armsql.SyncMemberProperties{\n\t\t\t\tDatabaseName: to.Ptr(\"syncgroupcrud-7421\"),\n\t\t\t\tDatabaseType: to.Ptr(armsql.SyncMemberDbTypeAzureSQLDatabase),\n\t\t\t\tServerName: to.Ptr(\"syncgroupcrud-3379.database.windows.net\"),\n\t\t\t\tSyncDirection: to.Ptr(armsql.SyncDirectionBidirectional),\n\t\t\t\tSyncMemberAzureDatabaseResourceID: to.Ptr(\"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/syncgroupcrud-65440/providers/Microsoft.Sql/servers/syncgroupcrud-8475/databases/syncgroupcrud-4328\"),\n\t\t\t\tUsePrivateLinkConnection: to.Ptr(true),\n\t\t\t\tUserName: to.Ptr(\"myUser\"),\n\t\t\t},\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (d *Deployment) createMember(spec api.DeploymentSpec, status *api.DeploymentStatus, group api.ServerGroup, id string, apiObject *api.ArangoDeployment, mods ...reconcile.CreateMemberMod) (string, error) {\n\tgs := status.GetServerGroupStatus(group)\n\n\tm, err := d.renderMember(spec, status, &gs, group, id, apiObject)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, mod := range mods {\n\t\tif err := mod(status, group, m); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif err := status.Members.Add(*m, group); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstatus.UpdateServerGroupStatus(group, gs)\n\n\treturn m.ID, nil\n}", "func NewMockMembers(ctrl *gomock.Controller) *MockMembers {\n\tmock := &MockMembers{ctrl: ctrl}\n\tmock.recorder = &MockMembersMockRecorder{mock}\n\treturn mock\n}", "func (r CreateProfileRequest) Send() (*CreateProfileOutput, error) {\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*CreateProfileOutput), nil\n}", "func (k Keeper) SetMembers(ctx sdk.Context, Members types.Members) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.MembersKey))\n\tb := k.cdc.MustMarshalBinaryBare(&Members)\n\tstore.Set(GetMembersIDBytes(Members.Id), b)\n}", "func GiveMemberList(pc net.PacketConn, addr net.Addr, memberList *[]MemberID) {\n\treply, _ := json.Marshal(*memberList)\n\tpc.WriteTo(reply, addr)\n}", "func (_AuthContract *AuthContractCaller) Members(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _AuthContract.contract.Call(opts, out, \"members\", arg0)\n\treturn *ret0, err\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\tu := user.Create()\n\n\tj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(j))\n}", "func CreateMemberlist(name, ip string) (*gcp_memberlist.Memberlist, error) {\n\n\t//Get URL for GCP service\n\tserviceUrl := os.Getenv(\"GCP_SERVICE_URL\")\n\tif serviceUrl == \"\" {\n\t\treturn nil, fmt.Errorf(\"GCP_SERVICE_URL environment variable unset or missing\")\n\t}\n\n\treturn gcp_memberlist.Create(\n\t\t&gcp_memberlist.IpAddress{\n\t\t\tName: name,\n\t\t\tIp: ip,\n\t\t\tPort: \"\",\n\t\t\tProtocol: \"tcp\",\n\t\t})\n}", "func (r CreateUserRequest) Send(ctx context.Context) (*CreateUserResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &CreateUserResponse{\n\t\tCreateUserOutput: r.Request.Data.(*CreateUserOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (service *ContrailService) RESTCreateLoadbalancerMember(c echo.Context) error {\n\trequestData := &models.CreateLoadbalancerMemberRequest{}\n\tif err := c.Bind(requestData); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"resource\": \"loadbalancer_member\",\n\t\t}).Debug(\"bind failed on create\")\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid JSON format\")\n\t}\n\tctx := c.Request().Context()\n\tresponse, err := service.CreateLoadbalancerMember(ctx, requestData)\n\tif err != nil {\n\t\treturn common.ToHTTPError(err)\n\t}\n\treturn c.JSON(http.StatusCreated, response)\n}", "func CreateSyncUsersRequest() (request *SyncUsersRequest) {\n\trequest = &SyncUsersRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EHPC\", \"2018-04-12\", \"SyncUsers\", \"\", \"\")\n\trequest.Method = requests.GET\n\treturn\n}", "func (r CreateProfileRequest) Send(ctx context.Context) (*CreateProfileResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &CreateProfileResponse{\n\t\tCreateProfileOutput: r.Request.Data.(*CreateProfileOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (r *RoleCreate) HasMembers() bool {\n\treturn r.hasMembers\n}", "func (c *Client) NewListMemberRequest(ctx context.Context, path string) (*http.Request, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c.JWTSigner != nil {\n\t\tif err := c.JWTSigner.Sign(req); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn req, nil\n}", "func (s *GroupsService) AddMember(\n\tctx context.Context,\n\tuserName, groupName, parentName string,\n) error {\n\traw, err := json.Marshal(struct {\n\t\tUserName string `json:\"user_name,omitempty\"`\n\t\tGroupName string `json:\"group_name,omitempty\"`\n\t\tParentName string `json:\"parent_name\"`\n\t}{\n\t\tuserName,\n\t\tgroupName,\n\t\tparentName,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\ts.client.url+\"2.0/groups/add-member\",\n\t\tbytes.NewBuffer(raw),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq = req.WithContext(ctx)\n\tres, err := s.client.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode >= 300 || res.StatusCode <= 199 {\n\t\treturn fmt.Errorf(\n\t\t\t\"Failed to returns 2XX response: %d\", res.StatusCode)\n\t}\n\n\treturn nil\n\n}", "func (s *service) fillMembersData(ctx context.Context, members []models.Member) ([]models.Member, error) {\n\tfor index, member := range members {\n\t\tuser, _, err := s.store.UserGetByID(ctx, member.ID, false)\n\t\tif err != nil || user == nil {\n\t\t\treturn nil, NewErrUserNotFound(member.ID, err)\n\t\t}\n\n\t\tmembers[index] = models.Member{ID: user.ID, Username: user.Username, Role: member.Role}\n\t}\n\n\treturn members, nil\n}", "func (r *channelMember) Create(mod *types.ChannelMember) (*types.ChannelMember, error) {\n\trh.SetCurrentTimeRounded(&mod.CreatedAt)\n\tmod.UpdatedAt = nil\n\n\treturn mod, r.db().Insert(\"messaging_channel_member\", mod)\n}", "func (a *MemberAwaitility) Create(obj client.Object) error {\n\terr := wait.Poll(a.RetryInterval, a.Timeout, func() (done bool, err error) {\n\t\tif err := a.Client.Create(context.TODO(), obj); err != nil {\n\t\t\ta.T.Logf(\"trying to create %+v. Error: %s. Will try to create again.\", obj, err.Error())\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn err\n}", "func (g *Group) RequestMemberlist() {\n\tjoinMessage := &JoinMessage{\n\t\tMember: g.Member().ProtoMember(),\n\t}\n\tprotoJoinMessage, _ := ptypes.MarshalAny(joinMessage)\n\n\tm := &Message{\n\t\tMessageType: Message_INTRO_SYN,\n\t\tAddr: g.Addr,\n\t\tDetails: protoJoinMessage,\n\t}\n\n\t// Only join using primary coordinator\n\tfor _, coordinator := range g.coordinators {\n\t\tif coordinator == g.Addr {\n\t\t\tcontinue\n\t\t}\n\t\tSendTCP(coordinator, m)\n\t}\n}", "func (r *UsersService) Create(usercreaterequest *UserCreateRequest) *UsersCreateCall {\n\tc := &UsersCreateCall{s: r.s, opt_: make(map[string]interface{})}\n\tc.usercreaterequest = usercreaterequest\n\treturn c\n}", "func AllMembers(req routes.MemberRequest) {\n\tdefer connLog.FuncTimeTrack(time.Now(), \"Member All Full Function\")\n\tfmt.Println(\"Endpoint Hit: All Members Endpoint\")\n\n\t//TODO: Run Debug, gets stuck in infinite loop\n\t//connLog.ConnTimeGet(config.MemberAll)\n\tresults, err := config.SqlDb().Query(\"SELECT * FROM members\")\n\tdefer config.SqlDb().Close()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tbuildResponse(results, err)\n}", "func (u *Users) Create(w http.ResponseWriter, r *http.Request) {\n\tvar SignupForm SignupForm\n\terr := parseForm(r, &SignupForm)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Fprintln(w, SignupForm)\n}", "func (m Member) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", m.ID)\n\tpopulate(objectMap, \"location\", m.Location)\n\tpopulate(objectMap, \"name\", m.Name)\n\tpopulate(objectMap, \"properties\", m.Properties)\n\tpopulate(objectMap, \"sku\", m.SKU)\n\tpopulate(objectMap, \"tags\", m.Tags)\n\tpopulate(objectMap, \"type\", m.Type)\n\treturn json.Marshal(objectMap)\n}", "func AddMember(req routes.MemberRequest) {\n\tstmt, err := config.SqlDb().Prepare(\"INSERT INTO members(name, lob, pcp) VALUES(?, ?, ?)\")\n\tdefer config.SqlDb().Close()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tstmt.Exec(req.Name, req.Lob, req.Pcp)\n\tlog.Printf(\"%s Added Successfully\", req.Name)\n}", "func CreateRendezvous(w http.ResponseWriter, r *http.Request) {\n\tname := rands(20)\n\tsig, err := fernet.EncryptAndSign([]byte(name), fernetKey)\n\tif err != nil {\n\t\tlog.Println(\"error signing app name:\", err)\n\t\thttp.Error(w, \"internal error\", 500)\n\t\treturn\n\t}\n\tw.WriteHeader(201)\n\turl := \"https://\" + name + \":\" + string(sig) + \"@route.webx.io/\"\n\tio.WriteString(w, url)\n}", "func (a *API) Create(ctx context.Context, param *protos.NewRoomParam) (*protos.Room, error) {\n\t// check if user presents\n\troom := &RoomModel{}\n\terr := a.DB.Where(&RoomModel{ID: param.Id}).\n\t\tFirst(room).Error\n\tif err != nil {\n\t\tif err != gorm.ErrRecordNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(room.ID) > 0 {\n\t\treturn nil, fmt.Errorf(RoomAlreadyExistError)\n\t}\n\t// get all users\n\tusers := []*UserModel{}\n\terr = a.DB.Where(\"id IN (?)\", param.UserIDs).\n\t\tFind(&users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// save room instance\n\troom = &RoomModel{\n\t\tID: param.Id,\n\t\tName: param.Name,\n\t\tPhoto: param.Photo,\n\t\tDescription: param.Description,\n\t}\n\terr = a.DB.Create(room).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// add member to it\n\terr = a.DB.Model(room).\n\t\tAssociation(\"Members\").\n\t\tAppend(users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// publish new room created events\n\tpayload, err := a.GetRoomInstancePayload(room)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.Events <- &RoomEvent{\n\t\tTime: time.Now(),\n\t\tEvent: RoomCreated,\n\t\tPayload: payload,\n\t}\n\treturn RoomModelToProto(room), nil\n}", "func Create(c *gin.Context) {\n\tvar user users.User\n\n\t// ShouldBindJSON - read request body and unmarshals the []bytes to user\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tbdErr := errors.NewBadRequestError(fmt.Sprintf(\"invalid json body: %s\", err.Error()))\n\t\tc.JSON(bdErr.Status, bdErr)\n\t\treturn\n\t}\n\n\tresult, err := services.UserServ.CreateUser(user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusCreated, result.Marshall(isPublic))\n}", "func (s *projService) CreateTeamMember(ctx context.Context, req *pb.CreateTeamMemberRequest) (*pb.CreateTeamMemberResponse, error) {\n\tresp := &pb.CreateTeamMemberResponse{}\n\tvar err error\n\n\tsqlstring := `INSERT INTO tb_TeamMember (dtmCreated, dtmModified, dtmDeleted, bitIsDeleted, intVersion, inbMserviceId, inbProjectId,\n\t\tchvName, intProjectRoleId, chvEmail) VALUES(NOW(), NOW(), NOW(), 0, 1, ?, ?, ?, ?, ?)`\n\n\tstmt, err := s.db.Prepare(sqlstring)\n\tif err != nil {\n\t\tlevel.Error(s.logger).Log(\"what\", \"Prepare\", \"error\", err)\n\t\tresp.ErrorCode = 500\n\t\tresp.ErrorMessage = \"db.Prepare failed\"\n\t\treturn resp, nil\n\t}\n\n\tdefer stmt.Close()\n\n\tres, err := stmt.Exec(req.GetMserviceId(), req.GetProjectId(), req.GetName(), req.GetProjectRoleId(), req.GetEmail())\n\tif err == nil {\n\t\tmemberId, err := res.LastInsertId()\n\t\tif err != nil {\n\t\t\tlevel.Error(s.logger).Log(\"what\", \"LastInsertId\", \"error\", err)\n\t\t} else {\n\t\t\tlevel.Debug(s.logger).Log(\"memberId\", memberId)\n\t\t}\n\n\t\tresp.MemberId = memberId\n\t\tresp.Version = 1\n\t} else {\n\t\tresp.ErrorCode = 501\n\t\tresp.ErrorMessage = err.Error()\n\t\tlevel.Error(s.logger).Log(\"what\", \"Exec\", \"error\", err)\n\t\terr = nil\n\t}\n\n\treturn resp, err\n}", "func (k Keeper) AppendMembers(\n\tctx sdk.Context,\n\tcreator string,\n\taddress string,\n) uint64 {\n\t// Create the Members\n\tcount := k.GetMembersCount(ctx)\n\tvar Members = types.Members{\n\t\tCreator: creator,\n\t\tId: count,\n\t\tAddress: address,\n\t}\n\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.MembersKey))\n\tvalue := k.cdc.MustMarshalBinaryBare(&Members)\n\tstore.Set(GetMembersIDBytes(Members.Id), value)\n\n\t// Update Members count\n\tk.SetMembersCount(ctx, count+1)\n\n\treturn count\n}", "func (o *DeleteAPI24PoliciesSmbMembersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.Authorization != nil {\n\n\t\t// header param Authorization\n\t\tif err := r.SetHeaderParam(\"Authorization\", *o.Authorization); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif o.XRequestID != nil {\n\n\t\t// header param X-Request-ID\n\t\tif err := r.SetHeaderParam(\"X-Request-ID\", *o.XRequestID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tvaluesMemberIds := o.MemberIds\n\n\tjoinedMemberIds := swag.JoinByFormat(valuesMemberIds, \"csv\")\n\t// query array param member_ids\n\tif err := r.SetQueryParam(\"member_ids\", joinedMemberIds...); err != nil {\n\t\treturn err\n\t}\n\n\tvaluesMemberNames := o.MemberNames\n\n\tjoinedMemberNames := swag.JoinByFormat(valuesMemberNames, \"csv\")\n\t// query array param member_names\n\tif err := r.SetQueryParam(\"member_names\", joinedMemberNames...); err != nil {\n\t\treturn err\n\t}\n\n\tvaluesMemberTypes := o.MemberTypes\n\n\tjoinedMemberTypes := swag.JoinByFormat(valuesMemberTypes, \"csv\")\n\t// query array param member_types\n\tif err := r.SetQueryParam(\"member_types\", joinedMemberTypes...); err != nil {\n\t\treturn err\n\t}\n\n\tvaluesPolicyIds := o.PolicyIds\n\n\tjoinedPolicyIds := swag.JoinByFormat(valuesPolicyIds, \"csv\")\n\t// query array param policy_ids\n\tif err := r.SetQueryParam(\"policy_ids\", joinedPolicyIds...); err != nil {\n\t\treturn err\n\t}\n\n\tvaluesPolicyNames := o.PolicyNames\n\n\tjoinedPolicyNames := swag.JoinByFormat(valuesPolicyNames, \"csv\")\n\t// query array param policy_names\n\tif err := r.SetQueryParam(\"policy_names\", joinedPolicyNames...); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *PostAPI24PoliciesNfsMembersParams) WithMembers(members *models.PolicyMemberExportPost) *PostAPI24PoliciesNfsMembersParams {\n\to.SetMembers(members)\n\treturn o\n}", "func ExampleMembersClient_Update() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armblockchain.NewMembersClient(\"51766542-3ed7-4a72-a187-0c8ab644ddab\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.Update(ctx,\n\t\t\"ContoseMember1\",\n\t\t\"mygroup\",\n\t\t&armblockchain.MembersClientUpdateOptions{BlockchainMember: &armblockchain.MemberUpdate{\n\t\t\tProperties: &armblockchain.MemberPropertiesUpdate{\n\t\t\t\tPassword: to.Ptr(\"<password>\"),\n\t\t\t\tConsortiumManagementAccountPassword: to.Ptr(\"<consortiumManagementAccountPassword>\"),\n\t\t\t},\n\t\t},\n\t\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (c *Client) NewCreateUsersRequest(ctx context.Context, path string, payload *CreateUsersPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType != \"*/*\" {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func (r *RoleCreate) GetMembers() []string {\n\treturn r.Members\n}", "func newMember(id string, nn string, meta map[string]string, send MemberSend) *Member {\n\treturn &Member{\n\t\tid: id,\n\t\tnickname: nn,\n\t\tmeta: meta,\n\t\tsendFunc: send,\n\t}\n}", "func (c *RequestGuildMembersCommand) MarshalJSON() ([]byte, error) {\n\ttype raw RequestGuildMembersCommand\n\n\tif c.UserIDs != nil && c.Query != nil {\n\t\treturn nil, errors.New(\"neither UserIDs nor Query can be filled\")\n\t}\n\n\tvar marshaling interface{} = (*raw)(c)\n\tif c.Query != nil {\n\t\t// Force the Limit field to be present if Query is present.\n\t\tmarshaling = struct {\n\t\t\t*raw\n\t\t\tLimit uint `json:\"limit\"`\n\t\t}{\n\t\t\traw: (*raw)(c),\n\t\t\tLimit: c.Limit,\n\t\t}\n\t}\n\n\treturn json.Marshal(marshaling)\n}", "func CreatePlayer(c *fiber.Ctx) {\n\tvar req createPlayerRequest\n\n\terr := c.BodyParser(&req)\n\tif err != nil {\n\t\tc.SendStatus(400)\n\t\tc.JSON(utils.FormatErrors(err))\n\t\treturn\n\t}\n\n\terr = req.validate()\n\tif err != nil {\n\t\tc.SendStatus(400)\n\t\tc.JSON(utils.FormatErrors(err))\n\t\treturn\n\t}\n\n\tplayer := &models.Player{\n\t\tUsername: req.Username,\n\t\tEmail: req.Email,\n\t}\n\n\terr = player.Create(req.PW)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.JSON(utils.FormatErrors(err))\n\t\treturn\n\t}\n\n\tplayer.Token, err = auth.CreateToken(player)\n\tif err != nil {\n\t\tc.SendStatus(500)\n\t\tc.JSON(utils.FormatErrors(err))\n\t\treturn\n\t}\n\n\tc.SendStatus(201)\n\tc.JSON(player)\n}", "func CreateSendRequest(args *SendArguments) []byte {\n\tsigners := GetSigners()\n\n\tconv := convert.NewConvert()\n\n\tif args.Party == \"\" {\n\t\tlog.Error(\"Missing Party information\")\n\t\treturn nil\n\t}\n\n\tif args.CounterParty == \"\" {\n\t\tlog.Error(\"Missing CounterParty information\")\n\t\treturn nil\n\t}\n\n\t// TODO: Can't convert identities to accounts, this way!\n\tparty := GetAccountKey(args.Party)\n\tcounterParty := GetAccountKey(args.CounterParty)\n\n\tif args.Currency == \"\" || args.Amount == \"\" {\n\t\tlog.Error(\"Missing an amount\")\n\t\treturn nil\n\t}\n\n\tamount := conv.GetCoin(args.Amount, args.Currency)\n\n\t// Build up the Inputs\n\tpartyBalance := GetBalance(party)\n\tcounterPartyBalance := GetBalance(counterParty)\n\tif partyBalance == nil || counterPartyBalance == nil {\n\t\tlog.Error(\"Missing Balances\")\n\t\treturn nil\n\t}\n\n\tinputs := make([]action.SendInput, 0)\n\tinputs = append(inputs,\n\t\taction.NewSendInput(party, *partyBalance),\n\t\taction.NewSendInput(counterParty, *counterPartyBalance))\n\n\t// Build up the outputs\n\toutputs := make([]action.SendOutput, 0)\n\toutputs = append(outputs,\n\t\taction.NewSendOutput(party, partyBalance.Minus(amount)),\n\t\taction.NewSendOutput(counterParty, counterPartyBalance.Plus(amount)))\n\n\tfee := conv.GetCoin(args.Fee, args.Currency)\n\tgas := conv.GetCoin(args.Gas, args.Currency)\n\n\tif conv.HasErrors() {\n\t\tConsole.Error(conv.GetErrors())\n\t\tos.Exit(-1)\n\t}\n\n\t// Create base transaction\n\tsend := &action.Send{\n\t\tBase: action.Base{\n\t\t\tType: action.SEND,\n\t\t\tChainId: app.ChainId,\n\t\t\tSigners: signers,\n\t\t\tSequence: global.Current.Sequence,\n\t\t},\n\t\tInputs: inputs,\n\t\tOutputs: outputs,\n\t\tFee: fee,\n\t\tGas: gas,\n\t}\n\n\treturn SignAndPack(action.SEND, action.Transaction(send))\n}", "func New(cfg *config.Config, lv []volume.Local, remote string, logger kitlog.Logger) (*Membership, error) {\n\tm := &Membership{\n\t\tlocalVolumes: lv,\n\t\tnodes: make(map[string]node),\n\t\tcfg: cfg,\n\t\tremovedVolumeIDs: make(map[string]time.Time),\n\t\tlogger: kitlog.With(logger, \"src\", \"membership\", \"name\", cfg.Name),\n\t}\n\n\tlist, err := memberlist.Create(m.buildConfig(cfg))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create memberlist: %s\", err.Error())\n\t}\n\n\tm.members = list\n\n\tif remote != \"\" {\n\t\tu, err := url.Parse(remote)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u.Scheme == \"\" {\n\t\t\tu.Scheme = \"http\"\n\t\t}\n\n\t\tc, err := client.New(u.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcfg, err := c.Config(context.TODO())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thost, _, err := net.SplitHostPort(u.Host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thostPort := net.JoinHostPort(host, strconv.Itoa(cfg.Memberlist.Port))\n\t\t_, err = list.Join([]string{hostPort})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to join cluster: %s\", err.Error())\n\t\t}\n\t\tm.logger.Log(\"msg\", fmt.Sprintf(\"Joined remote cluster %q\", hostPort))\n\t}\n\n\treturn m, nil\n}", "func (m *AdministrativeUnitsAdministrativeUnitItemRequestBuilder) Members()(*AdministrativeUnitsItemMembersRequestBuilder) {\n return NewAdministrativeUnitsItemMembersRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (o *UpdateAccountMemberParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.AccountUpdateMemberSetup != nil {\n\t\tif err := r.SetBodyParam(o.AccountUpdateMemberSetup); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// path param account_slug\n\tif err := r.SetPathParam(\"account_slug\", o.AccountSlug); err != nil {\n\t\treturn err\n\t}\n\n\t// path param member_id\n\tif err := r.SetPathParam(\"member_id\", o.MemberID); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Member) NewMember(node1 map[string]interface{}, node2 string, ref []string) (nodeNum, refNum int64, err error) {\n\n\tcon := createConnection()\n\tdefer con.Close()\n\n\tnode1Id := node1[\"id\"].(string)\n\n\tresult, err := con.ExecNeo(\n\t\t\"CREATE (n:Member {id:{id},name: {name}, sex: {sex},edu:{edu},birth:{birth},bf:{bf},info:{info}})\",\n\t\tnode1) // map[string]interface{}{\"name\": \"1\", \"sex\": 1}\n\tnumResult, _ := result.RowsAffected()\n\tfmt.Printf(\"CREATED ROWS: %d\\n\", numResult) // CREATED ROWS: 1\n\n\tvar numR int64\n\tif node2 != \"\" && len(ref) == 2 {\n\t\trel := Member{}\n\t\tnumR = rel.AddRelation(node1Id, node2, ref)\n\t\tfmt.Println(numR)\n\t}\n\n\treturn numResult, numR, err\n}", "func (mr *ClientMockRecorder) CreateOrganizationMembership(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrganizationMembership\", reflect.TypeOf((*Client)(nil).CreateOrganizationMembership), arg0, arg1)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.SignUp(data.Email, data.Password, data.RoleID)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func CreateMintRequest(args *SendArguments) []byte {\n\tsigners := GetSigners()\n\n\tconv := convert.NewConvert()\n\n\tif args.Party == \"\" {\n\t\tlog.Error(\"Missing Party information\", \"args\", args)\n\t\treturn nil\n\t}\n\n\t// TODO: Can't convert identities to accounts, this way!\n\tparty := GetAccountKey(args.Party)\n\tzero := GetAccountKey(\"Zero-OneLedger\")\n\n\tamount := conv.GetCoin(args.Amount, args.Currency)\n\n\t// Build up the Inputs\n\tzeroBalance := GetBalance(zero)\n\tpartyBalance := GetBalance(party)\n\n\tif zeroBalance == nil || partyBalance == nil {\n\t\tlog.Error(\"Missing Balances\")\n\t\treturn nil\n\t}\n\n\tinputs := make([]action.SendInput, 0)\n\tinputs = append(inputs,\n\t\taction.NewSendInput(zero, *zeroBalance),\n\t\taction.NewSendInput(party, *partyBalance))\n\n\t// Build up the outputs\n\toutputs := make([]action.SendOutput, 0)\n\toutputs = append(outputs,\n\t\taction.NewSendOutput(zero, zeroBalance.Minus(amount)),\n\t\taction.NewSendOutput(party, partyBalance.Plus(amount)))\n\n\tgas := conv.GetCoin(args.Gas, args.Currency)\n\tfee := conv.GetCoin(args.Fee, args.Currency)\n\n\tif conv.HasErrors() {\n\t\tConsole.Error(conv.GetErrors())\n\t\tos.Exit(-1)\n\t}\n\n\t// Create base transaction\n\tsend := &action.Send{\n\t\tBase: action.Base{\n\t\t\tType: action.SEND,\n\t\t\tChainId: app.ChainId,\n\t\t\tSigners: signers,\n\t\t\tOwner: zero,\n\t\t\tSequence: global.Current.Sequence,\n\t\t},\n\t\tInputs: inputs,\n\t\tOutputs: outputs,\n\t\tFee: fee,\n\t\tGas: gas,\n\t}\n\n\treturn SignAndPack(action.SEND, action.Transaction(send))\n}", "func (s *Service) Create(newUsersDefinition *model.NewUsersDefinition) *CreateOp {\n\treturn &CreateOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"POST\",\n\t\tPath: \"users\",\n\t\tPayload: newUsersDefinition,\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func ListMembers(client *clientv3.Client) (*clientv3.MemberListResponse, error) {\n\tctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout)\n\tdefer cancel()\n\treturn client.MemberList(ctx)\n}", "func Create(self *IpAddress) (*Memberlist, error) {\n\n\tserviceUrl := os.Getenv(\"GCP_SERVICE_URL\")\n\tif serviceUrl == \"\" {\n\t\treturn nil, fmt.Errorf(\"GCP_SERVICE_URL environment variable unset or missing\")\n\t}\n\n\tid, _ := uuid.NewV4()\n\n\tipAddresses := make(map[string]*IpAddress)\n\tipAddresses[id.String()] = self\n\n\treturn &Memberlist{\n\t\tServiceUrl: serviceUrl,\n\t\tUuid: id.String(),\n\t\tSelf: self,\n\t}, nil\n}", "func AddMember(client *clientv3.Client, peerAddrs []string) (*clientv3.MemberAddResponse, error) {\n\tctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout)\n\tdefer cancel()\n\treturn client.MemberAdd(ctx, peerAddrs)\n}", "func Create(conf *Config) (*Memberlist, error) {\n\tm, err := newMemberlist(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := m.setAlive(); err != nil {\n\t\tm.Shutdown()\n\t\treturn nil, err\n\t}\n\tm.schedule()\n\treturn m, nil\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqID(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t}\n\n\tu := model.UserModel{\n\t\t//BaseModel: model.BaseModel{},\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\t//fmt.Println()\n\t//log.Info(r.Username)\n\t//log.Info(r.Password)\n\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t}\n\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t}\n\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatabase, nil)\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\tSendResponse(c, nil, rsp)\n}", "func MembersAddDisplay(w http.ResponseWriter, r *http.Request) {\n\tauth := service.GetSessionMember(r)\n\t// get all team, company and department to select\n\tallTeams := model.GetAllTeam()\n\tcompanies := model.GetAllCompany()\n\tdepartments := model.GetAllDepartment()\n\tmember := model.Member{}\n\n\ttemplateData := map[string]interface{}{\n\t\t\"allTeams\": allTeams.List,\n\t\t\"companies\": companies,\n\t\t\"departments\": departments,\n\t\t\"member\": member,\n\t\t\"defaultGender\": setting.MaleGenderType,\n\t\t\"title\": \"Add Member\",\n\t\t\"auth\": auth,\n\t\t\"tab\": setting.MembersTab,\n\t}\n\n\ttmpl := template.Must(template.ParseFiles(\"template/admin_members/member_add.tmpl\", setting.AdminTemplate))\n\tif err := tmpl.ExecuteTemplate(w, \"base\", templateData); err != nil {\n\t\tLogger.Error(err.Error())\n\t}\n}", "func (ic *iamClient) AddUserGroupMembers(ctx context.Context, groupID uint64, request AddGroupMemberRequest) error {\n\tif ic == nil {\n\t\treturn ErrServerNotInit\n\t}\n\n\tvar (\n\t\t_ = \"AddUserGroupMembers\"\n\t\tpath = fmt.Sprintf(\"/api/v1/open/management/groups/%v/members/\", groupID)\n\t)\n\n\tvar (\n\t\turl = ic.opt.GateWayHost + path\n\t\tresp = &AddGroupMemberResponse{}\n\t)\n\n\tauth, err := ic.generateGateWayAuth(\"\")\n\tif err != nil {\n\t\tklog.Errorf(\"AddUserGroupMembers generateGateWayAuth failed: %v\", err)\n\t\treturn err\n\t}\n\n\tresult, body, errs := gorequest.New().\n\t\tTimeout(defaultTimeOut).\n\t\tPost(url).\n\t\tSet(\"Content-Type\", \"application/json\").\n\t\tSet(\"Accept\", \"application/json\").\n\t\tSet(\"X-Bkapi-Authorization\", auth).\n\t\tSetDebug(true).\n\t\tSend(&request).\n\t\tEndStruct(resp)\n\n\tif len(errs) != 0 {\n\t\tklog.Errorf(\"AddUserGroupMembers gorequest errors=`%s`\", errs)\n\t\treturn errs[0]\n\t}\n\tif result.StatusCode != http.StatusOK || resp.Code != 0 {\n\t\terrMsg := fmt.Errorf(\"AddUserGroupMembers API error: code[%v], body[%v], err[%s]\",\n\t\t\tresult.StatusCode, string(body), resp.Message)\n\t\treturn errMsg\n\t}\n\n\tklog.Infof(\"AddUserGroupMembers[%s:%v] successful\", ic.opt.SystemID, groupID)\n\treturn nil\n}", "func SetMemberRoutes(router *mux.Router) {\n\trouter.HandleFunc(\"/members\", controllers.CreateMember).Methods(\"POST\")\n\trouter.HandleFunc(\"/members\", controllers.GetMembers).Methods(\"GET\")\n\trouter.HandleFunc(\"/members/{id}\", controllers.UpdateMember).Methods(\"PUT\")\n\trouter.HandleFunc(\"/members/{id}\", controllers.DeleteMember).Methods(\"DELETE\")\n}", "func (c *PeerService) Create(gid string, peerParams *Peer) (*Peer, *http.Response, error) {\n\tpeer := new(Peer)\n\tapiError := new(APIError)\n\tpath := fmt.Sprintf(\"%s/peers\", gid)\n\tresp, err := c.sling.New().Post(path).BodyJSON(peerParams).Receive(peer, apiError)\n\treturn peer, resp, relevantError(err, *apiError)\n}", "func (s *MuteService) Create(params *MuteCreateParams) (User, *http.Response, error) {\n\tusers := new(User)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"create.json\").QueryStruct(params).Receive(users, apiError)\n\treturn *users, resp, relevantError(err, *apiError)\n}", "func (in *Members) DeepCopy() *Members {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Members)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Members) DeepCopy() *Members {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Members)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (a *MembersAPI) Get(ctx context.Context, req *http.Request) api.Response {\n\tdefer req.Body.Close()\n\n\td, err := api.GetDaemon(ctx)\n\tif err != nil {\n\t\treturn api.InternalError(err)\n\t}\n\n\tlistTask := membership.NewList(\n\t\tmakeMembershipStateShim(d.State()),\n\t)\n\tnodes, err := listTask.Run()\n\tif err != nil {\n\t\treturn api.SmartError(err)\n\t}\n\n\tresult := make([]ClusterRaftNode, len(nodes))\n\tfor k, v := range nodes {\n\t\tresult[k] = ClusterRaftNode{\n\t\t\tServerName: v.ServerName,\n\t\t\tURL: v.URL,\n\t\t\tDatabase: v.Database,\n\t\t\tStatus: v.Status,\n\t\t\tMessage: v.Message,\n\t\t}\n\t}\n\n\treturn api.SyncResponse(true, result)\n}" ]
[ "0.6807855", "0.61150706", "0.6020089", "0.60155904", "0.58056587", "0.57806194", "0.56505716", "0.5637864", "0.55466217", "0.5446939", "0.544583", "0.54326344", "0.5398153", "0.5361", "0.534575", "0.53239614", "0.5301728", "0.5221792", "0.5212375", "0.518709", "0.5156606", "0.5148869", "0.51466036", "0.5125648", "0.51001024", "0.50908136", "0.5079539", "0.5064003", "0.5021481", "0.5017572", "0.4991982", "0.49783066", "0.48925987", "0.48912138", "0.48859513", "0.4875978", "0.48749226", "0.48639655", "0.48565528", "0.4852178", "0.48478055", "0.48464724", "0.48450002", "0.48343876", "0.48277515", "0.48215237", "0.48191395", "0.4813367", "0.4811787", "0.48100027", "0.4806463", "0.479746", "0.4788486", "0.47871333", "0.47867227", "0.47845018", "0.47756022", "0.47677106", "0.47669917", "0.47573164", "0.47519153", "0.47492668", "0.47369435", "0.4711082", "0.47110587", "0.4701907", "0.46885902", "0.46818325", "0.46797538", "0.46671715", "0.46666062", "0.46648976", "0.46621516", "0.46500137", "0.46478188", "0.46379375", "0.4629099", "0.4627284", "0.4627117", "0.46239728", "0.46201685", "0.46010324", "0.45904312", "0.4583456", "0.4580614", "0.4577681", "0.45757172", "0.4571402", "0.45653445", "0.45648184", "0.45636758", "0.4552834", "0.45517018", "0.4545486", "0.4542062", "0.45419294", "0.4537326", "0.4537326", "0.4531524" ]
0.757311
1
SDKResponseMetdata returns the response metadata for the CreateMembers request.
func (r *CreateMembersResponse) SDKResponseMetdata() *aws.Response { return r.response }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *CreateMemberResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func CreateListClusterMembersResponse() (response *ListClusterMembersResponse) {\n\tresponse = &ListClusterMembersResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (r *StartMonitoringMembersResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateUserResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateProfileResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateReplicationGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateDBParameterGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateMembersInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Accounts != nil {\n\t\tv := s.Accounts\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Accounts\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.GraphArn != nil {\n\t\tv := *s.GraphArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GraphArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Message != nil {\n\t\tv := *s.Message\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Message\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (r *AddPermissionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func CreateListFunctionMetasResponse() (response *ListFunctionMetasResponse) {\n\tresponse = &ListFunctionMetasResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateMcubeUpgradePackageResponse() (response *CreateMcubeUpgradePackageResponse) {\n\tresponse = &CreateMcubeUpgradePackageResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (r *DescribeCreateAccountStatusResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateProjectVersionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateMembersInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AccountDetails != nil {\n\t\tv := s.AccountDetails\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"AccountDetails\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (r *ListFargateProfilesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ModifySelfservicePermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateMembersOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Members != nil {\n\t\tv := s.Members\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Members\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.UnprocessedAccounts != nil {\n\t\tv := s.UnprocessedAccounts\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"UnprocessedAccounts\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (r *AddResourcePermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateProjectResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateProjectResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateClusterResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateInstancesFromSnapshotResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateIdentityProviderResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RegisterUserResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateDBSecurityGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RoleCreate) HasMembers() bool {\n\treturn r.hasMembers\n}", "func (r *CreateMatchmakingConfigurationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (cgpr ContainersGetPropertiesResponse) NewMetadata() Metadata {\n\tmd := Metadata{}\n\tfor k, v := range cgpr.rawResponse.Header {\n\t\tif len(k) > mdPrefixLen {\n\t\t\tif prefix := k[0:mdPrefixLen]; strings.EqualFold(prefix, mdPrefix) {\n\t\t\t\tmd[strings.ToLower(k[mdPrefixLen:])] = v[0]\n\t\t\t}\n\t\t}\n\t}\n\treturn md\n}", "func (r *DescribeDBClusterParameterGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateRelationalDatabaseFromSnapshotResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *AssociateIpGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateCanaryResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateGovCloudAccountResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteMailboxPermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateJobResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListInstanceGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateEmailIdentityResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListEndpointGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateMatchmakingRuleSetResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *AdminConfirmSignUpResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateOpenIDConnectProviderResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateIndexResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreatePackagingConfigurationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *AttachLoadBalancerTargetGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateLicenseConfigurationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateVPCAssociationAuthorizationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DescribeTargetGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func NewMemberResponse(id string, createdAt time.Time) *MemberResponse {\n\tthis := MemberResponse{}\n\tthis.Id = id\n\tthis.CreatedAt = createdAt\n\treturn &this\n}", "func (r *CreateRegexPatternSetResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateSolutionVersionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateHITTypeResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateSchemaResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreatePackageResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateEndpointConfigResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateUserOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *GetPublicKeyResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ListGitHubAccountTokenNamesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (m *TeamItemRequestBuilder) Members()(*ifc923048eff969ef232f17cdaf6c11e18676c5c9e2918bc19001d30cbdc4b5c1.MembersRequestBuilder) {\n return ifc923048eff969ef232f17cdaf6c11e18676c5c9e2918bc19001d30cbdc4b5c1.NewMembersRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (r *ListGroupsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateProfileOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *CreateLayerResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateServiceLinkedRoleResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *GetCampaignVersionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateAccessPointResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateServerResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *StartReportCreationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *GetReusableDelegationSetLimitResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RegisterUsageResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RegisterUsageResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (mock *MailgunMock) CreateMemberCalls() []struct {\n\tMerge bool\n\tAddr string\n\tPrototype mailgun.Member\n} {\n\tvar calls []struct {\n\t\tMerge bool\n\t\tAddr string\n\t\tPrototype mailgun.Member\n\t}\n\tlockMailgunMockCreateMember.RLock()\n\tcalls = mock.calls.CreateMember\n\tlockMailgunMockCreateMember.RUnlock()\n\treturn calls\n}", "func (r *GetRelationalDatabaseMasterUserPasswordResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateSystemInstanceResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateTrafficMirrorFilterRuleResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateClassifierResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateSkillGroupOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *CreateConfigurationSetResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateFlowDefinitionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateHostedZoneResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateApiKeyResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateTriggerResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ModifyClusterSubnetGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RemoveLayerVersionPermissionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *RoleCreate) GetMembers() []string {\n\treturn r.Members\n}", "func (r *CreateImageResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *UpdateGameServerGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s CreateRoomOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *NiftyCreatePrivateLanResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateBucketResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (m *Value) Members() []xmlrpc.Member { return m.MembersMock() }", "func (r *CreateAliasResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *AddRoleToDBInstanceResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ResetDBParameterGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateNetworkInterfaceResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r CreateMembersRequest) Send(ctx context.Context) (*CreateMembersResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &CreateMembersResponse{\n\t\tCreateMembersOutput: r.Request.Data.(*CreateMembersOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (r CreateMembersRequest) Send(ctx context.Context) (*CreateMembersResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &CreateMembersResponse{\n\t\tCreateMembersOutput: r.Request.Data.(*CreateMembersOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (s CreateModelOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *ListSecurityProfilesResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *CreateNFSFileShareResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (mock *MailgunMock) CreateMemberListCalls() []struct {\n\tSubscribed *bool\n\tAddr string\n\tNewMembers []interface{}\n} {\n\tvar calls []struct {\n\t\tSubscribed *bool\n\t\tAddr string\n\t\tNewMembers []interface{}\n\t}\n\tlockMailgunMockCreateMemberList.RLock()\n\tcalls = mock.calls.CreateMemberList\n\tlockMailgunMockCreateMemberList.RUnlock()\n\treturn calls\n}" ]
[ "0.6399727", "0.61073905", "0.58518744", "0.55516726", "0.54876393", "0.5387715", "0.5352443", "0.53465104", "0.53399855", "0.5329582", "0.53176534", "0.53114414", "0.52635205", "0.5251484", "0.52496046", "0.5248241", "0.5235946", "0.52353257", "0.5220183", "0.5220183", "0.5217957", "0.5192094", "0.5189785", "0.5177759", "0.51473117", "0.5135012", "0.51261467", "0.51149994", "0.5111366", "0.5096168", "0.5095792", "0.50926924", "0.5079804", "0.5071157", "0.5066639", "0.50636876", "0.5061545", "0.50602585", "0.50593233", "0.50549895", "0.5052772", "0.504262", "0.5041812", "0.50410074", "0.5040444", "0.5039073", "0.5034818", "0.50310147", "0.50279754", "0.50215346", "0.501816", "0.5017697", "0.50142676", "0.50123775", "0.5011916", "0.5010518", "0.5009015", "0.5008533", "0.5008048", "0.49915728", "0.49866322", "0.49862018", "0.4985763", "0.4984995", "0.49768832", "0.49745026", "0.49670815", "0.4963835", "0.4963835", "0.49528843", "0.49523398", "0.49500754", "0.4946978", "0.49445295", "0.49409688", "0.49403283", "0.4937893", "0.4932278", "0.49312627", "0.49275187", "0.49253088", "0.49133414", "0.49125847", "0.4911953", "0.49110082", "0.49072775", "0.4906949", "0.4905429", "0.49040395", "0.48928046", "0.48852134", "0.48840442", "0.4882819", "0.4877216", "0.4877216", "0.48696545", "0.48665375", "0.48594564", "0.48548415" ]
0.6764258
1
Describe sends metrics descriptions of this collector through the ch channel. It implements collector interface
func (pc *PBSCollector) Describe(ch chan<- *prometheus.Desc) { for _, element := range pc.descPtrMap { ch <- element } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Collector) Describe(chan<- *prometheus.Desc) {}", "func (c *metricbeatCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\tfor _, metric := range c.metrics {\n\t\tch <- metric.desc\n\t}\n\n}", "func (a collectorAdapter) Describe(ch chan<- *prometheus.Desc) {\n\t// We have to send *some* metric in Describe, but we don't know which ones\n\t// we're going to get, so just send a dummy metric.\n\tch <- prometheus.NewDesc(\"dummy_metric\", \"Dummy metric.\", nil, nil)\n}", "func (c *filebeatCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\tfor _, metric := range c.metrics {\n\t\tch <- metric.desc\n\t}\n\n}", "func (c *beatCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\tfor _, metric := range c.metrics {\n\t\tch <- metric.desc\n\t}\n\n}", "func (m *metricVec) Describe(ch chan<- *Desc) { m.metricMap.Describe(ch) }", "func (*interfaceCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- receiveBytesDesc\n\tch <- receivePacketsDesc\n\tch <- receiveErrorsDesc\n\tch <- receiveDropsDesc\n\tch <- transmitBytesDesc\n\tch <- transmitPacketsDesc\n\tch <- transmitDropsDesc\n\tch <- transmitErrorsDesc\n\tch <- ipv6receiveBytesDesc\n\tch <- ipv6receivePacketsDesc\n\tch <- ipv6transmitBytesDesc\n\tch <- ipv6transmitPacketsDesc\n\tch <- adminStatusDesc\n\tch <- operStatusDesc\n\tch <- errorStatusDesc\n}", "func (c *goCollector) Describe(ch chan<- *Desc) {\n\tc.base.Describe(ch)\n\tfor _, i := range c.msMetrics {\n\t\tch <- i.desc\n\t}\n\tfor _, m := range c.rmExposedMetrics {\n\t\tch <- m.Desc()\n\t}\n}", "func (c *auditdCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\tfor _, metric := range c.metrics {\n\t\tch <- metric.desc\n\t}\n\n}", "func (collector *Metrics) Describe(ch chan<- *prometheus.Desc) {\n\tch <- collector.issue\n}", "func (k *KACollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range k.metrics {\n\t\tch <- m\n\t}\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- connected\n\tch <- up\n\tch <- distance\n\tch <- latency\n\tch <- users\n\tch <- channels\n\tch <- ison\n}", "func (c *Collector) Describe(ch chan<- *prometheus.Desc) {\n\tc.state.describe(ch)\n\tc.dbSize.describe(ch)\n\tc.uptime.describe(ch)\n\tc.clientConnections.describe(ch)\n\tc.clientReadRequests.describe(ch)\n\tc.clientWriteRequests.describe(ch)\n\tc.clientDroppedRequests.describe(ch)\n}", "func (c *OrchestratorCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.upMetric.Desc()\n\n\tfor _, m := range c.metrics {\n\t\tch <- m\n\t}\n}", "func (collector *MetricsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor k := range collector.metrics {\n\t\tfor idxMColl := range collector.metrics[k] {\n\t\t\tch <- collector.metrics[k][idxMColl].metricDesc\n\t\t}\n\t}\n\tcollector.defMetrics.describe(ch)\n}", "func (r *RGWCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, metric := range r.collectorList() {\n\t\tmetric.Describe(ch)\n\t}\n}", "func (collector *collector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- cpuUsageDesc\n\tch <- memUsageDesc\n\tch <- memUsagePeakDesc\n\tch <- swapUsageDesc\n\tch <- swapUsagePeakDesc\n\tch <- processCountDesc\n\tch <- containerPIDDesc\n\tch <- runningStatusDesc\n\tch <- diskUsageDesc\n\tch <- networkUsageDesc\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tmetricCh := make(chan prometheus.Metric)\n\tdoneCh := make(chan struct{})\n\n\tgo func() {\n\t\tfor m := range metricCh {\n\t\t\tch <- m.Desc()\n\t\t}\n\t\tclose(doneCh)\n\t}()\n\n\te.Collect(metricCh)\n\tclose(metricCh)\n\t<-doneCh\n}", "func (m *metricMap) Describe(ch chan<- *Desc) {\n\tch <- m.desc\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range e.serverMetrics {\n\t\tch <- m\n\t}\n\tch <- solaceUp\n}", "func (c *VMCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range c.getMetrics() {\n\t\tch <- m.Desc()\n\t}\n}", "func (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, d := range descriptors {\n\t\tch <- d\n\t}\n}", "func (o *requestMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tch <- o.desc\n}", "func (n LXCCollector) Describe(ch chan<- *prometheus.Desc) {\n\tscrapeDurations.Describe(ch)\n}", "func (c *ComputeCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Instances\n\tch <- c.ForwardingRules\n}", "func (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tc.config.getAllDescs(ch)\n}", "func (c *KubernetesCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Up\n\tch <- c.NodePools\n\tch <- c.Nodes\n}", "func (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- scrapeDurationDesc\n\tpower.Describe(ch)\n\tthermal.Describe(ch)\n}", "func (c *prometheusCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.maxOpenConnections\n\tch <- c.openConnections\n\tch <- c.inUse\n\tch <- c.idle\n\tch <- c.waitCount\n\tch <- c.waitDuration\n\tch <- c.maxIdleClosed\n\tch <- c.maxIdleTimeClosed\n\tch <- c.maxLifetimeClosed\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\t// We cannot know in advance what metrics the exporter will generate\n\t// from clickhouse. So we use the poor man's describe method: Run a collect\n\t// and send the descriptors of all the collected metrics.\n\n\tmetricCh := make(chan prometheus.Metric)\n\tdoneCh := make(chan struct{})\n\n\tgo func() {\n\t\tfor m := range metricCh {\n\t\t\tch <- m.Desc()\n\t\t}\n\t\tclose(doneCh)\n\t}()\n\n\te.Collect(metricCh)\n\tclose(metricCh)\n\t<-doneCh\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- metric_uptime.Desc()\n\tch <- nomad_up.Desc()\n\tch <- metric_request_response_time_total.Desc()\n\tch <- metric_request_response_time_avg.Desc()\n\n\tfor _, metric := range metric_request_status_count_current {\n\t\tch <- metric.Desc()\n\t}\n\tfor _, metric := range metric_request_status_count_total {\n\t\tch <- metric.Desc()\n\t}\n}", "func (c *ImageCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Active\n\tch <- c.ImageSize\n\tch <- c.DiskSize\n\tch <- c.Created\n\tch <- c.Deprecated\n}", "func (coll WmiCollector) Describe(ch chan<- *prometheus.Desc) {\n\tdefer trace()()\n\tscrapeDurations.Describe(ch)\n}", "func (o *OSDCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Describe(ch)\n\t}\n\tch <- o.OSDDownDesc\n\tch <- o.ScrubbingStateDesc\n\tch <- o.PGObjectsRecoveredDesc\n}", "func (o *OSDCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Describe(ch)\n\t}\n\tch <- o.ScrubbingStateDesc\n}", "func (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, co := range c.collectors {\n\t\tco.describe(ch)\n\t}\n}", "func (c *PostfixQueueCollector) Describe(ch chan<- *prometheus.Desc) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ageSecondsHistogram.Describe(ch)\n\tc.sizeBytesHistogram.Describe(ch)\n\tc.scrapeDurationGauge.Describe(ch)\n\tc.scrapeSuccessGauge.Describe(ch)\n}", "func (c *MosquittoCounter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Desc\n}", "func (a *AttunityCollector) Describe(ch chan<- *prometheus.Desc) {\n\t// Hi I do nothing\n}", "func (c *Collector) Describe(ch chan<- *prometheus.Desc) {\n\tprometheus.DescribeByCollect(c, ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.withCollectors(func(cs []prometheus.Collector) {\n\t\tfor _, c := range cs {\n\t\t\tc.Describe(ch)\n\t\t}\n\t})\n}", "func (sc *SlurmCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, element := range sc.descPtrMap {\n\t\tch <- element\n\t}\n}", "func (coll WmiCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- scrapeDurationDesc\n\tch <- scrapeSuccessDesc\n}", "func (c *TeamsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.totalTeamsGaugeDesc\n}", "func (c *InterfacesCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range c.collectors() {\n\t\tm.Describe(ch)\n\t}\n}", "func (m *ClientMetrics) Describe(ch chan<- *prom.Desc) {\n\tm.clientStartedCounter.Describe(ch)\n\tm.clientHandledCounter.Describe(ch)\n\tm.clientStreamMsgReceived.Describe(ch)\n\tm.clientStreamMsgSent.Describe(ch)\n\tif m.clientHandledHistogramEnabled {\n\t\tm.clientHandledHistogram.Describe(ch)\n\t}\n}", "func (c *MetricsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.verify\n}", "func (n NodeCollector) Describe(ch chan<- *prometheus.Desc) {\n\tscrapeDurations.Describe(ch)\n}", "func (c *Client) Describe(ch chan<- *prometheus.Desc) {\n\tc.metrics.functionInvocation.Describe(ch)\n\tc.metrics.queueHistogram.Describe(ch)\n\tc.metrics.functionsHistogram.Describe(ch)\n\tc.metrics.serviceReplicasGauge.Describe(ch)\n\tc.metrics.functionInvocationStarted.Describe(ch)\n}", "func (collector *Collector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- collector.incidentsCreatedCount\n}", "func (c *SecurityGroupCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Defined\n\tch <- c.EnableDefault\n\tch <- c.ProjectDefault\n\tch <- c.Stateful\n\tch <- c.InboundDefault\n\tch <- c.OutboundDefault\n\tch <- c.Servers\n\tch <- c.Created\n\tch <- c.Modified\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- systemStatus\n\tch <- systemTemperature\n\tch <- systemPowerStatus\n\tch <- systemFanStatus\n\tch <- systemCPUFanStatus\n\tch <- systemUpgradeAvailable\n\n\tch <- memTotalSwap\n\tch <- memAvailSwap\n\tch <- memTotalReal\n\tch <- memAvailReal\n\tch <- memTotalFree\n\tch <- memShared\n\tch <- memBuffer\n\tch <- memCached\n\n\tch <- loadShort\n\tch <- loadMid\n\tch <- loadLong\n\n\tch <- cpuUser\n\tch <- cpuNice\n\tch <- cpuSystem\n\tch <- cpuIdle\n\tch <- cpuWait\n\tch <- cpuKernel\n\tch <- cpuInterrupt\n\n\tch <- netIn\n\tch <- netOut\n}", "func (c *Collector) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, scraper := range c.Scrapers {\n\t\tfor _, metric := range scraper.Metrics {\n\t\t\tch <- metric.metric\n\t\t}\n\t}\n}", "func (m *MetricVec) Describe(ch chan<- *Desc) {\n\tch <- m.desc\n}", "func (collector *OpenweatherCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\t//Update this section with the each metric you create for a given collector\n\tch <- collector.temperatureMetric\n\tch <- collector.humidity\n\tch <- collector.feelslike\n\tch <- collector.pressure\n\tch <- collector.windspeed\n\tch <- collector.rain1h\n\tch <- collector.winddegree\n\tch <- collector.cloudiness\n\tch <- collector.sunrise\n\tch <- collector.sunset\n\tch <- collector.currentconditions\n}", "func (c *PTVMetricsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tdefer timeTrack(time.Now(), \"PTVMetricsCollector.Describe\")\n\n\tc.metrics.Describe(ch)\n}", "func (n DellHWCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- scrapeDurationDesc\n\tch <- scrapeSuccessDesc\n}", "func (c *solarCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\t// Describe the Collector's member that are of type Desc\n\tds := []*prometheus.Desc{\n\t\tc.panelVoltage,\n\t}\n\n\tfor _, d := range ds {\n\t\tch <- d\n\t}\n\t// Describe the other types\n\tc.scrapeFailures.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tprometheus.DescribeByCollect(e, ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.cpuPercent.Describe(ch)\n\te.dataIO.Describe(ch)\n\te.logIO.Describe(ch)\n\te.memoryPercent.Describe(ch)\n\te.workPercent.Describe(ch)\n\te.sessionPercent.Describe(ch)\n\te.storagePercent.Describe(ch)\n\te.dbUp.Describe(ch)\n\te.up.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.statusNightscout.Describe(ch)\n}", "func (c *transportNodeCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.edgeClusterMembership\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, cc := range e.collectors {\n\t\tcc.Describe(ch)\n\t}\n}", "func (t *TimestampCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- t.Description\n}", "func (c *StorageDomainCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- upDesc\n\tch <- masterDesc\n\tch <- availableDesc\n\tch <- usedDesc\n\tch <- committedDesc\n}", "func (c *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, cc := range c.collectors {\n\t\tcc.Describe(ch)\n\t}\n}", "func (c *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, cc := range c.collectors {\n\t\tcc.Describe(ch)\n\t}\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- domainsBeingBlocked\n\tch <- dnsQueries\n\tch <- adsBlocked\n\tch <- adsPercentage\n\tch <- domainsOverTime\n\tch <- adsOverTime\n\tch <- topQueries\n\tch <- topAds\n\tch <- topSources\n\tch <- queryTypes\n}", "func (c *CephExporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, cc := range c.collectors {\n\t\tcc.Describe(ch)\n\t}\n}", "func (pc *PrometheusCollector) Describe(ch chan<- *prometheus.Desc) {\n\tprometheus.DescribeByCollect(pc, ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.up.Describe(ch)\n\te.totalScrapes.Describe(ch)\n\te.exchangeStatus.Describe(ch)\n\te.ltp.Describe(ch)\n\te.bestBid.Describe(ch)\n\te.bestAsk.Describe(ch)\n\te.bestBidSize.Describe(ch)\n\te.bestAskSize.Describe(ch)\n\te.totalBidDepth.Describe(ch)\n\te.totalAskDepth.Describe(ch)\n\te.volume.Describe(ch)\n\te.volumeByProduct.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range replicationMetrics {\n\t\tch <- m\n\t}\n\tfor _, m := range securityMetrics {\n\t\tch <- m\n\t}\n\tfor _, m := range storageMetrics {\n\t\tch <- m\n\t}\n\tfor _, m := range systemMetrics {\n\t\tch <- m\n\t}\n\tch <- artifactoryUp\n\tch <- e.totalScrapes.Desc()\n\tch <- e.jsonParseFailures.Desc()\n}", "func (uc *UpgradeCollector) Describe(ch chan<- *prometheus.Desc) {\n\t// .spec\n\tch <- uc.managedMetrics.upgradeAt\n\tch <- uc.managedMetrics.pdbTimeout\n\n\t// .status\n\tch <- uc.managedMetrics.startTime\n\tch <- uc.managedMetrics.completeTime\n\n\t// .status.conditions[]\n\tch <- uc.managedMetrics.sendStartedNotification\n\tch <- uc.managedMetrics.preHealthCheck\n\tch <- uc.managedMetrics.extDepAvailCheck\n\tch <- uc.managedMetrics.scaleUpExtraNodes\n\tch <- uc.managedMetrics.controlPlaneMaintWindow\n\tch <- uc.managedMetrics.commenceUpgrade\n\tch <- uc.managedMetrics.controlPlaneUpgraded\n\tch <- uc.managedMetrics.removeControlPlaneMaint\n\tch <- uc.managedMetrics.workersMaintWindow\n\tch <- uc.managedMetrics.allWorkerNodesUpgraded\n\tch <- uc.managedMetrics.removeExtraScaledNodes\n\tch <- uc.managedMetrics.removeMaintWindow\n\tch <- uc.managedMetrics.postClusterHealthCheck\n\tch <- uc.managedMetrics.sendCompletedNotification\n}", "func (collector *atlassianUPMCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- collector.atlassianUPMTimeMetric\n\tch <- collector.atlassianUPMUpMetric\n\tch <- collector.atlassianUPMPlugins\n\tch <- collector.atlassianUPMVersionsMetric\n}", "func (c *OSCollector) Describe(ch chan<- *prometheus.Desc) {\n\n\tch <- c.PhysicalMemoryFreeBytes\n\tch <- c.PagingFreeBytes\n\tch <- c.VirtualMemoryFreeBytes\n\tch <- c.ProcessesMax\n\tch <- c.ProcessMemoryMaxBytes\n\tch <- c.Processes\n\tch <- c.Users\n\tch <- c.PagingMaxBytes\n\tch <- c.VirtualMemoryBytes\n\tch <- c.VisibleMemoryBytes\n}", "func (e *ebpfConntracker) Describe(ch chan<- *prometheus.Desc) {\n\tch <- conntrackerTelemetry.registersTotal\n}", "func (c *PricingCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Image\n\tch <- c.FloatingIP\n\tch <- c.Traffic\n\tch <- c.ServerBackup\n\tch <- c.Volume\n\tch <- c.Servers\n\tch <- c.LoadBalancers\n}", "func (c *SpeakerDeckCollector) Describe(channel chan<- *prometheus.Desc) {\n\tchannel <- c.duration\n\tchannel <- c.state\n\tchannel <- c.stars\n\tchannel <- c.views\n}", "func (p *plug) Describe(ch chan<- *prometheus.Desc) {\n\tp.doStats(ch, doDesc)\n}", "func (e *UwsgiExporter) Describe(ch chan<- *prometheus.Desc) {\n\te.uwsgiUp.Describe(ch)\n\te.scrapeDurations.Describe(ch)\n\n\tfor _, descs := range e.descriptorsMap {\n\t\tfor _, desc := range descs {\n\t\t\tch <- desc\n\t\t}\n\t}\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- up\n\tch <- clusterServers\n\tch <- clusterLeader\n\tch <- nodeCount\n\tch <- memberStatus\n\tch <- memberWanStatus\n\tch <- serviceCount\n\tch <- serviceNodesHealthy\n\tch <- nodeChecks\n\tch <- serviceChecks\n\tch <- keyValues\n\tch <- serviceTag\n\tch <- serviceCheckNames\n}", "func (o *observer) Describe(ch chan<- *prometheus.Desc) {\n\to.updateError.Describe(ch)\n\to.verifyError.Describe(ch)\n\to.expiration.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- e.poolUsage.Desc()\n\tch <- e.providersOnline.Desc()\n\tch <- e.providersFaulted.Desc()\n}", "func (c *DebugFsStatCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.hits\n\tch <- c.misses\n}", "func (c *ledCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.brightness\n\tch <- c.maxBrightness\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- e.up.Desc()\n\n\te.authCacheHits.Describe(ch)\n\te.authCacheMisses.Describe(ch)\n\te.databaseReads.Describe(ch)\n\te.databaseWrites.Describe(ch)\n\te.openDatabases.Describe(ch)\n\te.openOsFiles.Describe(ch)\n\te.requestTime.Describe(ch)\n\n\te.httpdStatusCodes.Describe(ch)\n\te.httpdRequestMethods.Describe(ch)\n\n\te.bulkRequests.Describe(ch)\n\te.clientsRequestingChanges.Describe(ch)\n\te.requests.Describe(ch)\n\te.temporaryViewReads.Describe(ch)\n\te.viewReads.Describe(ch)\n\n\te.diskSize.Describe(ch)\n\te.dataSize.Describe(ch)\n\te.diskSizeOverhead.Describe(ch)\n\n\te.activeTasks.Describe(ch)\n\te.activeTasksDatabaseCompaction.Describe(ch)\n\te.activeTasksViewCompaction.Describe(ch)\n\te.activeTasksIndexer.Describe(ch)\n\te.activeTasksReplication.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, desc := range junosDesc {\n\t\tch <- desc\n\t}\n}", "func (h *Metrics) Describe(in chan<- *prometheus.Desc) {\n\th.duration.Describe(in)\n\th.totalRequests.Describe(in)\n\th.requestSize.Describe(in)\n\th.responseSize.Describe(in)\n\th.handlerStatuses.Describe(in)\n\th.responseTime.Describe(in)\n}", "func (w *Writer) Describe(ch chan<- *prometheus.Desc) {\n\tw.kafkaWriteStatus.Describe(ch)\n\tw.queuedForWrites.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\te.up.Describe(ch)\n\te.scrapeDuration.Describe(ch)\n\te.failedScrapes.Describe(ch)\n\te.totalScrapes.Describe(ch)\n\tch <- e.priceDesc\n\tch <- e.openDesc\n\tch <- e.detailsDesc\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- e.up.Desc()\n\n\tfor _, vec := range e.counters {\n\t\tvec.Describe(ch)\n\t}\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Describe(ch)\n\t}\n}", "func (*noOpConntracker) Describe(ch chan<- *prometheus.Desc) {}", "func (c *grpcClientManagerCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- connectionStateDesc\n}", "func (c *NFSCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.Up\n\tch <- c.NFSInfo\n\tch <- c.DiskFree\n\tch <- c.NICInfo\n\tch <- c.NICReceive\n\tch <- c.NICSend\n\n\tch <- c.MaintenanceScheduled\n\tch <- c.MaintenanceInfo\n\tch <- c.MaintenanceStartTime\n\tch <- c.MaintenanceEndTime\n}", "func (e *exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- retrieveDurationDesc\n\tch <- retrieveSuccessDesc\n}", "func (c *analysisRunCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- descAnalysisRunInfo\n}", "func (m *ClientMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tm.clientHandledSummary.Describe(ch)\n}", "func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range e.gaugeVecs {\n\t\tm.Describe(ch)\n\t}\n}", "func (c *StatsCollector) Describe(descriptionChannel chan<- *prometheus.Desc) {\n\t// DescribeByCollect is a helper to implement the Describe method of a custom\n\t// Collector. It collects the metrics from the provided Collector and sends\n\t// their descriptors to the provided channel.\n\tprometheus.DescribeByCollect(c, descriptionChannel)\n}", "func (c *ImageCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.MinDiskSize\n}" ]
[ "0.821909", "0.81316125", "0.8063887", "0.80625445", "0.80529416", "0.80204767", "0.79817647", "0.79682547", "0.7951495", "0.7947539", "0.7913986", "0.78714305", "0.7863369", "0.78524923", "0.7849679", "0.78386784", "0.77726656", "0.7728355", "0.77277595", "0.77267617", "0.7721136", "0.77172804", "0.76838624", "0.76720977", "0.76646495", "0.765001", "0.7645362", "0.7643059", "0.76363283", "0.762702", "0.76262087", "0.7618892", "0.7616965", "0.7610202", "0.75920296", "0.75889343", "0.75795263", "0.7577178", "0.7564479", "0.75598806", "0.7541856", "0.75375205", "0.75304097", "0.7520786", "0.7516575", "0.7513191", "0.75107247", "0.74965596", "0.74927115", "0.74888724", "0.7484293", "0.7480378", "0.7478396", "0.7472037", "0.7471783", "0.74699926", "0.7465178", "0.7463066", "0.7455988", "0.74389184", "0.74142015", "0.7413771", "0.7413181", "0.7411067", "0.7407381", "0.7405012", "0.7405012", "0.73948205", "0.7393534", "0.73920816", "0.73917073", "0.73819387", "0.7365238", "0.7343064", "0.7338356", "0.7335179", "0.73164487", "0.7305448", "0.73009956", "0.7299527", "0.72907287", "0.7262534", "0.72619176", "0.72590363", "0.72533405", "0.7250026", "0.72498846", "0.72483325", "0.72465587", "0.72395176", "0.7237799", "0.7231751", "0.722222", "0.72214997", "0.7220443", "0.7213423", "0.72019464", "0.7201689", "0.7198989", "0.71939784" ]
0.72990876
80
Collect read the values of the metrics and passes them to the ch channel. It implements collector interface
func (pc *PBSCollector) Collect(ch chan<- prometheus.Metric) { pc.mutex.Lock() defer pc.mutex.Unlock() log.Debugf("Time since last scrape: %f seconds", time.Since(pc.lastScrape).Seconds()) if time.Since(pc.lastScrape).Seconds() > float64(pc.scrapeInterval) { pc.updateDynamicJobIds() var err error pc.sshClient, err = pc.sshConfig.NewClient() if err != nil { log.Errorf("Creating SSH client: %s", err.Error()) return } defer pc.sshClient.Close() log.Infof("Collecting metrics from PBS...") pc.trackedJobs = make(map[string]bool) if pc.targetJobIds != "" { pc.collectJobs(ch) } if !pc.skipInfra { pc.collectQueues(ch) } pc.lastScrape = time.Now() } pc.updateMetrics(ch) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *ClientMetrics) Collect(ch chan<- prom.Metric) {\n\tm.clientStartedCounter.Collect(ch)\n\tm.clientHandledCounter.Collect(ch)\n\tm.clientStreamMsgReceived.Collect(ch)\n\tm.clientStreamMsgSent.Collect(ch)\n\tif m.clientHandledHistogramEnabled {\n\t\tm.clientHandledHistogram.Collect(ch)\n\t}\n}", "func (o *requestMetrics) Collect(ch chan<- prometheus.Metric) {\n\tmetricFamilies, err := o.stStore.GetPromDirectMetrics()\n\tif err != nil {\n\t\tklog.Errorf(\"fetch prometheus metrics failed: %v\", err)\n\t\treturn\n\t}\n\to.handleMetrics(metricFamilies, ch)\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tc.m.Lock()\n\tfor _, m := range c.metrics {\n\t\tch <- m.metric\n\t}\n\tc.m.Unlock()\n}", "func (c *VMCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range c.getMetrics() {\n\t\tch <- m\n\t}\n}", "func (c *goCollector) Collect(ch chan<- Metric) {\n\t// Collect base non-memory metrics.\n\tc.base.Collect(ch)\n\n\tif len(c.sampleBuf) == 0 {\n\t\treturn\n\t}\n\n\t// Collect must be thread-safe, so prevent concurrent use of\n\t// sampleBuf elements. Just read into sampleBuf but write all the data\n\t// we get into our Metrics or MemStats.\n\t//\n\t// This lock also ensures that the Metrics we send out are all from\n\t// the same updates, ensuring their mutual consistency insofar as\n\t// is guaranteed by the runtime/metrics package.\n\t//\n\t// N.B. This locking is heavy-handed, but Collect is expected to be called\n\t// relatively infrequently. Also the core operation here, metrics.Read,\n\t// is fast (O(tens of microseconds)) so contention should certainly be\n\t// low, though channel operations and any allocations may add to that.\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t// Populate runtime/metrics sample buffer.\n\tmetrics.Read(c.sampleBuf)\n\n\t// Collect all our runtime/metrics user chose to expose from sampleBuf (if any).\n\tfor i, metric := range c.rmExposedMetrics {\n\t\t// We created samples for exposed metrics first in order, so indexes match.\n\t\tsample := c.sampleBuf[i]\n\n\t\t// N.B. switch on concrete type because it's significantly more efficient\n\t\t// than checking for the Counter and Gauge interface implementations. In\n\t\t// this case, we control all the types here.\n\t\tswitch m := metric.(type) {\n\t\tcase *counter:\n\t\t\t// Guard against decreases. This should never happen, but a failure\n\t\t\t// to do so will result in a panic, which is a harsh consequence for\n\t\t\t// a metrics collection bug.\n\t\t\tv0, v1 := m.get(), unwrapScalarRMValue(sample.Value)\n\t\t\tif v1 > v0 {\n\t\t\t\tm.Add(unwrapScalarRMValue(sample.Value) - m.get())\n\t\t\t}\n\t\t\tm.Collect(ch)\n\t\tcase *gauge:\n\t\t\tm.Set(unwrapScalarRMValue(sample.Value))\n\t\t\tm.Collect(ch)\n\t\tcase *batchHistogram:\n\t\t\tm.update(sample.Value.Float64Histogram(), c.exactSumFor(sample.Name))\n\t\t\tm.Collect(ch)\n\t\tdefault:\n\t\t\tpanic(\"unexpected metric type\")\n\t\t}\n\t}\n\n\tif c.msMetricsEnabled {\n\t\t// ms is a dummy MemStats that we populate ourselves so that we can\n\t\t// populate the old metrics from it if goMemStatsCollection is enabled.\n\t\tvar ms runtime.MemStats\n\t\tmemStatsFromRM(&ms, c.sampleMap)\n\t\tfor _, i := range c.msMetrics {\n\t\t\tch <- MustNewConstMetric(i.desc, i.valType, i.eval(&ms))\n\t\t}\n\t}\n}", "func (h *Metrics) Collect(in chan<- prometheus.Metric) {\n\th.duration.Collect(in)\n\th.totalRequests.Collect(in)\n\th.requestSize.Collect(in)\n\th.responseSize.Collect(in)\n\th.handlerStatuses.Collect(in)\n\th.responseTime.Collect(in)\n}", "func (c *OrchestratorCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects\n\tdefer c.mutex.Unlock()\n\n\tstats, err := c.orchestratorClient.GetMetrics()\n\tif err != nil {\n\t\tc.upMetric.Set(serviceDown)\n\t\tch <- c.upMetric\n\t\tlog.Printf(\"Error getting Orchestrator stats: %v\", err)\n\t\treturn\n\t}\n\n\tc.upMetric.Set(serviceUp)\n\tch <- c.upMetric\n\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"cluter_size\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Status.Details.AvailableNodes)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_active_node\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.IsActiveNode))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"problems\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Problems)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"last_failover_id\"],\n\t\tprometheus.CounterValue, float64(stats.LastFailoverID))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_healthy\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.Healthy))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"failed_seeds\"],\n\t\tprometheus.CounterValue, float64(stats.FailedSeeds))\n}", "func (m *Monitoring) collect() {\n\tfor {\n\t\tevents, ok := <-m.ch\n\t\tif !ok {\n\t\t\tlog.Printf(\"event channel is closed\")\n\t\t\treturn\n\t\t}\n\n\t\tif err := m.w.Write(context.Background(), events); err != nil {\n\t\t\tlog.Printf(\"failed to write metric events %+v: %v\", events, err)\n\t\t}\n\t}\n\n}", "func (*noOpConntracker) Collect(ch chan<- prometheus.Metric) {}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping ingestor: %s\", err)\n\t}\n\treturn\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tglog.Error(fmt.Sprintf(\"Error collecting stats: %s\", err))\n\t}\n\treturn\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tc.mut.RLock()\n\tdefer c.mut.RUnlock()\n\n\tif c.inner != nil {\n\t\tc.inner.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tlog.Infof(\"Syno exporter starting\")\n\tif e.Client == nil {\n\t\tlog.Errorf(\"Syno client not configured.\")\n\t\treturn\n\t}\n\terr := e.Client.Connect()\n\tif err != nil {\n\t\tlog.Errorln(\"Can't connect to Synology for SNMP: %s\", err)\n\t\treturn\n\t}\n\tdefer e.Client.SNMP.Conn.Close()\n\n\te.collectSystemMetrics(ch)\n\te.collectCPUMetrics(ch)\n\te.collectLoadMetrics(ch)\n\te.collectMemoryMetrics(ch)\n\te.collectNetworkMetrics(ch)\n\te.collectDiskMetrics(ch)\n\n\tlog.Infof(\"Syno exporter finished\")\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\t// Protect metrics from concurrent collects.\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\t// Scrape metrics from Tankerkoenig API.\n\tif err := e.scrape(ch); err != nil {\n\t\te.logger.Printf(\"error: cannot scrape tankerkoenig api: %v\", err)\n\t}\n\n\t// Collect metrics.\n\te.up.Collect(ch)\n\te.scrapeDuration.Collect(ch)\n\te.failedScrapes.Collect(ch)\n\te.totalScrapes.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tif err := e.scrape(); err != nil {\n\t\tlog.Error(err)\n\t\tnomad_up.Set(0)\n\t\tch <- nomad_up\n\t\treturn\n\t}\n\n\tch <- nomad_up\n\tch <- metric_uptime\n\tch <- metric_request_response_time_total\n\tch <- metric_request_response_time_avg\n\n\tfor _, metric := range metric_request_status_count_current {\n\t\tch <- metric\n\t}\n\tfor _, metric := range metric_request_status_count_total {\n\t\tch <- metric\n\t}\n}", "func (c *filebeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\te.scrape()\n\n\te.up.Collect(ch)\n\te.totalScrapes.Collect(ch)\n\te.exchangeStatus.Collect(ch)\n\te.ltp.Collect(ch)\n\te.bestBid.Collect(ch)\n\te.bestAsk.Collect(ch)\n\te.bestBidSize.Collect(ch)\n\te.bestAskSize.Collect(ch)\n\te.totalBidDepth.Collect(ch)\n\te.totalAskDepth.Collect(ch)\n\te.volume.Collect(ch)\n\te.volumeByProduct.Collect(ch)\n}", "func (collector *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfilterMetricsByKind := func(kind string, orgMetrics []constMetric) (filteredMetrics []constMetric) {\n\t\tfor _, metric := range orgMetrics {\n\t\t\tif metric.kind == kind {\n\t\t\t\tfilteredMetrics = append(filteredMetrics, metric)\n\t\t\t}\n\t\t}\n\t\treturn filteredMetrics\n\t}\n\tcollector.defMetrics.reset()\n\tfor k := range collector.metrics {\n\t\tcounters := filterMetricsByKind(config.KeyMetricTypeCounter, collector.metrics[k])\n\t\tgauges := filterMetricsByKind(config.KeyMetricTypeGauge, collector.metrics[k])\n\t\thistograms := filterMetricsByKind(config.KeyMetricTypeHistogram, collector.metrics[k])\n\t\tcollectCounters(counters, collector.defMetrics, ch)\n\t\tcollectGauges(gauges, collector.defMetrics, ch)\n\t\tcollectHistograms(histograms, collector.defMetrics, ch)\n\t\tcollector.cache.Reset()\n\t}\n\tcollector.defMetrics.collectDefaultMetrics(ch)\n}", "func (c *metricbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping: %s\", err)\n\t}\n\treturn\n}", "func (c *StatsCollector) Collect(metricChannel chan<- prometheus.Metric) {\n\t// read all stats from Kamailio\n\tif completeStatMap, err := c.fetchStats(); err == nil {\n\t\t// and produce various prometheus.Metric for well-known stats\n\t\tproduceMetrics(completeStatMap, metricChannel)\n\t\t// produce prometheus.Metric objects for scripted stats (if any)\n\t\tconvertScriptedMetrics(completeStatMap, metricChannel)\n\t} else {\n\t\t// something went wrong\n\t\t// TODO: add a error metric\n\t\tlog.Error(\"Could not fetch values from kamailio\", err)\n\t}\n}", "func (c *CephExporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (m *ClientMetrics) Collect(ch chan<- prometheus.Metric) {\n\tm.clientHandledSummary.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar (\n\t\tdata *Data\n\t\terr error\n\t)\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.resetGaugeVecs() // Clean starting point\n\n\tvar endpointOfAPI []string\n\tif strings.HasSuffix(rancherURL, \"v3\") || strings.HasSuffix(rancherURL, \"v3/\") {\n\t\tendpointOfAPI = endpointsV3\n\t} else {\n\t\tendpointOfAPI = endpoints\n\t}\n\n\tcacheExpired := e.IsCacheExpired()\n\n\t// Range over the pre-configured endpoints array\n\tfor _, p := range endpointOfAPI {\n\t\tif cacheExpired {\n\t\t\tdata, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error getting JSON from URL %s\", p)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.cache[p] = data\n\t\t} else {\n\t\t\td, ok := e.cache[p]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata = d\n\t\t}\n\n\t\tif err := e.processMetrics(data, p, e.hideSys, ch); err != nil {\n\t\t\tlog.Errorf(\"Error scraping rancher url: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Metrics successfully processed for %s\", p)\n\t}\n\n\tif cacheExpired {\n\t\te.RenewCache()\n\t}\n\n\tfor _, m := range e.gaugeVecs {\n\t\tm.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.withCollectors(func(cs []prometheus.Collector) {\n\t\tfor _, c := range cs {\n\t\t\tc.Collect(ch)\n\t\t}\n\t})\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tok := e.collectPeersMetric(ch)\n\tok = e.collectLeaderMetric(ch) && ok\n\tok = e.collectNodesMetric(ch) && ok\n\tok = e.collectMembersMetric(ch) && ok\n\tok = e.collectMembersWanMetric(ch) && ok\n\tok = e.collectServicesMetric(ch) && ok\n\tok = e.collectHealthStateMetric(ch) && ok\n\tok = e.collectKeyValues(ch) && ok\n\n\tif ok {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 1.0,\n\t\t)\n\t} else {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 0.0,\n\t\t)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\t// Reset metrics.\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tfor _, vec := range e.counters {\n\t\tvec.Reset()\n\t}\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\te.up.Set(0)\n\t\tlog.Printf(\"Error while querying Elasticsearch: %v\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read ES response body: %v\", err)\n\t\te.up.Set(0)\n\t\treturn\n\t}\n\n\te.up.Set(1)\n\n\tvar all_stats NodeStatsResponse\n\terr = json.Unmarshal(body, &all_stats)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshal JSON into struct: %v\", err)\n\t\treturn\n\t}\n\n\t// Regardless of whether we're querying the local host or the whole\n\t// cluster, here we can just iterate through all nodes found.\n\n\tfor node, stats := range all_stats.Nodes {\n\t\tlog.Printf(\"Processing node %v\", node)\n\t\t// GC Stats\n\t\tfor collector, gcstats := range stats.JVM.GC.Collectors {\n\t\t\te.counters[\"jvm_gc_collection_count\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionCount))\n\t\t\te.counters[\"jvm_gc_collection_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionTime))\n\t\t}\n\n\t\t// Breaker stats\n\t\tfor breaker, bstats := range stats.Breakers {\n\t\t\te.gauges[\"breakers_estimated_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.EstimatedSize))\n\t\t\te.gauges[\"breakers_limit_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.LimitSize))\n\t\t}\n\n\t\t// JVM Memory Stats\n\t\te.gauges[\"jvm_mem_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapCommitted))\n\t\te.gauges[\"jvm_mem_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapUsed))\n\t\te.gauges[\"jvm_mem_heap_max_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapMax))\n\t\te.gauges[\"jvm_mem_non_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapCommitted))\n\t\te.gauges[\"jvm_mem_non_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapUsed))\n\n\t\t// Indices Stats\n\t\te.gauges[\"indices_fielddata_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.Evictions))\n\t\te.gauges[\"indices_fielddata_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.MemorySize))\n\t\te.gauges[\"indices_filter_cache_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.Evictions))\n\t\te.gauges[\"indices_filter_cache_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.MemorySize))\n\n\t\te.gauges[\"indices_docs_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Count))\n\t\te.gauges[\"indices_docs_deleted\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Deleted))\n\n\t\te.gauges[\"indices_segments_memory_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Segments.Memory))\n\n\t\te.gauges[\"indices_store_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.Size))\n\t\te.counters[\"indices_store_throttle_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.ThrottleTime))\n\n\t\te.counters[\"indices_flush_total\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Total))\n\t\te.counters[\"indices_flush_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Time))\n\n\t\t// Transport Stats\n\t\te.counters[\"transport_rx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxCount))\n\t\te.counters[\"transport_rx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxSize))\n\t\te.counters[\"transport_tx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxCount))\n\t\te.counters[\"transport_tx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxSize))\n\t}\n\n\t// Report metrics.\n\tch <- e.up\n\n\tfor _, vec := range e.counters {\n\t\tvec.Collect(ch)\n\t}\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\tfor _, cc := range e.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *beatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (c *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, s := range c.status {\n\t\ts.RLock()\n\t\tdefer s.RUnlock()\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyRestore),\n\t\t\t\"verify_restore\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyDiff),\n\t\t\t\"verify_diff\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyChecksum),\n\t\t\t\"verify_checksum\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t}\n\n}", "func (c *OSCollector) Collect(ch chan<- prometheus.Metric) {\n\tif desc, err := c.collect(ch); err != nil {\n\t\tlog.Println(\"[ERROR] failed collecting os metrics:\", desc, err)\n\t\treturn\n\t}\n}", "func (coll WmiCollector) Collect(ch chan<- prometheus.Metric) {\n\texecute(coll.collector, ch)\n}", "func (m httpReferenceDiscoveryMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.firstPacket.Collect(metrics)\n\tm.totalTime.Collect(metrics)\n\tm.advertisedRefs.Collect(metrics)\n}", "func (p *plug) Collect(ch chan<- prometheus.Metric) {\n\tp.doStats(ch, doMetric)\n}", "func (c *auditdCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (c *Client) Collect(ch chan<- prometheus.Metric) {\n\tc.metrics.functionInvocation.Collect(ch)\n\tc.metrics.functionsHistogram.Collect(ch)\n\tc.metrics.queueHistogram.Collect(ch)\n\tc.metrics.functionInvocationStarted.Collect(ch)\n\tc.metrics.serviceReplicasGauge.Reset()\n\tfor _, service := range c.services {\n\t\tvar serviceName string\n\t\tif len(service.Namespace) > 0 {\n\t\t\tserviceName = fmt.Sprintf(\"%s.%s\", service.Name, service.Namespace)\n\t\t} else {\n\t\t\tserviceName = service.Name\n\t\t}\n\t\tc.metrics.serviceReplicasGauge.\n\t\t\tWithLabelValues(serviceName).\n\t\t\tSet(float64(service.Replicas))\n\t}\n\tc.metrics.serviceReplicasGauge.Collect(ch)\n}", "func (p *Metrics) Collect(c chan<- prometheus.Metric) {\n\t//rlockCollect(c,&p.mucout,p.counters)\n\t//rlockCollect(c,&p.mugau,p.gauges)\n\t//rlockCollect(c,&p.muhist,p.historams)\n\t//rlockCollect(c,&p.musumm,p.summaries)\n\tp.rlockCollectCounter(c)\n\tp.rlockCollectGauge(c)\n\tp.rlockCollectHistorams(c)\n\tp.rlockCollectSummaries(c)\n}", "func (c *transportNodeCollector) Collect(ch chan<- prometheus.Metric) {\n\ttransportNodeMetrics := c.generateTransportNodeMetrics()\n\tfor _, metric := range transportNodeMetrics {\n\t\tch <- metric\n\t}\n}", "func (sc *SlurmCollector) Collect(ch chan<- prometheus.Metric) {\n\tsc.mutex.Lock()\n\tdefer sc.mutex.Unlock()\n\n\tlog.Debugf(\"Time since last scrape: %f seconds\", time.Since(sc.lastScrape).Seconds())\n\tif time.Since(sc.lastScrape).Seconds() > float64(sc.scrapeInterval) {\n\t\tsc.updateDynamicJobIds()\n\t\tvar err error\n\t\tsc.sshClient, err = sc.sshConfig.NewClient()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Creating SSH client: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer sc.sshClient.Close()\n\t\tlog.Infof(\"Collecting metrics from Slurm...\")\n\t\tsc.trackedJobs = make(map[string]bool)\n\t\tif sc.targetJobIds == \"\" {\n\t\t\t// sc.collectQueue()\n\t\t} else {\n\t\t\tsc.collectAcct()\n\t\t}\n\t\tif !sc.skipInfra {\n\t\t\tsc.collectInfo()\n\t\t}\n\t\tsc.lastScrape = time.Now()\n\t\tsc.delJobs()\n\n\t}\n\n\tsc.updateMetrics(ch)\n}", "func (e *exporter) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(e.Collectors))\n\tfor name, c := range e.Collectors {\n\t\tgo func(name string, c Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.zpool.getStatus()\n\te.poolUsage.Set(float64(e.zpool.capacity))\n\te.providersOnline.Set(float64(e.zpool.online))\n\te.providersFaulted.Set(float64(e.zpool.faulted))\n\n\tch <- e.poolUsage\n\tch <- e.providersOnline\n\tch <- e.providersFaulted\n}", "func (c *solarCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer c.mutex.Unlock()\n\tif err := c.collect(ch); err != nil {\n\t\tlog.Printf(\"Error getting solar controller data: %s\", err)\n\t\tc.scrapeFailures.Inc()\n\t\tc.scrapeFailures.Collect(ch)\n\t}\n\treturn\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.scrape(ch); err != nil {\n\t\tlog.Printf(\"Error scraping nightscout url: %s\", err)\n\t}\n\n\te.statusNightscout.Collect(ch)\n\n\treturn\n}", "func (c *interfaceCollector) Collect(client *rpc.Client, ch chan<- prometheus.Metric, labelValues []string) error {\n\tstats, err := c.interfaceStats(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, s := range stats {\n\t\tc.collectForInterface(s, ch, labelValues)\n\t}\n\n\treturn nil\n}", "func (pc *PrometheusCollector) Collect(ch chan<- prometheus.Metric) {\n\tpc.attempts.Collect(ch)\n\tpc.errors.Collect(ch)\n\tpc.successes.Collect(ch)\n\tpc.failures.Collect(ch)\n\tpc.rejects.Collect(ch)\n\tpc.shortCircuits.Collect(ch)\n\tpc.timeouts.Collect(ch)\n\tpc.fallbackSuccesses.Collect(ch)\n\tpc.fallbackFailures.Collect(ch)\n\tpc.totalDuration.Collect(ch)\n\tpc.runDuration.Collect(ch)\n}", "func (m *Client) Collect(ch chan<- prometheus.Metric) {\n\tm.storeMu.Lock()\n\tdefer m.storeMu.Unlock()\n\n\tch <- prometheus.MustNewConstMetric(m.storeValuesDesc, prometheus.GaugeValue, float64(len(m.store)))\n\n\tfor k, v := range m.store {\n\t\tch <- prometheus.MustNewConstMetric(m.storeSizesDesc, prometheus.GaugeValue, float64(len(v.value)), k)\n\t}\n}", "func (a collectorAdapter) Collect(ch chan<- prometheus.Metric) {\n\tif err := a.Update(ch); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to update collector: %v\", err))\n\t}\n}", "func (o *observer) Collect(ch chan<- prometheus.Metric) {\n\to.updateError.Collect(ch)\n\to.verifyError.Collect(ch)\n\to.expiration.Collect(ch)\n}", "func (collector *Metrics) Collect(ch chan<- prometheus.Metric) {\n\n\tcollectedIssues, err := fetchJiraIssues()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, issue := range collectedIssues.Issues {\n\t\tcreatedTimestamp := convertToUnixTime(issue.Fields.Created)\n\t\tch <- prometheus.MustNewConstMetric(collector.issue, prometheus.CounterValue, createdTimestamp, issue.Fields.Status.Name, issue.Fields.Project.Name, issue.Key, issue.Fields.Assignee.Name, issue.Fields.Location.Name, issue.Fields.Priority.Name, issue.Fields.Level.Name, issue.Fields.RequestType.Name, issue.Fields.Feedback, issue.Fields.Urgency.Name, issue.Fields.IssueType.Name, issue.Fields.Reporter.Name, issue.Fields.Satisfaction)\n\t}\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tif c.client == nil {\n\t\tsigChannel := make(chan os.Signal)\n\t\tsignal.Notify(sigChannel, os.Interrupt, syscall.SIGTERM)\n\t\tclientOptions := []hilink.Option{\n\t\t\thilink.URL(*c.options.Url),\n\t\t}\n\t\tif *c.options.Password != \"\" {\n\t\t\tclientOptions = append(clientOptions, hilink.Auth(*c.options.Username, *c.options.Password))\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"url\": *c.options.Url,\n\t\t\t\"user\": *c.options.Username,\n\t\t}).Debug(\"Connecting\")\n\t\tclient, err := hilink.NewClient(clientOptions...)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to contact device: %s\", err)\n\t\t}\n\t\tgo func() {\n\t\t\t<-sigChannel\n\t\t\tlog.Info(\"Stopping, disconnecting from device\")\n\t\t\tc.client.Disconnect()\n\t\t\tos.Exit(0)\n\t\t}()\n\t\tc.client = client\n\t\tdefer c.client.Disconnect()\n\t}\n\n\twg := sync.WaitGroup{}\n\tfor _, collector := range c.collectors {\n\t\tcol := collector\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tctx := &collectorContext{ch, c.client}\n\t\t\terr := col.collect(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n}", "func (p *promProducer) Collect(ch chan<- prometheus.Metric) {\n\tfor _, obj := range p.store.Objects() {\n\t\tmessage, ok := obj.(producers.MetricsMessage)\n\t\tif !ok {\n\t\t\tpromLog.Warnf(\"Unsupported message type %T\", obj)\n\t\t\tcontinue\n\t\t}\n\t\tdims := dimsToMap(message.Dimensions)\n\n\t\tfor _, d := range message.Datapoints {\n\t\t\tpromLog.Debugf(\"Processing datapoint %s\", d.Name)\n\t\t\tvar tagKeys []string\n\t\t\tvar tagVals []string\n\t\t\tfor k, v := range dims {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\t\t\tfor k, v := range d.Tags {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\n\t\t\tname := sanitizeName(d.Name)\n\t\t\tval, err := coerceToFloat(d.Value)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Bad datapoint value %q: %s\", d.Value, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdesc := prometheus.NewDesc(name, \"DC/OS Metrics Datapoint\", tagKeys, nil)\n\t\t\tmetric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, tagVals...)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Could not create Prometheus metric %s: %s\", name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpromLog.Debugf(\"Emitting datapoint %s\", name)\n\t\t\tch <- metric\n\t\t}\n\n\t}\n}", "func (c *SystemCollector) Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) error {\n\tif desc, err := c.collect(ctx, ch); err != nil {\n\t\t_ = level.Error(c.logger).Log(\"failed collecting system metrics\", \"desc\", desc, \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tresp, err := e.Pihole.GetMetrics()\n\tif err != nil {\n\t\tlog.Errorf(\"Pihole error: %s\", err.Error())\n\t\treturn\n\t}\n\tlog.Debugf(\"PiHole metrics: %#v\", resp)\n\tch <- prometheus.MustNewConstMetric(\n\t\tdomainsBeingBlocked, prometheus.CounterValue, float64(resp.DomainsBeingBlocked))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tdnsQueries, prometheus.CounterValue, float64(resp.DNSQueriesToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsBlocked, prometheus.CounterValue, float64(resp.AdsBlockedToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsPercentage, prometheus.CounterValue, float64(resp.AdsPercentageToday))\n\n\tfor k, v := range resp.Querytypes {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tqueryTypes, prometheus.CounterValue, v, k)\n\t}\n\tfor k, v := range resp.TopQueries {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopQueries, prometheus.CounterValue, float64(v), k)\n\t}\n\tfor k, v := range resp.TopAds {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopAds, prometheus.CounterValue, float64(v), k)\n\n\t}\n\tfor k, v := range resp.TopSources {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopSources, prometheus.CounterValue, float64(v), k)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup, result := e.scrape(ch)\n\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n\tch <- prometheus.MustNewConstMetric(iqAirUp, prometheus.GaugeValue, up)\n\tch <- prometheus.MustNewConstMetric(iqAirCO2, prometheus.GaugeValue, float64(result.CO2))\n\tch <- prometheus.MustNewConstMetric(iqAirP25, prometheus.GaugeValue, float64(result.P25))\n\tch <- prometheus.MustNewConstMetric(iqAirP10, prometheus.GaugeValue, float64(result.P10))\n\tch <- prometheus.MustNewConstMetric(iqAirTemp, prometheus.GaugeValue, float64(result.Temperature))\n\tch <- prometheus.MustNewConstMetric(iqAirHumidity, prometheus.GaugeValue, float64(result.Humidity))\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup := e.scrape(ch)\n\n\tch <- prometheus.MustNewConstMetric(artifactoryUp, prometheus.GaugeValue, up)\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n}", "func (r *RGWCollector) Collect(ch chan<- prometheus.Metric, version *Version) {\n\tif !r.background {\n\t\tr.logger.WithField(\"background\", r.background).Debug(\"collecting RGW GC stats\")\n\t\terr := r.collect()\n\t\tif err != nil {\n\t\t\tr.logger.WithField(\"background\", r.background).WithError(err).Error(\"error collecting RGW GC stats\")\n\t\t}\n\t}\n\n\tfor _, metric := range r.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n}", "func (c collector) Collect(ch chan<- prometheus.Metric) {\n\tvar wg sync.WaitGroup\n\n\t// We don't bail out on errors because those can happen if there is a race condition between\n\t// the destruction of a container and us getting to read the cgroup data. We just don't report\n\t// the values we don't get.\n\n\tcollectors := []func(string, *regexp.Regexp){\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tnuma, err := cgroups.GetNumaStats(cgroupPath(\"memory\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateNumaStatMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], numa)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect NUMA stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tmemory, err := cgroups.GetMemoryUsage(cgroupPath(\"memory\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateMemoryUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], memory)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect memory usage stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tmigrate, err := cgroups.GetCPUSetMemoryMigrate(cgroupPath(\"cpuset\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateMemoryMigrateMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], migrate)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect memory migration stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tcpuAcctUsage, err := cgroups.GetCPUAcctStats(cgroupPath(\"cpuacct\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateCPUAcctUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], cpuAcctUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect CPU accounting stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\thugeTlbUsage, err := cgroups.GetHugetlbUsage(cgroupPath(\"hugetlb\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateHugeTlbUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], hugeTlbUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect hugetlb stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t\tfunc(path string, re *regexp.Regexp) {\n\t\t\tdefer wg.Done()\n\t\t\tblkioDeviceUsage, err := cgroups.GetBlkioThrottleBytes(cgroupPath(\"blkio\", path))\n\t\t\tif err == nil {\n\t\t\t\tupdateBlkioDeviceUsageMetric(ch, re.FindStringSubmatch(filepath.Base(path))[0], blkioDeviceUsage)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"failed to collect blkio stats for %s: %v\", path, err)\n\t\t\t}\n\t\t},\n\t}\n\n\tcontainerIDRegexp := regexp.MustCompile(`[a-z0-9]{64}`)\n\n\tfor _, path := range walkCgroups() {\n\t\twg.Add(len(collectors))\n\t\tfor _, fn := range collectors {\n\t\t\tgo fn(path, containerIDRegexp)\n\t\t}\n\t}\n\n\t// We need to wait so that the response channel doesn't get closed.\n\twg.Wait()\n}", "func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) {\n\toomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState()\n\tfor host, oomCount := range oomCountByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.OOMCountDesc,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(oomCount),\n\t\t\thost,\n\t\t)\n\t}\n\tfor host, ramUsage := range ramUsageByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RAMUsageDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\tramUsage,\n\t\t\thost,\n\t\t)\n\t}\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.totalScrapes.Inc()\n\terr := c.getDadataBalance()\n\tif err != nil {\n\t\tc.failedBalanceScrapes.Inc()\n\t}\n\terr = c.getDadataStats()\n\tif err != nil {\n\t\tc.failedStatsScrapes.Inc()\n\t}\n\n\tch <- c.totalScrapes\n\tch <- c.failedBalanceScrapes\n\tch <- c.failedStatsScrapes\n\tch <- c.CurrentBalance\n\tch <- c.ServicesClean\n\tch <- c.ServicesMerging\n\tch <- c.ServicesSuggestions\n}", "func (o *OSDCollector) Collect(ch chan<- prometheus.Metric) {\n\tif err := o.collectOSDPerf(); err != nil {\n\t\tlog.Println(\"failed collecting osd perf stats:\", err)\n\t}\n\n\tif err := o.collectOSDDump(); err != nil {\n\t\tlog.Println(\"failed collecting osd dump:\", err)\n\t}\n\n\tif err := o.collectOSDDF(); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tif err := o.collectOSDTreeDown(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n\n\tif err := o.collectOSDScrubState(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd scrub state:\", err)\n\t}\n}", "func (c *TCPCollector) Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) error {\n\tif desc, err := c.collect(ctx, ch); err != nil {\n\t\t_ = level.Error(c.logger).Log(\"failed collecting tcp metrics\", \"desc\", desc, \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (pr *PeriodicReader) collect(ctx context.Context, method func(context.Context, data.Metrics) error) error {\n\tpr.lock.Lock()\n\tdefer pr.lock.Unlock()\n\n\t// The lock ensures that re-use of `pr.data` is successful, it\n\t// means that shutdown, flush, and ordinary collection are\n\t// exclusive. Note that shutdown will cancel a concurrent\n\t// (ordinary) export, while flush will wait for a concurrent\n\t// export.\n\tpr.data = pr.producer.Produce(&pr.data)\n\n\treturn method(ctx, pr.data)\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tsess, err := sessions.CreateAWSSession()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t// Init WaitGroup. Without a WaitGroup the channel we write\n\t// results to will close before the goroutines finish\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.Scrapers))\n\n\t// Iterate through all scrapers and invoke the scrape\n\tfor _, scraper := range c.Scrapers {\n\t\t// Wrape the scrape invocation in a goroutine, but we need to pass\n\t\t// the scraper into the function explicitly to re-scope the variable\n\t\t// the goroutine accesses. If we don't do this, we can sometimes hit\n\t\t// a case where the scraper reports results twice and the collector panics\n\t\tgo func(scraper *Scraper) {\n\t\t\t// Done call deferred until end of the scrape\n\t\t\tdefer wg.Done()\n\n\t\t\tlog.Debugf(\"Running scrape: %s\", scraper.ID)\n\t\t\tscrapeResults := scraper.Scrape(sess)\n\n\t\t\t// Iterate through scrape results and send the metric\n\t\t\tfor key, results := range scrapeResults {\n\t\t\t\tfor _, result := range results {\n\t\t\t\t\tch <- prometheus.MustNewConstMetric(scraper.Metrics[key].metric, result.Type, result.Value, result.Labels...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Debugf(\"Scrape completed: %s\", scraper.ID)\n\t\t}(scraper)\n\t}\n\t// Wait\n\twg.Wait()\n}", "func (p *Collector) Collect(c chan<- prometheus.Metric) {\n\tp.Sink.mu.Lock()\n\tdefer p.Sink.mu.Unlock()\n\n\texpire := p.Sink.expiration != 0\n\tnow := time.Now()\n\tfor k, v := range p.Sink.gauges {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.gauges, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.summaries {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.summaries, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.counters {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.counters, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n}", "func (collector *OpenweatherCollector) Collect(ch chan<- prometheus.Metric) {\n\t// Get Coords\n\tlatitude, longitude := geo.Get_coords(openstreetmap.Geocoder(), collector.Location)\n\n\t// Setup HTTP Client\n\tclient := &http.Client{\n\t\tTimeout: 1 * time.Second,\n\t}\n\n\t// Grab Metrics\n\tw, err := owm.NewCurrent(collector.DegreesUnit, collector.Language, collector.ApiKey, owm.WithHttpClient(client))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tlog.Infof(\"Collecting metrics from openweather API successful\")\n\t}\n\n\tw.CurrentByCoordinates(&owm.Coordinates{Longitude: longitude, Latitude: latitude})\n\n\t// Get Weather description out of Weather slice to pass as label\n\tvar weather_description string\n\tfor _, n := range w.Weather {\n\t\tweather_description = n.Description\n\t}\n\n\t//Write latest value for each metric in the prometheus metric channel.\n\t//Note that you can pass CounterValue, GaugeValue, or UntypedValue types here.\n\tch <- prometheus.MustNewConstMetric(collector.temperatureMetric, prometheus.GaugeValue, w.Main.Temp, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.humidity, prometheus.GaugeValue, float64(w.Main.Humidity), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.feelslike, prometheus.GaugeValue, w.Main.FeelsLike, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.pressure, prometheus.GaugeValue, w.Main.Pressure, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.windspeed, prometheus.GaugeValue, w.Wind.Speed, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.rain1h, prometheus.GaugeValue, w.Rain.OneH, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.winddegree, prometheus.GaugeValue, w.Wind.Deg, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.cloudiness, prometheus.GaugeValue, float64(w.Clouds.All), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.sunrise, prometheus.GaugeValue, float64(w.Sys.Sunrise), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.sunset, prometheus.GaugeValue, float64(w.Sys.Sunset), collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.snow1h, prometheus.GaugeValue, w.Snow.OneH, collector.Location)\n\tch <- prometheus.MustNewConstMetric(collector.currentconditions, prometheus.GaugeValue, 0, collector.Location, weather_description)\n}", "func (d *decorator) Collect(in chan<- prometheus.Metric) {\n\td.duration.Collect(in)\n\td.requests.Collect(in)\n}", "func (n DellHWCollector) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(n.collectors))\n\tfor name, c := range n.collectors {\n\t\tgo func(name string, c collector.Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar up float64 = 1\n\n\tglobalMutex.Lock()\n\tdefer globalMutex.Unlock()\n\n\tif e.config.resetStats && !globalResetExecuted {\n\t\t// Its time to try to reset the stats\n\t\tif e.resetStatsSemp1() {\n\t\t\tlevel.Info(e.logger).Log(\"msg\", \"Statistics successfully reset\")\n\t\t\tglobalResetExecuted = true\n\t\t\tup = 1\n\t\t} else {\n\t\t\tup = 0\n\t\t}\n\t}\n\n\tif e.config.details {\n\t\tif up > 0 {\n\t\t\tup = e.getClientSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getQueueSemp1(ch)\n\t\t}\n\t\tif up > 0 && e.config.scrapeRates {\n\t\t\tup = e.getQueueRatesSemp1(ch)\n\t\t}\n\t} else { // Basic\n\t\tif up > 0 {\n\t\t\tup = e.getRedundancySemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getSpoolSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getHealthSemp1(ch)\n\t\t}\n\t\tif up > 0 {\n\t\t\tup = e.getVpnSemp1(ch)\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(solaceUp, prometheus.GaugeValue, up)\n}", "func (c *MemoryCollector) Collect(ch chan<- prometheus.Metric) error {\n\tif desc, err := c.collect(ch); err != nil {\n\t\tlog.Error(\"failed collecting memory metrics:\", desc, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tfor _, db := range e.dbs {\n\t\t// logger.Log(\"Scraping\", db.String())\n\t\tgo e.scrapeDatabase(db)\n\t}\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.cpuPercent.Collect(ch)\n\te.dataIO.Collect(ch)\n\te.logIO.Collect(ch)\n\te.memoryPercent.Collect(ch)\n\te.workPercent.Collect(ch)\n\te.sessionPercent.Collect(ch)\n\te.storagePercent.Collect(ch)\n\te.dbUp.Collect(ch)\n\te.up.Set(1)\n}", "func (c *systemCollector) Collect(dClient utils.DS8kClient, ch chan<- prometheus.Metric) {\n\tlog.Debugln(\"Entering systems collector ...\")\n\treqSystemURL := \"https://\" + dClient.IpAddress + \":\" + ds8KAPIPort + \"/api/v1/systems\"\n\tsystemsResp, err := dClient.CallDS8kAPI(reqSystemURL)\n\tif err != nil {\n\t\tlog.Errorln(\"Executing '/api/v1/systems' failed: \", err)\n\t}\n\tlog.Debugln(\"Response of '/api/v1/systems': \", systemsResp)\n\t// This is the sample output of /api/v1/systems\n\t// {\n\t// \t\"counts\": {\n\t// \t\t\"data_counts\": 1,\n\t// \t\t\"total_counts\": 1\n\t// \t},\n\t// \t\"data\": {\n\t// \t\t\"systems\": [\n\t// \t\t\t{\n\t// \t\t\t\t\"MTM\": \"2831-984\",\n\t// \t\t\t\t\"bundle\": \"88.33.41.0\",\n\t// \t\t\t\t\"cap\": \"43512313675776\",\n\t// \t\t\t\t\"capalloc\": \"31521838727168\",\n\t// \t\t\t\t\"capavail\": \"11906723086336\",\n\t// \t\t\t\t\"capraw\": \"87241523200000\",\n\t// \t\t\t\t\"id\": \"2107-75DXA41\",\n\t// \t\t\t\t\"name\": \"IBM.2107-75DXA40\",\n\t// \t\t\t\t\"release\": \"8.3.3\",\n\t// \t\t\t\t\"sn\": \"75DXA41\",\n\t// \t\t\t\t\"state\": \"online\",\n\t// \t\t\t\t\"wwnn\": \"5005076306FFD65A\"\n\t// \t\t\t}\n\t// \t\t]\n\t// \t},\n\t// \t\"server\": {\n\t// \t\t\"code\": \"\",\n\t// \t\t\"message\": \"Operation done successfully.\",\n\t// \t\t\"status\": \"ok\"\n\t// \t}\n\t// }\n\n\tsystemsData := gjson.Get(systemsResp, \"data\").String()\n\tsystems := gjson.Get(systemsData, \"systems\").Array()\n\tfor _, system := range systems {\n\t\tlabelvalues := []string{system.Get(\"name\").String(), dClient.IpAddress}\n\t\tch <- prometheus.MustNewConstMetric(totalSystemCapacity, prometheus.GaugeValue, system.Get(\"cap\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(availableSystemCapacity, prometheus.GaugeValue, system.Get(\"capavail\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(allocatedSystemCapacity, prometheus.GaugeValue, system.Get(\"capalloc\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(systemCapacityUsedPercent, prometheus.GaugeValue, system.Get(\"capalloc\").Float()/system.Get(\"cap\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(rawSystemCapacity, prometheus.GaugeValue, system.Get(\"capraw\").Float(), labelvalues...)\n\t}\n\tlog.Debugln(\"Leaving systems collector.\")\n}", "func (e *ebpfConntracker) Collect(ch chan<- prometheus.Metric) {\n\tebpfTelemetry := &netebpf.ConntrackTelemetry{}\n\tif err := e.telemetryMap.Lookup(unsafe.Pointer(&zero), unsafe.Pointer(ebpfTelemetry)); err != nil {\n\t\tlog.Tracef(\"error retrieving the telemetry struct: %s\", err)\n\t} else {\n\t\tdelta := ebpfTelemetry.Registers - conntrackerTelemetry.lastRegisters\n\t\tconntrackerTelemetry.lastRegisters = ebpfTelemetry.Registers\n\t\tch <- prometheus.MustNewConstMetric(conntrackerTelemetry.registersTotal, prometheus.CounterValue, float64(delta))\n\t}\n}", "func (c *DiskCache) Collect(metrics chan<- prometheus.Metric) {\n\tc.requestTotals.Collect(metrics)\n\tc.missTotals.Collect(metrics)\n\tc.bytesStoredtotals.Collect(metrics)\n\tc.bytesFetchedtotals.Collect(metrics)\n\tc.bytesLoserTotals.Collect(metrics)\n\tc.errTotal.Collect(metrics)\n\tc.walkerRemovalTotal.Collect(metrics)\n\tc.walkerErrorTotal.Collect(metrics)\n\tc.walkerEmptyDirTotal.Collect(metrics)\n\tc.walkerEmptyDirRemovalTotal.Collect(metrics)\n}", "func (w *Writer) Collect(ch chan<- prometheus.Metric) {\n\tw.kafkaWriteStatus.Collect(ch)\n\tw.queuedForWrites.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tignore := strings.Split(*flagStatsIgnore, \",\")\n\tif len(ignore) == 1 && ignore[0] == \"\" {\n\t\tignore = []string{}\n\t}\n\tnicks := strings.Split(*flagStatsNicks, \",\")\n\tif len(nicks) == 1 && nicks[0] == \"\" {\n\t\tnicks = []string{}\n\t}\n\tres := e.client.Stats(irc.StatsRequest{\n\t\tLocal: *flagStatsLocal,\n\t\tTimeout: *flagStatsTimeout,\n\t\tIgnoreServers: ignore,\n\t\tNicks: nicks,\n\t})\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tconnected, prometheus.GaugeValue, boolToFloat[e.client.Server != \"\"])\n\n\t_, ok := res.Servers[e.client.Server]\n\tif res.Timeout && !ok {\n\t\t// Timeout, no data at all\n\t\tif e.client.Server != \"\" {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tup, prometheus.GaugeValue, 0.0, e.client.Server)\n\t\t}\n\t} else {\n\t\t// Global state\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tchannels, prometheus.GaugeValue, float64(res.Channels))\n\n\t\tfor nick, nickIson := range res.Nicks {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tison, prometheus.GaugeValue, boolToFloat[nickIson], nick)\n\t\t}\n\n\t\t// Per server state\n\t\tfor server, stats := range res.Servers {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tdistance, prometheus.GaugeValue, float64(stats.Distance), server)\n\n\t\t\tif *flagStatsLocal && e.client.Server != server {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tup, prometheus.GaugeValue, boolToFloat[stats.Up], server)\n\n\t\t\tif stats.Up {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tusers, prometheus.GaugeValue, float64(stats.Users), server)\n\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tlatency, prometheus.GaugeValue, float64(stats.ResponseTime.Sub(stats.RequestTime))/float64(time.Second), server)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *prometheusCollector) Collect(ch chan<- prometheus.Metric) {\n\tvar stats = c.db.Stats()\n\n\tch <- prometheus.MustNewConstMetric(c.maxOpenConnections, prometheus.GaugeValue, float64(stats.MaxOpenConnections))\n\tch <- prometheus.MustNewConstMetric(c.openConnections, prometheus.GaugeValue, float64(stats.OpenConnections))\n\tch <- prometheus.MustNewConstMetric(c.inUse, prometheus.GaugeValue, float64(stats.InUse))\n\tch <- prometheus.MustNewConstMetric(c.idle, prometheus.GaugeValue, float64(stats.Idle))\n\tch <- prometheus.MustNewConstMetric(c.waitCount, prometheus.CounterValue, float64(stats.WaitCount))\n\tch <- prometheus.MustNewConstMetric(c.waitDuration, prometheus.CounterValue, float64(stats.WaitDuration))\n\tch <- prometheus.MustNewConstMetric(c.maxIdleClosed, prometheus.CounterValue, float64(stats.MaxIdleClosed))\n\tch <- prometheus.MustNewConstMetric(c.maxIdleTimeClosed, prometheus.CounterValue, float64(stats.MaxIdleTimeClosed))\n\tch <- prometheus.MustNewConstMetric(c.maxLifetimeClosed, prometheus.CounterValue, float64(stats.MaxLifetimeClosed))\n}", "func (e *Exporter) collect(ch chan<- prometheus.Metric) error {\n\tvar mempct, memtot, memfree float64\n\tif v, e := mem.VirtualMemory(); e == nil {\n\t\tmempct = v.UsedPercent\n\t\tmemtot = float64(v.Total)\n\t\tmemfree = float64(v.Free)\n\t}\n\tvar swappct, swaptot, swapfree float64\n\tif v, e := mem.SwapMemory(); e == nil {\n\t\tswappct = v.UsedPercent\n\t\tswaptot = float64(v.Total)\n\t\tswapfree = float64(v.Free)\n\t}\n\tvar cpupct float64\n\tif c, e := cpu.Percent(time.Millisecond, false); e == nil {\n\t\tcpupct = c[0] // one value since we didn't ask per cpu\n\t}\n\tvar load1, load5, load15 float64\n\tif l, e := load.Avg(); e == nil {\n\t\tload1 = l.Load1\n\t\tload5 = l.Load5\n\t\tload15 = l.Load15\n\t}\n\n\tvar cpuTotal, vsize, rss, openFDs, maxFDs, maxVsize float64\n\tif proc, err := procfs.NewProc(int(*pid)); err == nil {\n\t\tif stat, err := proc.NewStat(); err == nil {\n\t\t\tcpuTotal = float64(stat.CPUTime())\n\t\t\tvsize = float64(stat.VirtualMemory())\n\t\t\trss = float64(stat.ResidentMemory())\n\t\t}\n\t\tif fds, err := proc.FileDescriptorsLen(); err == nil {\n\t\t\topenFDs = float64(fds)\n\t\t}\n\t\tif limits, err := proc.NewLimits(); err == nil {\n\t\t\tmaxFDs = float64(limits.OpenFiles)\n\t\t\tmaxVsize = float64(limits.AddressSpace)\n\t\t}\n\t}\n\n\tvar procCpu, procMem float64\n\tvar estCon, lisCon, othCon, totCon, closeCon, timeCon, openFiles float64\n\tvar nThreads float64\n\tif proc, err := process.NewProcess(int32(*pid)); err == nil {\n\t\tif v, e := proc.CPUPercent(); e == nil {\n\t\t\tprocCpu = float64(v)\n\t\t}\n\t\tif v, e := proc.MemoryPercent(); e == nil {\n\t\t\tprocMem = float64(v)\n\t\t}\n\n\t\tif v, e := proc.NumThreads(); e == nil {\n\t\t\tnThreads = float64(v)\n\t\t}\n\t\tif connections, e := proc.Connections(); e == nil {\n\t\t\tfor _, v := range connections {\n\t\t\t\tif v.Status == \"LISTEN\" {\n\t\t\t\t\tlisCon += 1\n\t\t\t\t} else if v.Status == \"ESTABLISHED\" {\n\t\t\t\t\testCon += 1\n\t\t\t\t} else if v.Status == \"TIME_WAIT\" {\n\t\t\t\t\ttimeCon += 1\n\t\t\t\t} else if v.Status == \"CLOSE_WAIT\" {\n\t\t\t\t\tcloseCon += 1\n\t\t\t\t} else {\n\t\t\t\t\tothCon += 1\n\t\t\t\t}\n\t\t\t}\n\t\t\ttotCon = lisCon + estCon + timeCon + closeCon + othCon\n\t\t}\n\t\tif oFiles, e := proc.OpenFiles(); e == nil {\n\t\t\topenFiles = float64(len(oFiles))\n\t\t}\n\t}\n\n\t// metrics from process collector\n\tch <- prometheus.MustNewConstMetric(e.cpuTotal, prometheus.CounterValue, cpuTotal)\n\tch <- prometheus.MustNewConstMetric(e.openFDs, prometheus.CounterValue, openFDs)\n\tch <- prometheus.MustNewConstMetric(e.maxFDs, prometheus.CounterValue, maxFDs)\n\tch <- prometheus.MustNewConstMetric(e.vsize, prometheus.CounterValue, vsize)\n\tch <- prometheus.MustNewConstMetric(e.maxVsize, prometheus.CounterValue, maxVsize)\n\tch <- prometheus.MustNewConstMetric(e.rss, prometheus.CounterValue, rss)\n\t// node specific metrics\n\tch <- prometheus.MustNewConstMetric(e.memPercent, prometheus.CounterValue, mempct)\n\tch <- prometheus.MustNewConstMetric(e.memTotal, prometheus.CounterValue, memtot)\n\tch <- prometheus.MustNewConstMetric(e.memFree, prometheus.CounterValue, memfree)\n\tch <- prometheus.MustNewConstMetric(e.swapPercent, prometheus.CounterValue, swappct)\n\tch <- prometheus.MustNewConstMetric(e.swapTotal, prometheus.CounterValue, swaptot)\n\tch <- prometheus.MustNewConstMetric(e.swapFree, prometheus.CounterValue, swapfree)\n\tch <- prometheus.MustNewConstMetric(e.numCpus, prometheus.CounterValue, float64(runtime.NumCPU()))\n\tch <- prometheus.MustNewConstMetric(e.load1, prometheus.CounterValue, load1)\n\tch <- prometheus.MustNewConstMetric(e.load5, prometheus.CounterValue, load5)\n\tch <- prometheus.MustNewConstMetric(e.load15, prometheus.CounterValue, load15)\n\t// process specific metrics\n\tch <- prometheus.MustNewConstMetric(e.procCpu, prometheus.CounterValue, procCpu)\n\tch <- prometheus.MustNewConstMetric(e.procMem, prometheus.CounterValue, procMem)\n\tch <- prometheus.MustNewConstMetric(e.numThreads, prometheus.CounterValue, nThreads)\n\tch <- prometheus.MustNewConstMetric(e.cpuPercent, prometheus.CounterValue, cpupct)\n\tch <- prometheus.MustNewConstMetric(e.openFiles, prometheus.CounterValue, openFiles)\n\tch <- prometheus.MustNewConstMetric(e.totCon, prometheus.CounterValue, totCon)\n\tch <- prometheus.MustNewConstMetric(e.lisCon, prometheus.CounterValue, lisCon)\n\tch <- prometheus.MustNewConstMetric(e.estCon, prometheus.CounterValue, estCon)\n\tch <- prometheus.MustNewConstMetric(e.closeCon, prometheus.CounterValue, closeCon)\n\tch <- prometheus.MustNewConstMetric(e.timeCon, prometheus.CounterValue, timeCon)\n\treturn nil\n}", "func (c *solarCollector) collect(ch chan<- prometheus.Metric) error {\n\t// fetch the status of the controller\n\ttracer, err := gotracer.Status(\"/dev/ttyUSB0\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/*\n\t * report the collected data\n\t */\n\n\t// store boolean values as a float (1 == true, 0 == false)\n\tvar loadIsActive float64\n\t// Panel array\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.panelPower,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.ArrayPower),\n\t)\n\n\t// Batteries\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batterySOC,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatterySOC),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryTemp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryTemp),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryMinVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryMinVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.batteryMaxVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.BatteryMaxVoltage),\n\t)\n\n\t// Load output\n\tif tracer.Load {\n\t\tloadIsActive = 1\n\t}\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadActive,\n\t\tprometheus.GaugeValue,\n\t\tloadIsActive,\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadVoltage,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadVoltage),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadCurrent,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadCurrent),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.loadPower,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.LoadPower),\n\t)\n\n\t// controller infos\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.deviceTemp,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.DeviceTemp),\n\t)\n\n\t// energy consumed\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedDaily,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedDaily),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedMonthly,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedMonthly),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedAnnual,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedAnnual),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyConsumedTotal,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyConsumedTotal),\n\t)\n\t// energy generated\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedDaily,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedDaily),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedMonthly,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedMonthly),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedAnnual,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedAnnual),\n\t)\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.energyGeneratedTotal,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(tracer.EnergyGeneratedTotal),\n\t)\n\n\treturn nil\n}", "func (c *MosquittoCounter) Collect(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.Desc,\n\t\tprometheus.CounterValue,\n\t\tc.counter.value,\n\t)\n}", "func (c *grpcClientManagerCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, con := range c.cm.Metrics().Connections {\n\t\tl := []string{con.Target}\n\t\tch <- prometheus.MustNewConstMetric(connectionStateDesc, prometheus.GaugeValue, float64(con.State), l...)\n\t}\n}", "func (c *InterfacesCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range c.collectors() {\n\t\tm.Collect(ch)\n\t}\n}", "func (c *PostfixQueueCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ageSecondsHistogram.Collect(ch)\n\tc.sizeBytesHistogram.Collect(ch)\n\tc.scrapeDurationGauge.Collect(ch)\n\tc.scrapeSuccessGauge.Collect(ch)\n}", "func (collector *collector) Collect(ch chan<- prometheus.Metric) {\n\tcontainerNames, err := collector.server.GetContainerNames()\n\tif err != nil {\n\t\tcollector.logger.Printf(\"Can't query container names: %s\", err)\n\t\treturn\n\t}\n\n\tfor _, containerName := range containerNames {\n\t\tstate, _, err := collector.server.GetContainerState(containerName)\n\t\tif err != nil {\n\t\t\tcollector.logger.Printf(\n\t\t\t\t\"Can't query container state for `%s`: %s\", containerName, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcollector.collectContainerMetrics(ch, containerName, state)\n\t}\n}", "func (collector *atlassianUPMCollector) Collect(ch chan<- prometheus.Metric) {\n\tstartTime := time.Now()\n\tlog.Debug(\"Collect start\")\n\n\tlog.Debug(\"create request object\")\n\treq, err := http.NewRequest(\"GET\", baseURL, nil)\n\tif err != nil {\n\t\tlog.Error(\"http.NewRequest returned an error:\", err)\n\t}\n\n\tlog.Debug(\"create Basic auth string from argument passed\")\n\tbearer = \"Basic \" + *token\n\n\tlog.Debug(\"add authorization header to the request\")\n\treq.Header.Add(\"Authorization\", bearer)\n\n\tlog.Debug(\"add content type to the request\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tlog.Debug(\"make request... get back a response\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\t\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 0, *fqdn)\n\t\tlog.Warn(\"http.DefaultClient.Do returned an error:\", err, \" return from Collect\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Debug(\"response status code: \", resp.StatusCode)\n\t}\n\n\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 1, *fqdn)\n\n\tvar allPlugins restPlugins\n\tif resp.StatusCode == 200 {\n\t\tlog.Debug(\"get all plugins\")\n\t\tallPlugins = plugins(resp)\n\n\t\t// return user-installed plugins if argument passed\n\t\tif *userInstalled {\n\t\t\tlog.Debug(\"-user-installed found\")\n\t\t\tallPlugins = userInstalledPlugins(allPlugins)\n\t\t}\n\n\t\t// plugins have the ability to be installed, but disabled, this will remove them if disabled\n\t\tif *dropDisabled {\n\t\t\tlog.Debug(\"-drop-disabled found\")\n\t\t\tallPlugins = dropDisabledPlugins(allPlugins)\n\t\t}\n\n\t\t// Jira specific\n\t\t// some plugins maintained by Jira have an additional element, this gives the option to drop those plugins\n\t\tif *dropJiraSoftware {\n\t\t\tlog.Debug(\"-drop-jira-software found\")\n\t\t\tallPlugins = dropJiraSoftwarePlugins(allPlugins)\n\t\t}\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range allPlugins.Plugins {\n\n\t\t\tlog.Debug(\"creating plugin metric for: \" + plugin.Name)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMPlugins,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t0,\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tif resp.StatusCode == 200 && *checkUpdates {\n\t\tlog.Debug(\"get remaining plugins available info\")\n\t\tavailablePluginsMap := getAvailablePluginInfo(allPlugins)\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range availablePluginsMap {\n\t\t\tavailableUpdate := false\n\n\t\t\tverInstalled, err := version.NewVersion(plugin.InstalledVersion)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning plugin installed into version object\")\n\t\t\t}\n\n\t\t\tverAvailable, err := version.NewVersion(plugin.Version)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning available plugin into version object\")\n\t\t\t}\n\n\t\t\tif verInstalled.LessThan(verAvailable) {\n\t\t\t\tlog.Debug(\"plugin: \", plugin.Name, \", is currently running: \", plugin.InstalledVersion, \", and can be upgraded to: \", plugin.Version)\n\t\t\t\tavailableUpdate = true\n\t\t\t}\n\n\t\t\tlog.Debug(\"creating plugin version metric for: \", plugin.Name, \", with Key: \", plugin.Key)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMVersionsMetric,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tboolToFloat(availableUpdate),\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstring(plugin.InstalledVersion),\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tfinishTime := time.Now()\n\telapsedTime := finishTime.Sub(startTime)\n\tlog.Debug(\"set the duration metric\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMTimeMetric, prometheus.GaugeValue, elapsedTime.Seconds(), *fqdn)\n\n\tlog.Debug(\"Collect finished\")\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tif ch == nil {\n\t\tglog.Info(\"Prometheus channel is closed. Skipping\")\n\t\treturn\n\t}\n\n\te.mutex.Lock()\n\tdefer func() {\n\t\te.mutex.Unlock()\n\t\te.cleanup.Range(func(key, value interface{}) bool {\n\t\t\tswitch chiName := key.(type) {\n\t\t\tcase string:\n\t\t\t\te.cleanup.Delete(key)\n\t\t\t\te.removeInstallationReference(chiName)\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}()\n\n\tglog.Info(\"Starting Collect\")\n\tvar wg = sync.WaitGroup{}\n\t// Getting hostnames of Pods and requesting the metrics data from ClickHouse instances within\n\tfor chiName := range e.chInstallations {\n\t\t// Loop over all hostnames of this installation\n\t\tglog.Infof(\"Collecting metrics for %s\\n\", chiName)\n\t\tfor _, hostname := range e.chInstallations[chiName].hostnames {\n\t\t\twg.Add(1)\n\t\t\tgo func(name, hostname string, c chan<- prometheus.Metric) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tglog.Infof(\"Querying metrics for %s\\n\", hostname)\n\t\t\t\tmetricsData := make([][]string, 0)\n\t\t\t\tfetcher := e.newFetcher(hostname)\n\t\t\t\tif err := fetcher.clickHouseQueryMetrics(&metricsData); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying metrics for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d metrics for %s\\n\", len(metricsData), hostname)\n\t\t\t\twriteMetricsDataToPrometheus(c, metricsData, name, hostname)\n\n\t\t\t\tglog.Infof(\"Querying table sizes for %s\\n\", hostname)\n\t\t\t\ttableSizes := make([][]string, 0)\n\t\t\t\tif err := fetcher.clickHouseQueryTableSizes(&tableSizes); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying table sizes for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d table sizes for %s\\n\", len(tableSizes), hostname)\n\t\t\t\twriteTableSizesDataToPrometheus(c, tableSizes, name, hostname)\n\n\t\t\t}(chiName, hostname, ch)\n\t\t}\n\t}\n\twg.Wait()\n\tglog.Info(\"Finished Collect\")\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tstart := time.Now()\n\n\tp := \"Chassis/1\"\n\terr := power.Collect(p, c.cl, ch)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\terr = thermal.Collect(p, c.cl, ch)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tduration := time.Now().Sub(start).Seconds()\n\tch <- prometheus.MustNewConstMetric(scrapeDurationDesc, prometheus.GaugeValue, duration, c.cl.HostName())\n}", "func (w *HotCache) CollectMetrics() {\n\tw.writeFlow.CollectMetrics(\"write\")\n\tw.readFlow.CollectMetrics(\"read\")\n}", "func (c *Controller) CollectMetrics(ch chan<- prometheus.Metric) {\n\tmetric, err := prometheus.NewConstMetric(controllermanager.ControllerWorkerSum, prometheus.GaugeValue, float64(c.RunningWorkers()), \"controllerregistration\")\n\tif err != nil {\n\t\tcontrollermanager.ScrapeFailures.With(prometheus.Labels{\"kind\": \"controllerregistration-controller\"}).Inc()\n\t\treturn\n\t}\n\tch <- metric\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n if err := e.scrape(ch); err != nil {\n\t\tlog.Infof(\"Error scraping tinystats: %s\", err)\n\t}\n e.ipv4QueryA.Collect(ch)\n e.ipv4QueryNS.Collect(ch)\n e.ipv4QueryCNAME.Collect(ch)\n e.ipv4QuerySOA.Collect(ch)\n e.ipv4QueryPTR.Collect(ch)\n e.ipv4QueryHINFO.Collect(ch)\n e.ipv4QueryMX.Collect(ch)\n e.ipv4QueryTXT.Collect(ch)\n e.ipv4QueryRP.Collect(ch)\n e.ipv4QuerySIG.Collect(ch)\n e.ipv4QueryKEY.Collect(ch)\n e.ipv4QueryAAAA.Collect(ch)\n e.ipv4QueryAXFR.Collect(ch)\n e.ipv4QueryANY.Collect(ch)\n e.ipv4QueryTOTAL.Collect(ch)\n e.ipv4QueryOTHER.Collect(ch)\n e.ipv4QueryNOTAUTH.Collect(ch)\n e.ipv4QueryNOTIMPL.Collect(ch)\n e.ipv4QueryBADCLASS.Collect(ch)\n e.ipv4QueryNOQUERY.Collect(ch)\n\n e.ipv6QueryA.Collect(ch)\n e.ipv6QueryNS.Collect(ch)\n e.ipv6QueryCNAME.Collect(ch)\n e.ipv6QuerySOA.Collect(ch)\n e.ipv6QueryPTR.Collect(ch)\n e.ipv6QueryHINFO.Collect(ch)\n e.ipv6QueryMX.Collect(ch)\n e.ipv6QueryTXT.Collect(ch)\n e.ipv6QueryRP.Collect(ch)\n e.ipv6QuerySIG.Collect(ch)\n e.ipv6QueryKEY.Collect(ch)\n e.ipv6QueryAAAA.Collect(ch)\n e.ipv6QueryAXFR.Collect(ch)\n e.ipv6QueryANY.Collect(ch)\n e.ipv6QueryTOTAL.Collect(ch)\n e.ipv6QueryOTHER.Collect(ch)\n e.ipv6QueryNOTAUTH.Collect(ch)\n e.ipv6QueryNOTIMPL.Collect(ch)\n e.ipv6QueryBADCLASS.Collect(ch)\n e.ipv6QueryNOQUERY.Collect(ch)\n\n\treturn\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\t// Get the last views\n\tviews := c.views\n\t// Now clear them out for the next accumulation\n\tc.views = c.views[:0]\n\tc.mu.Unlock()\n\n\tif len(views) == 0 {\n\t\treturn\n\t}\n\n\t// seen is necessary because within each Collect cycle\n\t// if a Metric is sent to Prometheus with the same make up\n\t// that is \"name\" and \"labels\", it will error out.\n\tseen := make(map[prometheus.Metric]bool)\n\n\tfor _, vd := range views {\n\t\tfor _, row := range vd.Rows {\n\t\t\tmetric := c.toMetric(vd.View, row)\n\t\t\tif _, ok := seen[metric]; !ok && metric != nil {\n\t\t\t\tch <- metric\n\t\t\t\tseen[metric] = true\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *ServiceQuotasExporter) Collect(ch chan<- prometheus.Metric) {\n\tquotas, err := e.quotasClient.QuotasAndUsage()\n\tif err != nil {\n\t\tlog.Errorf(\"Can not retrieve quotas and limits: %s\", err)\n\t}\n\n\tfor _, quota := range quotas {\n\t\tresourceID := quota.Identifier()\n\n\t\tmetricLimit, ok := e.metricsQuotaLimit[resourceID]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(metricLimit, prometheus.GaugeValue, quota.Quota, resourceID)\n\n\t\tmetricUsed, ok := e.metricsUsedQuota[resourceID]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(metricUsed, prometheus.GaugeValue, quota.Usage, resourceID)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tdefer func() { ch <- e.up }()\n\n\t// If we fail at any point in retrieving GPU status, we fail 0\n\te.up.Set(1)\n\n\te.GetTelemetryFromNVML()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (coll WmiCollector) Collect(ch chan<- prometheus.Metric) {\n\tdefer trace()()\n\twg := sync.WaitGroup{}\n\twg.Add(len(coll.collectors))\n\tfor name, c := range coll.collectors {\n\t\tgo func(name string, c collector.Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n\tscrapeDurations.Collect(ch)\n}", "func (c *ImageCollector) Collect(ch chan<- prometheus.Metric) {\n\tctx, cancel := context.WithTimeout(context.Background(), c.timeout)\n\tdefer cancel()\n\timages, _, err := c.client.Images.ListUser(ctx, nil)\n\tif err != nil {\n\t\tc.errors.WithLabelValues(\"image\").Add(1)\n\t\tlevel.Warn(c.logger).Log(\n\t\t\t\"msg\", \"can't list images\",\n\t\t\t\"err\", err,\n\t\t)\n\t\treturn\n\t}\n\n\tfor _, img := range images {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.MinDiskSize,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(img.MinDiskSize*1024*1024*1024),\n\t\t\tfmt.Sprintf(\"%d\", img.ID), img.Name, img.Regions[0], img.Type, img.Distribution,\n\t\t)\n\t}\n}", "func (s PowerControl) Collect(ch chan<- prometheus.Metric) {\n\tmetric := config.GOFISH.Service\n\n\tchass, _ := metric.Chassis()\n\n\tfor _, v := range chass {\n\t\tpowers, _ := v.Power()\n\t\tif powers != nil {\n\t\t\tfor _, p := range powers.PowerControl {\n\t\t\t\tch <- prometheus.MustNewConstMetric(config.C_powercontrol, prometheus.GaugeValue, float64(0),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerMetrics.AverageConsumedWatts),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerCapacityWatts),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.MemberID),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerMetrics.IntervalInMin),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerMetrics.MaxConsumedWatts),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerMetrics.MinConsumedWatts),\n\t\t\t\t)\n\n\t\t\t\tch <- prometheus.MustNewConstMetric(config.C_powerconsumedbyall, prometheus.GaugeValue, float64(p.PowerConsumedWatts),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.PowerCapacityWatts),\n\t\t\t\t\tfmt.Sprintf(\"%v\", p.MemberID),\n\t\t\t\t)\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (c *UPSCollector) Collect(ch chan<- prometheus.Metric) {\n\tif desc, err := c.collect(ch); err != nil {\n\t\tlog.Printf(\"[ERROR] failed collecting UPS metric %v: %v\", desc, err)\n\t\tch <- prometheus.NewInvalidMetric(desc, err)\n\t\treturn\n\t}\n}", "func lvCollect(ch chan<- prometheus.Metric, lvs []map[string]string, vgName string) {\n for _, lv := range lvs {\n lvSizeF, err := strconv.ParseFloat(strings.Trim(lv[\"lv_size\"], \"B\"), 64)\n if err != nil {\n log.Print(err)\n return\n }\n ch <- prometheus.MustNewConstMetric(lvSizeMetric, prometheus.GaugeValue, lvSizeF, lv[\"lv_name\"], lv[\"lv_uuid\"], vgName)\n }\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tjunosTotalScrapeCount++\n\tch <- prometheus.MustNewConstMetric(junosDesc[\"ScrapesTotal\"], prometheus.CounterValue, junosTotalScrapeCount)\n\n\twg := &sync.WaitGroup{}\n\tfor _, collector := range e.Collectors {\n\t\twg.Add(1)\n\t\tgo e.runCollector(ch, collector, wg)\n\t}\n\twg.Wait()\n}", "func (c *SchedulerController) CollectMetrics(ch chan<- prometheus.Metric) {\n\tmetric, err := prometheus.NewConstMetric(scheduler.ControllerWorkerSum, prometheus.GaugeValue, float64(c.RunningWorkers()), \"seed\")\n\tif err != nil {\n\t\tscheduler.ScrapeFailures.With(prometheus.Labels{\"kind\": \"gardener-shoot-scheduler\"}).Inc()\n\t\treturn\n\t}\n\tch <- metric\n}" ]
[ "0.73168796", "0.7302511", "0.7300016", "0.72376364", "0.7230181", "0.71361977", "0.7107565", "0.70940626", "0.70791847", "0.70347685", "0.70186526", "0.701455", "0.70036155", "0.70034826", "0.6995493", "0.6993202", "0.6978086", "0.6977177", "0.6966793", "0.6963395", "0.6930937", "0.6916874", "0.6879939", "0.68732256", "0.6871748", "0.68516403", "0.68516403", "0.6843492", "0.6818147", "0.6814053", "0.6806176", "0.6794889", "0.6793242", "0.67922384", "0.67835593", "0.6769379", "0.676009", "0.67599523", "0.6751293", "0.67396796", "0.67359674", "0.6734478", "0.6729602", "0.6693992", "0.6690584", "0.6686506", "0.66863906", "0.667418", "0.6672927", "0.66562223", "0.66514796", "0.66350573", "0.65952796", "0.6591796", "0.65906", "0.6580818", "0.65725845", "0.65671885", "0.6561363", "0.6555761", "0.6550838", "0.65418476", "0.65272236", "0.6509881", "0.65087306", "0.64994407", "0.6497929", "0.64974314", "0.64794", "0.647234", "0.646937", "0.6460018", "0.6456609", "0.64381", "0.6432223", "0.6421381", "0.6413016", "0.6412264", "0.64080626", "0.6406985", "0.6398457", "0.6395343", "0.63884324", "0.63882565", "0.63660455", "0.63625705", "0.6351686", "0.634618", "0.63390076", "0.6317238", "0.6310596", "0.62799776", "0.627301", "0.6269097", "0.62677056", "0.6252339", "0.6242956", "0.6230828", "0.6230089", "0.6229007", "0.62288725" ]
0.0
-1
nextLineIterator returns a function that iterates over an io.Reader object returning each line parsed in fields following the parser method passed as argument
func parseBlocks(buf io.Reader) (map[string](map[string](string)), error) { buffer := buf.(*bytes.Buffer) result := make(map[string](map[string](string))) var err error var line string var split_line []string var label string for { line, err = buffer.ReadString('\n') if err == io.EOF { return result, nil } else if err != nil { return result, err } split_line = strings.Split(line, ":") if len(split_line) < 2 { return result, errors.New("did not find any of the jobs requested in the HPC") } label = strings.TrimSpace(split_line[1]) result[label] = make(map[string](string)) for { line, err = buffer.ReadString('\n') if err == io.EOF { return result, nil } else if err != nil { return result, err } split_line = strings.Split(line, "=") if len(split_line) < 2 { break } result[label][strings.TrimSpace(split_line[0])] = strings.TrimSpace(split_line[1]) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func nextLineIterator(buf io.Reader, parser func(string) []string) func() ([]string, error) {\n\tvar buffer = buf.(*bytes.Buffer)\n\tvar parse = parser\n\treturn func() ([]string, error) {\n\t\t// get next line in buffer\n\t\tline, err := buffer.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// fmt.Print(line)\n\n\t\t// parse the line and return\n\t\tparsed := parse(line)\n\t\tif parsed == nil {\n\t\t\treturn nil, errors.New(\"not able to parse line\")\n\t\t}\n\t\treturn parsed, nil\n\t}\n}", "func EachIOLine(f io.ReadCloser, handler func(line string, num int) error) error {\n\tdefer Fclose(f)\n\tr := bufio.NewReader(f)\n\tvar err error\n\tfor i := 0; err == nil; i++ {\n\t\tvar line string\n\t\tline, err = r.ReadString('\\n')\n\t\tif err != nil && line == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tline = strings.Trim(line, \"\\n\\r\")\n\t\terrr := handler(line, i)\n\t\tif errr != nil {\n\t\t\treturn errr\n\t\t}\n\t}\n\tif err == io.EOF {\n\t\treturn nil\n\t}\n\treturn err\n}", "func LineReader(file *os.File, bus ChannelBus) {\n\tr := openReader(file)\n\tfor line, err := r.ReadString('\\n'); err == nil; line, err = r.ReadString('\\n') {\n\t\tbus.CurrentLine <- line\n\t}\n\tfile.Close()\n\tclose(bus.CurrentLine)\n}", "func NewLineScanner(b []byte) func() ([]byte, int) {\n\tstart := -1\n\tend := -1\n\tmax := len(b)\n\treturn func() ([]byte, int) {\n\t\tend++\n\t\tif end >= max {\n\t\t\treturn nil, 0\n\t\t}\n\t\tfor start = end; end < max; end++ {\n\t\t\tif b[end] == nl { // look for newline char\n\t\t\t\treturn b[start:end], end - start\n\t\t\t}\n\t\t}\n\t\treturn b[start:max], max - start\n\t}\n}", "func (i *FuncIterator) GetNext() (line []byte, input interface{}, err error) {\n\tnextIndex := atomic.AddInt64(&i.currentIndex, 1)\n\tvar nextValue string\n\tif i.endIndex != 0 && nextIndex > i.endIndex {\n\t\terr = io.EOF\n\t} else {\n\t\tnextValue, err = i.next(nextIndex)\n\t\tline = []byte(nextValue)\n\t}\n\treturn line, nextValue, err\n}", "func ReadLines(sc *bufio.Scanner, sep string, handler func(int, []string) bool) error {\n\tlineCount := 0 // line number of current position\n\tfields := make([]string, 0) // fields for current line\n\tbuilder := strings.Builder{} // string builder for current field\n\tquoted := false // whether current position in quote\n\tfor sc.Scan() {\n\t\t// read line\n\t\tlineStr := sc.Text()\n\t\tline := []rune(lineStr)\n\t\t// start of line\n\t\tif quoted {\n\t\t\tbuilder.WriteString(\"\\r\\n\")\n\t\t}\n\t\t// parse line\n\t\tfor i := 0; i < len(line); i++ {\n\t\t\tif string(line[i]) == sep && !quoted {\n\t\t\t\t// end of field\n\t\t\t\tfields = append(fields, builder.String())\n\t\t\t\tbuilder.Reset()\n\t\t\t} else if line[i] == '\"' {\n\t\t\t\tif quoted {\n\t\t\t\t\tif i+1 >= len(line) || line[i+1] != '\"' {\n\t\t\t\t\t\t// end of quoted\n\t\t\t\t\t\tquoted = false\n\t\t\t\t\t} else {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tbuilder.WriteRune('\"')\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// start of quoted\n\t\t\t\t\tquoted = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbuilder.WriteRune(line[i])\n\t\t\t}\n\t\t}\n\t\t// end of line\n\t\tif !quoted {\n\t\t\tfields = append(fields, builder.String())\n\t\t\tbuilder.Reset()\n\t\t\tif !handler(lineCount, fields) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfields = []string{}\n\t\t}\n\t\t// increase line count\n\t\tlineCount++\n\t}\n\treturn sc.Err()\n}", "func (io *Io) NextLine() string {\n\tif io.nextToken < len(io.tokens) {\n\t\tpanic(\"io.nextToken < len(io.tokens)\")\n\t}\n\n\tvar buffer bytes.Buffer\n\n\tfor {\n\t\tline, isPrefix, err := io.reader.ReadLine()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tbuffer.Write(line)\n\t\tif !isPrefix {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn buffer.String()\n}", "func (c Command) lineReader(r io.Reader) {\n\tscanner := bufio.NewScanner(r)\n\n\tfor scanner.Scan() {\n\t\tc.Stdout(scanner.Text())\n\t}\n}", "func (t *ReaderTokeniser) ReadLine() ([]string, error) {\n\tfor {\n\t\tif line, lineok := t.tokeniseUntilLine(); lineok {\n\t\t\treturn line, nil\n\t\t}\n\t\tif err := t.fillFromReader(); err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\t}\n}", "func (r *linesIterator) Next(line *string) bool {\n\n\tfor r.scanner.Scan() {\n\t\t*line = r.scanner.Text()\n\t\treturn true\n\t}\n\n\treturn false\n}", "func LineReader(r io.Reader) chan string {\n\tch := make(chan string)\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(r)\n\n\t\tfor scanner.Scan() {\n\t\t\tl := scanner.Text()\n\t\t\tl = strings.TrimSpace(l)\n\t\t\tif len(l) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tch <- l\n\t\t}\n\n\t\tclose(ch)\n\t}()\n\n\treturn ch\n}", "func NewLinesIterator(path string) (iter.Iterator, error) {\n\tfile, err := os.Open(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlinesCount, err := linesCount(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = file.Seek(0, os.SEEK_SET); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &linesIterator{\n\t\tpath: path,\n\t\tlines: make(chan string),\n\t\tlinesCount: linesCount,\n\t\tfile: file,\n\t\tscanner: bufio.NewScanner(file),\n\t}, nil\n}", "func (i *Iter) Next() *Field", "func (lf *ListFile) IterateLines(iterator func(line string) bool) error {\n\treturn lf.iterateLines(func(b []byte) bool {\n\t\treturn iterator(string(b))\n\t})\n}", "func (in *interp) readLine(line string) ([]interface{}, error) {\n\tif !in.pendingLine.ready() {\n\t\treturn in.readExprLine(line, nil)\n\t}\n\n\tvar s scanner.Scanner\n\tfset := token.NewFileSet()\n\tfile := fset.AddFile(\"\", fset.Base(), len(line))\n\ts.Init(file, []byte(line), nil, 0)\n\n\t_, tok, lit := s.Scan()\n\tswitch tok {\n\tcase token.EOF:\n\t\treturn nil, nil\n\n\tcase token.IMPORT:\n\t\t_, tok, lit = s.Scan()\n\t\tif tok != token.STRING {\n\t\t\treturn nil, errors.New(\"expected string literal\")\n\t\t}\n\t\tpkgpath, err := strconv.Unquote(lit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpkg, err := in.loadPackage(pkgpath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tin.imports = append(in.imports, pkg)\n\t\treturn nil, nil\n\n\tcase token.IDENT:\n\t\tok, err := in.maybeReadAssignment(line, &s, lit, file.Base())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif ok {\n\t\t\treturn nil, nil\n\t\t}\n\t\tfallthrough\n\n\tdefault:\n\t\treturn in.readExprLine(line, nil)\n\t}\n}", "func ForeachLine(in io.Reader, cb func(s string, b bool)) {\n\tr := bufio.NewReader(in)\n\tfor {\n\t\tlineNL, err := r.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tif len(lineNL) > 0 {\n\t\t\t\tcb(lineNL, false)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tcb(lineNL[:len(lineNL)-1], true)\n\t}\n}", "func (io *Io) NextLine() string {\n\tvar buffer []byte\n\tfor {\n\t\tline, isPrefix, err := io.reader.ReadLine()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tbuffer = append(buffer, line...)\n\t\tif !isPrefix {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn string(buffer)\n}", "func readLine(in *bufio.Reader) ([]string, error) {\n\tfor {\n\t\tline, err := in.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tif len(line) == 0 {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\targs := strings.Fields(line)\n\t\t// skip empty lines and comments\n\t\tif (len(args) == 0) || (args[0][0] == '#') || (args[0][0] == ';') {\n\t\t\tcontinue\n\t\t}\n\t\treturn args, nil\n\t}\n}", "func (p *Parser) Next() (textparse.Entry, error) {\n\tfor p.s.Scan() {\n\t\t// TODO(bwplotka): Assuming all line by line. If not do refetch like in previous version with more lines.\n\t\tline := p.s.Bytes()\n\n\t\tp.Parser = textparse.New(line, \"\") // use promtext format\n\t\tif et, err := p.Parser.Next(); err != io.EOF {\n\t\t\treturn et, err\n\t\t}\n\t\t// EOF from parser, continue scanning.\n\t}\n\tif err := p.s.Err(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn 0, io.EOF\n}", "func (io *Io) Next() string {\n\tfor io.nextToken >= len(io.tokens) {\n\t\tline := io.NextLine()\n\t\tio.tokens = strings.Fields(line)\n\t\tio.nextToken = 0\n\t}\n\tr := io.tokens[io.nextToken]\n\tio.nextToken++\n\treturn r\n}", "func Fscanln(r io.Reader, a ...interface{}) (n int, err error) {}", "func (line *LineEntry) Next() (*LineEntry, error) {\n\tvar entry dwarf.LineEntry\n\n\tline.reader.Seek(line.pos)\n\terr := line.reader.Next(&entry)\n\tif err != nil {\n\t\treturn nil, Error(err)\n\t}\n\n\treturn &LineEntry{\n\t\treader: line.reader,\n\t\tpos: line.reader.Tell(),\n\t\tFilename: entry.File.Name,\n\t\tAddress: uintptr(entry.Address),\n\t\tIsStmt: entry.IsStmt,\n\t\tLine: uint(entry.Line),\n\t\tColumn: uint(entry.Column),\n\t}, nil\n}", "func (fu fileUtil) ReadByLines(filePath string, handler func(line string) error) error {\n\tvar f *os.File\n\tvar err error\n\tif f, err = os.Open(filePath); err == nil {\n\t\tdefer f.Close()\n\t\tvar line string\n\t\tscanner := bufio.NewScanner(f)\n\t\tfor scanner.Scan() {\n\t\t\tline = scanner.Text()\n\t\t\terr = handler(line)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n\n}", "func (fs *Fields) Iter() (*Field, Iter)", "func ReadLines(r io.Reader) Stream {\n c, _ := r.(io.Closer)\n return &lineStream{bufio: bufio.NewReader(r), maybeCloser: maybeCloser{c: c}}\n}", "func NewIterator(reader *bufio.Reader) (*Iterator, error) {\n\titerator := &Iterator{\n\t\treader: reader,\n\t}\n\n\t// Read the header\n\titerator.err = iterator.readHeader()\n\tif iterator.err != nil {\n\t\treturn nil, iterator.err\n\t}\n\n\treturn iterator, nil\n}", "func (r *EntryReader) Next() (entry Entry, err error) {\n\tlines := []string{}\n\n\tfor i := 0; i < r.linecount; i++ {\n\n\t\tif !r.scanner.Scan() {\n\t\t\tif err = r.scanner.Err(); err != nil {\n\t\t\t\t// input error\n\t\t\t\treturn\n\t\t\t} else if i == 0 {\n\t\t\t\t// EOF between entries -- OK\n\t\t\t\terr = io.EOF\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\t// EOF in the middle of an entry -- not OK\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlines = append(lines, r.scanner.Text())\n\t}\n\n\treturn Entry{Lines: lines}, nil\n}", "func (dr *SeparatedReaders) Next() (err error) {\n\tdr.Count++\n\tif !dr.delimiterFound {\n\t\t// read and discard remains of section.\n\t\t// TODO could read directly any unused, reducing copying taking place\n\t\tbuf := make([]byte, bytes.MinRead)\n\t\tfor {\n\t\t\t_, err = dr.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tdr.delimiterFound = false\n\treturn\n}", "func FileReadLine(path string, line int) ([]string, error) {\n\tif line <= 0 {\n\t\tline = 1\n\t}\n\tvar content []string\n\te := FileIterateLine(path, func(n int, l string) bool {\n\t\tif n <= line {\n\t\t\tcontent = append(content, l)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn content, e\n}", "func (parser *Parser) Next() (api.Call, error) {\n\tfor parser.scanner.Scan() {\n\t\tline := parser.scanner.Text()\n\t\tcall := parseCall(line)\n\t\tfmt.Printf(\"%#+v\\n\", call)\n\t\treturn call, nil\n\t}\n\n\tif err := parser.scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, io.EOF\n}", "func execmReaderReadLine(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadLine()\n\tp.Ret(1, ret, ret1)\n}", "func (obj *LineFile) readLine(r *bufio.Reader) ([]byte, error) {\n\tvar results []byte\n\thasMore := true\n\tbytes := []byte{}\n\tvar err error\n\tfor hasMore {\n\t\tbytes, hasMore, err = r.ReadLine()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif len(bytes) > 0 {\n\t\t\tresults = append(results, bytes...)\n\t\t}\n\t}\n\treturn results, err\n}", "func readLine(r io.ReaderAt, offset int64) (s string, err error) {\n\tsr := io.NewSectionReader(r, offset, bufio.MaxScanTokenSize)\n\tsc := bufio.NewScanner(sr)\n\n\tif sc.Scan() {\n\t\ts = sc.Text()\n\t}\n\tif sc.Err() != nil {\n\t\terr = sc.Err()\n\t\treturn\n\t}\n\n\treturn\n}", "func EachLine(path string, handler func(line string, num int) error) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn EachIOLine(f, handler)\n}", "func (s *SyncTask) readLines(input io.Reader, decoders chan<- []byte) error {\n\n\trd := bufio.NewReader(input)\n\n\tfor {\n\t\tline, err := rd.ReadBytes('\\n')\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\treturn nil\n\t\tcase nil:\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\n\t\tdecoders <- line\n\t\tmetrics.fileLines.Add(1)\n\t}\n}", "func (io *Io) Next() string {\n\tif io.nextToken >= len(io.tokens) {\n\t\tline := io.NextLine()\n\t\tio.tokens = strings.Fields(line)\n\t\tio.nextToken = 0\n\t}\n\n\tres := io.tokens[io.nextToken]\n\tio.nextToken++\n\treturn res\n}", "func (u *uploader) nextReader() (readerAtSeeker, int, []byte, error) {\n\ttype readerAtSeeker interface {\n\t\tio.ReaderAt\n\t\tio.ReadSeeker\n\t}\n\tswitch r := u.in.Body.(type) {\n\tcase readerAtSeeker:\n\t\tvar err error\n\n\t\tn := u.cfg.PartSize\n\t\tif u.totalSize >= 0 {\n\t\t\tbytesLeft := u.totalSize - u.readerPos\n\n\t\t\tif bytesLeft <= u.cfg.PartSize {\n\t\t\t\terr = io.EOF\n\t\t\t\tn = bytesLeft\n\t\t\t}\n\t\t}\n\t\treader := io.NewSectionReader(r, u.readerPos, n)\n\t\tu.readerPos += n\n\n\t\treturn reader, int(n), nil, err\n\n\tdefault:\n\t\tpart := u.bufferPool.Get().([]byte)\n\t\tn, err := readFillBuf(r, part)\n\t\tu.readerPos += int64(n)\n\n\t\treturn bytes.NewReader(part[0:n]), n, part, err\n\t}\n}", "func NextLine() string {\n\tsc.Scan()\n\treturn sc.Text()\n}", "func LineReader(r io.Reader) (<-chan string, error) {\n\treturn lineReader(func() (io.Reader, func(), error) { return r, nil, nil })\n}", "func readLine(reader *bufio.Reader) ([]byte, error) {\n\tline := []byte{}\n\tfor {\n\t\t_line, isPrefix, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\treturn line, err\n\t\t}\n\t\tline = append(line, _line...)\n\t\tif !isPrefix {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn line, nil\n}", "func readLine(bufferedReader *bufio.Reader) (string, error) {\n\tvar (\n\t\tisPrefix bool = true\n\t\terr error = nil\n\t\tline, ln []byte\n\t)\n\n\tfor isPrefix && err == nil {\n\t\tline, isPrefix, err = bufferedReader.ReadLine()\n\t\tln = append(ln, line...)\n\t}\n\n\treturn string(ln), err\n}", "func (l *lexer) readLines() error {\n\tl.reset()\n\tln, _, err := l.bufReader.ReadLine()\n\tif err != nil {\n\t\tlog.Printf(\"Error: bufio.ReadLine: %v\\n\", err)\n\t}\n\tl.currentLine = l.nextLine\n\tl.nextLine = strings.TrimSpace(string(ln))\n\treturn err\n}", "func (r *lineReader) readLine(ctx context.Context) ([]byte, error) {\n\tvar buf []byte\n\tfor ctx.Err() == nil {\n\t\tline, err := r.r.ReadSlice('\\n')\n\t\tline = utils.BytesCopy(line)\n\t\tif err == nil {\n\t\t\treturn concatBufs(buf, line), err\n\t\t}\n\n\t\tif err == io.EOF {\n\t\t\tbuf = concatBufs(buf, line)\n\t\t\tif len(buf) == 0 {\n\t\t\t\treturn nil, io.EOF\n\t\t\t}\n\t\t\tutils.Sleep(ctx, r.eofSleep)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err == bufio.ErrBufferFull {\n\t\t\treturn concatBufs(buf, line), nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn nil, io.ErrClosedPipe\n}", "func FileIterateLine(path string, callback func(num int, line string) bool) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tbuf := bufio.NewReader(f)\n\tn := 0\n\tfor {\n\t\tn++\n\t\tline, isPrefix, err := buf.ReadLine()\n\t\tfor isPrefix {\n\t\t\tvar next []byte\n\t\t\tnext, isPrefix, err = buf.ReadLine()\n\t\t\tline = append(line, next...)\n\t\t}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif n == 1 && len(line) > 2 { //has bom?\n\t\t\tif line[0] == 239 && line[1] == 187 && line[2] == 191 {\n\t\t\t\tline = line[3:]\n\t\t\t}\n\t\t}\n\t\tif !callback(n, string(line)) {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func Lines(r io.Reader, callback func(line string) error) (err error) {\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\terr = callback(scanner.Text())\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn scanner.Err()\n}", "func ReadLines(scanner *bufio.Scanner, numOfLines int) (lines []string, err error) {\n i := 0\n for scanner.Scan() {\n i++\n if i <= numOfLines {\n lines = append(lines, scanner.Text())\n if i == numOfLines {\n return lines, scanner.Err()\n }\n }\n }\n\n return lines, io.EOF\n}", "func NewIterator(\n\treader xio.Reader64,\n\tdescr namespace.SchemaDescr,\n\topts encoding.Options,\n) encoding.ReaderIterator {\n\tstream := encoding.NewIStream(reader)\n\n\ti := &iterator{\n\t\topts: opts,\n\t\tstream: stream,\n\t\tmarshaller: newCustomMarshaller(),\n\t\ttsIterator: m3tsz.NewTimestampIterator(opts, true),\n\t}\n\ti.resetSchema(descr)\n\treturn i\n}", "func readLine(reader *bufio.Reader) (line string, err error) {\n\tvar part []byte\n\tvar prefix bool\n\n\tbuffer := bytes.NewBuffer(make([]byte, 0))\n\tfor {\n\t\tif part, prefix, err = reader.ReadLine(); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tbuffer.Write(part)\n\t\tif !prefix {\n\t\t\tline = buffer.String()\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (p *parser) parseLine(line string) {\n\tfor _, option := range p.options {\n\t\tif strings.HasPrefix(line, option.prefix) {\n\t\t\t// 1st condiition expect to parse a single line where the prefix is match\n\t\t\tif option.count == 0 {\n\t\t\t\tp.ips = append(p.ips, strings.Fields(line)[option.index])\n\t\t\t}\n\n\t\t\t// look for the IPs in lines after prefix are matched\n\t\t\tfor i := 0; i < option.count; i++ {\n\t\t\t\tif !p.scanner.Scan() {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tline := p.scanner.Text()\n\t\t\t\tp.ips = append(p.ips, strings.Fields(line)[option.index])\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Parser) parseLine(wg *sync.WaitGroup, in chan string, out chan *Record) {\n\tcp := re.Copy() //\"When using a Regexp in multiple goroutines, giving each goroutine its own copy helps to avoid lock contention\"\n\tfor l := range in {\n\t\tvar line []string\n\t\tif parsed := cp.FindAllStringSubmatch(l, -1); len(parsed) == 1 {\n\t\t\tline = parsed[0]\n\t\t} else {\n\t\t\t//fmt.Println(l) // uncomment this line if you want to find log lines that aren't being parsed\n\t\t\tcontinue\n\t\t}\n\n\t\tr := &Record{\n\t\t\tIP: line[1],\n\t\t\tMethod: line[3],\n\t\t\tFilename: line[4],\n\t\t\tStatus: line[6],\n\t\t\tReferer: line[8],\n\t\t\tUserAgent: line[9],\n\t\t}\n\n\t\tr.TS, _ = time.Parse(timeFmt, line[2])\n\t\tout <- r\n\t}\n\twg.Done()\n}", "func (c Crossref) Iterate(r io.Reader) (<-chan interface{}, error) {\n\tch := make(chan interface{})\n\treader := bufio.NewReader(r)\n\ti := 0\n\tvar lines []string\n\tgo func() {\n\t\tfor {\n\t\t\tline, err := reader.ReadString('\\n')\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\ti++\n\t\t\tlines = append(lines, line)\n\t\t\tif i == BatchSize {\n\t\t\t\tch <- NewBatch(lines)\n\t\t\t\tlines = lines[:0]\n\t\t\t\ti = 0\n\t\t\t}\n\t\t}\n\t\tch <- NewBatch(lines)\n\t\tclose(ch)\n\t}()\n\treturn ch, nil\n}", "func (writeFlags *writeFlagsType) createLineReader(args []string) (r io.Reader, closer io.Closer, err error) {\n\tif len(args) > 0 && args[0][0] == '@' {\n\t\t// backward compatibility: @ in arg denotes a file\n\t\twriteFlags.File = args[0][1:]\n\t}\n\n\tif len(writeFlags.File) > 0 {\n\t\tf, err := os.Open(writeFlags.File)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to open %q: %v\", writeFlags.File, err)\n\t\t}\n\t\tcloser = f\n\t\tr = f\n\t\tif len(writeFlags.Format) == 0 && strings.HasSuffix(writeFlags.File, \".csv\") {\n\t\t\twriteFlags.Format = inputFormatCsv\n\t\t}\n\t} else if len(args) == 0 || args[0] == \"-\" {\n\t\t// backward compatibility: \"-\" also means stdin\n\t\tr = os.Stdin\n\t} else {\n\t\tr = strings.NewReader(args[0])\n\t}\n\t// validate input format\n\tif len(writeFlags.Format) > 0 && writeFlags.Format != inputFormatLineProtocol && writeFlags.Format != inputFormatCsv {\n\t\treturn nil, nil, fmt.Errorf(\"unsupported input format: %s\", writeFlags.Format)\n\t}\n\n\tif writeFlags.Format == inputFormatCsv {\n\t\tr = write.CsvToProtocolLines(r)\n\t}\n\treturn r, closer, nil\n}", "func ParseReader(reader io.Reader) ([]Rule, error) {\n\n\tbr := bufio.NewReader(reader)\n\n\trules := make([]Rule, 0)\n\n\tbuffered := \"\"\n\n\tfor {\n\t\tbytes, err := br.ReadBytes('\\n')\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(bytes) > 0 {\n\n\t\t\tline := strings.TrimSpace(string(bytes))\n\n\t\t\tif strings.HasSuffix(line, \"\\\\\") {\n\t\t\t\tbuffered = fmt.Sprintf(\"%s %s\",\n\t\t\t\t\tbuffered, line[0:len(line)-1])\n\t\t\t} else {\n\t\t\t\tbuffered = fmt.Sprintf(\"%s %s\", buffered, line)\n\t\t\t\trule, err := Parse(strings.TrimSpace(buffered))\n\t\t\t\tif err == nil {\n\t\t\t\t\trules = append(rules, rule)\n\t\t\t\t}\n\t\t\t\tbuffered = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif err != nil && err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn rules, nil\n}", "func parseLines(scanner *bufio.Scanner, writer *bufio.Writer) []string {\n\tdefer writer.Flush()\n\theader := make([]string, 0)\n\tfor scanner.Scan() {\n\t\tparsed := parseRecord(scanner.Text())\n\t\toutput := make([]string, 0)\n\t\tfor _, field := range header {\n\t\t\tif val, iskey := parsed[field]; iskey {\n\t\t\t\toutput = append(output, val)\n\t\t\t\tdelete(parsed, field)\n\t\t\t} else {\n\t\t\t\toutput = append(output, \"\")\n\t\t\t}\n\t\t}\n\n\t\tfor field, value := range parsed {\n\t\t\toutput = append(output, value)\n\t\t\theader = append(header, field)\n\t\t}\n\t\toutput = append(output, strconv.Itoa(len(output)))\n\t\twriter.WriteString(strings.Join(output, parse.delim) + \"\\n\")\n\t}\n\treturn header\n}", "func readLine(reader *bufio.Reader, buffer *bytes.Buffer) (line string, size int, err error) {\n\tvar (\n\t\tsegment []byte\n\t\tnext bool\n\t)\n\t// if link file to stdin, can block forever here.\n\tfor {\n\t\tif segment, next, err = reader.ReadLine(); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\terr = errors.New(\"read line failed\")\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif _, err = buffer.Write(segment); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif next {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tsize = buffer.Len()\n\t\t\tline = buffer.String()\n\t\t\t//fix delim\n\t\t\treader.UnreadByte()\n\t\t\treader.UnreadByte()\n\t\t\tvar b []byte\n\t\t\tb, err = reader.ReadBytes('\\n')\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif b[0] == '\\r' {\n\t\t\t\tsize++\n\t\t\t}\n\t\t\tsize++\n\t\t\t// clear buffer\n\t\t\tbuffer.Reset()\n\t\t\treturn\n\t\t}\n\t}\n}", "func execmReaderReadContinuedLine(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*textproto.Reader).ReadContinuedLine()\n\tp.Ret(1, ret, ret1)\n}", "func (i *Filename) ReturnReader(startingLine int) (*bufio.Scanner, *os.File) {\n\treturn ReturnReader(string(*i), startingLine)\n}", "func ForEachLineInFile(filename string,\n\tprocessor func(line string) (bool, error)) error {\n\tfileProcessor := func(reader *bufio.Reader) error {\n\t\tfor {\n\t\t\tline, err := reader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgoOn, err := processor(strings.Trim(line, \" \\n\"))\n\t\t\tif goOn == false {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn WithOpenFileAsBufioReader(filename, fileProcessor)\n}", "func ParseLines(parser Parser, r io.Reader, storer storage.Storer, rawFlag bool, flushFlag bool, noCleanFlag bool) (err error) {\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tb := scanner.Bytes()\n\t\tn := len(b)\n\t\tif !noCleanFlag {\n\t\t\t// Remove unwanted ASCII characters\n\t\t\tn = Whitelist(b, n)\n\t\t}\n\t\tline := string(b[:n])\n\n\t\tif rawFlag {\n\t\t\t// Save raw text for each line\n\t\t\terr = storer.WriteString(RawName, line+\"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error writing unparsed text: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\td := parser.ParseLine(line)\n\t\tfor _, err := range d.Errors {\n\t\t\tlog.Printf(\"%v\", err)\n\t\t}\n\t\tif d.OK() {\n\t\t\t// Save data if properly parsed and not throttled\n\t\t\terr = storer.WriteString(UnderwayName, d.Line(\"\\t\")+\"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error writing parsed data: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tif flushFlag {\n\t\t\terr = storer.Flush()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error flushing data: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn fmt.Errorf(\"error reading lines: %v\", err)\n\t}\n\treturn nil\n}", "func readLine(r *bufio.Reader) (string, error) {\n\tvar (\n\t\tisPrefix = true\n\t\terr error\n\t\tline, ln []byte\n\t)\n\tfor isPrefix && err == nil {\n\t\tline, isPrefix, err = r.ReadLine()\n\t\tln = append(ln, line...)\n\t}\n\treturn string(ln), err\n}", "func generateCSVParseFunc(headers []string, fieldDelimiter rune, lazyQuotes bool) parseFunc {\n\treturn func(value interface{}) (interface{}, error) {\n\t\tcsvLine, err := valueAsString(value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treader := csvparser.NewReader(strings.NewReader(csvLine))\n\t\treader.Comma = fieldDelimiter\n\t\treader.FieldsPerRecord = len(headers)\n\t\treader.LazyQuotes = lazyQuotes\n\n\t\t// Typically only need one\n\t\tlines := make([][]string, 0, 1)\n\t\tfor {\n\t\t\tline, err := reader.Read()\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err != nil && len(line) == 0 {\n\t\t\t\treturn nil, errors.New(\"failed to parse entry\")\n\t\t\t}\n\n\t\t\tlines = append(lines, line)\n\t\t}\n\n\t\t/*\n\t\t\tThis parser is parsing a single value, which came from a single log entry.\n\t\t\tTherefore, if there are multiple lines here, it should be assumed that each\n\t\t\tsubsequent line contains a continuation of the last field in the previous line.\n\n\t\t\tGiven a file w/ headers \"A,B,C,D,E\" and contents \"aa,b\\nb,cc,d\\nd,ee\",\n\t\t\texpect reader.Read() to return bodies:\n\t\t\t- [\"aa\",\"b\"]\n\t\t\t- [\"b\",\"cc\",\"d\"]\n\t\t\t- [\"d\",\"ee\"]\n\t\t*/\n\n\t\tjoinedLine := lines[0]\n\t\tfor i := 1; i < len(lines); i++ {\n\t\t\tnextLine := lines[i]\n\n\t\t\t// The first element of the next line is a continuation of the previous line's last element\n\t\t\tjoinedLine[len(joinedLine)-1] += \"\\n\" + nextLine[0]\n\n\t\t\t// The remainder are separate elements\n\t\t\tfor n := 1; n < len(nextLine); n++ {\n\t\t\t\tjoinedLine = append(joinedLine, nextLine[n])\n\t\t\t}\n\t\t}\n\n\t\treturn headersMap(headers, joinedLine)\n\t}\n}", "func readLine(reader *bufio.Reader) (string, error) {\n\tvar line, b []byte\n\tvar err error\n\tisPrefix := true\n\tfor isPrefix {\n\t\tb, isPrefix, err = reader.ReadLine()\n\t\tline = append(line, b...)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn string(line), nil\n}", "func SrtingsIterator(strs ...string) Iterator {\n\tvar bbw Writer\n\tfor _, s := range strs {\n\t\tbs := []byte(s)\n\t\tbf, err := bbw.Allocate(len(bs), true)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcopy(bf, bs)\n\t}\n\n\tres, err := bbw.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trdr := new(Reader)\n\trdr.Reset(res, false)\n\treturn rdr\n}", "func LineReaderFrom(path string) (<-chan string, error) {\n\treturn lineReader(func() (io.Reader, func(), error) {\n\t\tif !FileExists(path) {\n\t\t\treturn nil, nil, nil\n\t\t}\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn f, func() { f.Close() }, nil\n\t})\n}", "func readLines(r io.Reader) ([]string, error) {\n\tlines := []string{}\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tline = removeComment(line, \"#\")\n\t\t// ignore empty lines\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tlines = append(lines, line)\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn lines, nil\n}", "func LinesFromReader(r io.Reader) ([]string, error) {\n\tvar lines []string\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn lines, nil\n}", "func ReadIO(in io.Reader) (l *Line, err error) {\n\n s := bufio.NewScanner(in)\n\n // scan once to get the first line\n if s.Scan() == false || s.Err() != nil {\n return nil, s.Err()\n }\n\n l = &Line{data: s.Text()}\n scanIO(l, s)\n\n return l, s.Err()\n}", "func (t *ReaderTokeniser) tokeniseUntilLine() (line []string, lineok bool) {\n\tvar nread int\n\tfor t.pos < t.max && !lineok {\n\t\tnread, lineok, line = t.tok.TokeniseBytes(t.buf[t.pos:t.max])\n\t\tt.pos += nread\n\t}\n\treturn\n}", "func TarIterator(reader io.Reader, visitor TarVisitor) error {\n\ttarReader := tar.NewReader(reader)\n\n\tfor {\n\t\thdr, err := tarReader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := visitor(hdr, tarReader); err != nil {\n\t\t\tif errors.Is(err, ErrTarStopIteration) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to visit tar entry=%q : %w\", hdr.Name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func LinebyLineScan() {\n file, err := os.Open(\"task.txt\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close()\n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n fmt.Println(scanner.Text())\n }\n if err := scanner.Err(); err != nil {\n log.Fatal(err)\n }\n}", "func FileForeachLine(vm *VM, target, locals Interface, msg *Message) (result Interface) {\n\tkn, vn, hkn, hvn, ev := ForeachArgs(msg)\n\tif ev == nil {\n\t\treturn vm.RaiseException(\"foreach requires 1, 2, or 3 arguments\")\n\t}\n\tf := target.(*File)\n\tk := 0\n\t// f.ReadLine implements the same logic as FileForeach above.\n\tfor {\n\t\tline, err := f.ReadLine()\n\t\tif line != nil {\n\t\t\tv := vm.NewSequence(line, true, \"latin1\")\n\t\t\tif hvn {\n\t\t\t\tSetSlot(locals, vn, v)\n\t\t\t\tif hkn {\n\t\t\t\t\tSetSlot(locals, kn, vm.NewNumber(float64(k)))\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = ev.Send(vm, v, locals)\n\t\t\tif rr, ok := CheckStop(result, NoStop); !ok {\n\t\t\t\tswitch s := rr.(Stop); s.Status {\n\t\t\t\tcase ContinueStop:\n\t\t\t\t\tresult = s.Result\n\t\t\t\tcase BreakStop:\n\t\t\t\t\treturn s.Result\n\t\t\t\tcase ReturnStop, ExceptionStop:\n\t\t\t\t\treturn rr\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"iolang: invalid Stop: %#v\", rr))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tk++\n\t\t}\n\t}\n\treturn result\n}", "func (p *ParserBase) Next() {\n\tp.newline = false\n\tp.Item = p.Lxr.Next()\n\tp.EndPos = int32(p.Item.Pos)\n\tfor {\n\t\tif p.Token == tok.Newline {\n\t\t\tif p.Lxr.AheadSkip(0).Token != tok.QMark {\n\t\t\t\tp.newline = true\n\t\t\t}\n\t\t} else if p.Token != tok.Comment && p.Token != tok.Whitespace {\n\t\t\tbreak\n\t\t}\n\t\tp.Item = p.Lxr.Next()\n\t}\n\tif p.EqToIs && p.Token == tok.Eq {\n\t\tp.Token = tok.Is\n\t}\n}", "func processFile(m Samples, rf io.Reader, a action) {\n csv := csv.NewReader(rf)\n header := true\n var s_header []string\n for {\n s_line, err := csv.Read()\n if err == io.EOF {\n break\n }\n if err != nil {\n log.Fatal(\"Error reading from csv file in ulrness.processFile() \", \" err: \", err)\n }\n if header {\n s_header = s_line\n header = false\n } else {\n err = a(m, s_line, s_header)\n if err != nil {\n log.Fatal(\"Error processing line in urlness.processFile()\", \"error: \", err)\n }\n }\n }\n}", "func readFields(r io.Reader)(o rune,t rune,b int,e int,f int,s string,err error){\nvar l int\nif _,err= fmt.Fscanf(r,\"%c%c%d %d %d %d\",&o,&t,&b,&e,&f,&l);err!=nil{\nreturn\n}\nif l!=0{\nrs:=make([]rune,l)\nfor i:=0;i<l;i++{\nif _,err= fmt.Fscanf(r,\"%c\",&rs[i]);err!=nil{\nreturn\n}\n}\ns= string(rs)\n}\nvar nl[1]byte\nif _,err= r.Read(nl[:]);err!=nil{\nreturn\n}\nreturn\n}", "func ReadLines(r io.Reader) <-chan string {\n\tlines := make(chan string)\n\tgo func() {\n\t\tdefer close(lines)\n\t\tscanner := bufio.NewScanner(r)\n\t\tfor scanner.Scan() {\n\t\t\tlines <- scanner.Text()\n\t\t}\n\t}()\n\treturn lines\n}", "func parser(\n\tin <-chan string,\n\terrors chan<- error,\n\tquit chan struct{},\n\tdefinitionFile string,\n) chan Parsed {\n\n\tdef, err := definition.NewDefinition(definitionFile)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to read definition: %s\", err)\n\t}\n\n\tout := make(chan Parsed)\n\n\tfor i := 0; i < NumParserWorkers; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn\n\t\t\t\tcase body := <-in:\n\t\t\t\t\tp := Parsed{\n\t\t\t\t\t\tFields: def.Parse(body),\n\t\t\t\t\t\tSize: binary.Size([]byte(body)),\n\t\t\t\t\t}\n\t\t\t\t\tout <- p\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn out\n}", "func (b *RFCTextReader) ReadLine() (v string, lineType int, err error) {\n\tif b.lastLine {\n\t\terr = io.EOF\n\t\treturn\n\t}\n\tfor !b.lastLine {\n\t\tif v, err = b.reader.ReadString('\\n'); nil != err {\n\t\t\tif err == io.EOF {\n\t\t\t\tb.lastLine = true\n\t\t\t\terr = nil\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tb.lineno++\n\t\tv = strings.TrimRightFunc(v, unicode.IsSpace)\n\t\tswitch b.mode {\n\t\tcase readModeNormal:\n\t\t\tif spaceCount := isSchemaStart(v); (spaceCount > 3) && (spaceCount < 12) {\n\t\t\t\tv = strings.TrimLeftFunc(v, unicode.IsSpace)\n\t\t\t\tif isSchemaEnd(v) {\n\t\t\t\t\treturn v, LineTypeSchema, nil\n\t\t\t\t}\n\t\t\t\tb.schemaTextSpaceCount = spaceCount\n\t\t\t\tb.mode = readModeSchema\n\t\t\t\tb.schemaTextBuffer = v\n\t\t\t} else {\n\t\t\t\tif chapterText := trapChapter.FindString(v); chapterText != \"\" {\n\t\t\t\t\tb.CurrentChapter = strings.TrimRightFunc(chapterText, unicode.IsSpace)\n\t\t\t\t\tlineType = LineTypeChapter\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\tcase readModeSchema:\n\t\t\tif 0 == len(v) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif trapPageHeader1.MatchString(v) && trapPageHeader2.MatchString(v) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif trapPageFooter.MatchString(v) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tspaceCount := countLeadingSpace(v)\n\t\t\tif spaceCount < b.schemaTextSpaceCount {\n\t\t\t\tlog.Printf(\"WARN: indent ot enough for schema: %v, line=%d\", v, b.lineno)\n\t\t\t}\n\t\t\tv = strings.TrimLeftFunc(v, unicode.IsSpace)\n\t\t\tb.schemaTextBuffer = b.schemaTextBuffer + \" \" + v\n\t\t\tif isSchemaEnd(b.schemaTextBuffer) {\n\t\t\t\tb.mode = readModeNormal\n\t\t\t\tv = b.schemaTextBuffer\n\t\t\t\tlineType = LineTypeSchema\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Printf(\"ERR: unknown mode: %v\", b.mode)\n\t\t}\n\t}\n\treturn\n}", "func LinesParser(l *[]Line, ts TransitSource) error {\n\tlog.Printf(\"Parsing lines\")\n\tLinesIgnored = LoadIgnoreLineIds()\n\tloadLineNumberMapping()\n\tagencyLines, err := getAgencyLines(ts.Path, ts.Uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*l = *agencyLines\n\treturn nil\n}", "func Fscanln(r io.Reader, a ...interface{}) (n int, err error) { return fmt.Fscanln(r, a...) }", "func ReaderRead(r *csv.Reader,) ([]string, error)", "func ParseReader(filename string, r io.Reader, opts ...Option) (any, error) { // nolint: deadcode\n\tb, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Parse(filename, b, opts...)\n}", "func NewFileByLineOpsReader(filename string, logger *Logger, opFilter string) (error, *ByLineOpsReader) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\terr, reader := NewByLineOpsReader(file, logger, opFilter)\n\tif err != nil {\n\t\treturn err, reader\n\t}\n\treader.closeFunc = func() {\n\t\tfile.Close()\n\t}\n\treturn nil, reader\n}", "func TestLineReader(t *testing.T) {\n\tvar (\n\t\thinames = []string{\"hi\", \"hil\", \"hit\"}\n\t\thnames = append(hinames, \"how\")\n\t\tallnames = append(hnames, \"there\")\n\t\ttests = []struct {\n\t\t\tin string\n\t\t\tnames []string\n\t\t\tout string\n\t\t}{\n\t\t\t{\"ther \", []string{\"there\"}, \"there\"},\n\t\t\t{\"ther\", []string{\"there\"}, \"there\"},\n\t\t\t{\"\\n\", []string{}, \"\"},\n\t\t\t{\"\", []string{}, \"\"},\n\t\t\t{\" \", []string{}, \"\"},\n\t\t}\n\t)\n\tfor _, tst := range tests {\n\t\tr := bytes.NewBufferString(tst.in)\n\t\tt.Logf(\"Test %v\", tst)\n\t\tcr, cw := io.Pipe()\n\t\tf := NewStringCompleter(allnames)\n\n\t\tl := NewLineReader(f, r, cw)\n\t\tvar out []byte\n\t\tgo func(o string, r io.Reader) {\n\t\t\tvar err error\n\t\t\tout, err = ioutil.ReadAll(r)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"reading console io.Pipe: got %v, want nil\", err)\n\t\t\t}\n\t\t\tif string(out) != o {\n\t\t\t\tt.Errorf(\"console out: got %v, want %v\", o, string(out))\n\t\t\t}\n\t\t}(tst.out, cr)\n\n\t\ts, err := l.ReadOne()\n\n\t\tt.Logf(\"ReadOne returns %v %v\", s, err)\n\t\tif err != nil && err != io.EOF && err != ErrEOL {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif len(s) != len(tst.names) {\n\t\t\tt.Fatalf(\"Got %d choices, want 1\", len(s))\n\t\t}\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif s[0] != tst.names[0] {\n\t\t\tt.Errorf(\"Got %v, want %v\", s[0], tst.names[0])\n\t\t}\n\t}\n}", "func NewReader(r *bufio.Reader) *Reader {\n\tscanner := bufio.NewScanner(r)\n\tscanner.Split(bufio.ScanLines)\n\treturn &Reader{\n\t\tscanner: scanner,\n\t\teof: false,\n\t}\n}", "func (d *Decoder) parseLine(line []byte) ([]pair, error) {\n\tvar add pair\n\tvar beg, offset int64\n\tvar esc bool\n\n\tstate := make(scanState, 0, 3)\n\tbuf := bytes.NewReader(line)\n\n\tfor r, sz, err := buf.ReadRune(); err == nil; r, sz, err = buf.ReadRune() {\n\t\tif r == 0xFFFD && sz == 1 {\n\t\t\treturn nil, errBadUnicode(line, offset)\n\t\t}\n\t\tswitch state.top() {\n\t\tcase scanNone:\n\t\t\tif unicode.IsSpace(r) {\n\t\t\t\t// skip\n\t\t\t} else if unicode.IsLetter(r) || unicode.IsNumber(r) {\n\t\t\t\tstate.push(scanAttr)\n\t\t\t\tbeg = offset\n\t\t\t} else {\n\t\t\t\treturn nil, errBadAttr(line, offset)\n\t\t\t}\n\t\tcase scanAttr:\n\t\t\tif unicode.IsSpace(r) {\n\t\t\t\tadd.attr = line[beg:offset]\n\t\t\t\td.pairbuf = append(d.pairbuf, add)\n\t\t\t\tif _, ok := d.attrs[string(add.attr)]; ok {\n\t\t\t\t\td.havemulti = true\n\t\t\t\t\td.multi[string(add.attr)] = struct{}{}\n\t\t\t\t} else {\n\t\t\t\t\td.attrs[string(add.attr)] = struct{}{}\n\t\t\t\t}\n\t\t\t\tadd.attr, add.val, esc = nil, nil, false\n\t\t\t\tstate.pop()\n\t\t\t} else if r == '=' {\n\t\t\t\tadd.attr = line[beg:offset]\n\t\t\t\tif _, ok := d.attrs[string(add.attr)]; ok {\n\t\t\t\t\td.havemulti = true\n\t\t\t\t\td.multi[string(add.attr)] = struct{}{}\n\t\t\t\t} else {\n\t\t\t\t\td.attrs[string(add.attr)] = struct{}{}\n\t\t\t\t}\n\t\t\t\tstate.pop()\n\t\t\t\tstate.push(scanValueStart)\n\t\t\t} else if !(r == '-' || unicode.IsLetter(r) || unicode.IsNumber(r)) {\n\t\t\t\treturn nil, errBadAttr(line, offset)\n\t\t\t}\n\t\tcase scanValueStart:\n\t\t\tbeg = offset\n\t\t\tstate.pop()\n\t\t\tstate.push(scanValue)\n\n\t\t\tif r == '\\'' {\n\t\t\t\tstate.push(scanQuoteStart)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase scanValue:\n\t\t\tif unicode.IsSpace(r) {\n\t\t\t\tstate.pop()\n\t\t\t\tadd.val = line[beg:offset]\n\t\t\t\tif esc {\n\t\t\t\t\tadd.val = bytes.Replace(add.val, []byte(\"''\"), []byte(\"'\"), -1)\n\t\t\t\t}\n\t\t\t\td.pairbuf = append(d.pairbuf, add)\n\t\t\t\tadd.attr, add.val = nil, nil\n\t\t\t}\n\t\tcase scanQuoteClose:\n\t\t\tstate.pop()\n\t\t\tif r == '\\'' {\n\t\t\t\tesc = true\n\t\t\t\tstate.push(scanQuoteValue)\n\t\t\t} else if unicode.IsSpace(r) {\n\t\t\t\tstate.pop()\n\t\t\t\tadd.val = line[beg : offset-1]\n\t\t\t\tif esc {\n\t\t\t\t\tadd.val = bytes.Replace(add.val, []byte(\"''\"), []byte(\"'\"), -1)\n\t\t\t\t}\n\t\t\t\td.pairbuf = append(d.pairbuf, add)\n\t\t\t\tadd.attr, add.val, esc = nil, nil, false\n\t\t\t} else {\n\t\t\t\treturn nil, errMissingSpace(line, offset)\n\t\t\t}\n\t\tcase scanQuoteStart:\n\t\t\tstate.pop()\n\t\t\tif r != '\\'' {\n\t\t\t\tbeg++\n\t\t\t\tstate.pop()\n\t\t\t\tstate.push(scanQuoteValue)\n\t\t\t} else {\n\t\t\t\tesc = true\n\t\t\t}\n\t\tcase scanQuoteValue:\n\t\t\tif r == '\\'' {\n\t\t\t\tstate.pop()\n\t\t\t\tstate.push(scanQuoteClose)\n\t\t\t} else if r == '\\n' {\n\t\t\t\treturn nil, errUnterminated(line, offset)\n\t\t\t}\n\t\t}\n\t\toffset += int64(sz)\n\t}\n\tswitch state.top() {\n\tcase scanQuoteValue, scanQuoteStart:\n\t\treturn nil, errUnterminated(line, offset)\n\tcase scanAttr:\n\t\tadd.attr = line[beg:offset]\n\t\tif _, ok := d.attrs[string(add.attr)]; ok {\n\t\t\td.havemulti = true\n\t\t\td.multi[string(add.attr)] = struct{}{}\n\t\t} else {\n\t\t\td.attrs[string(add.attr)] = struct{}{}\n\t\t}\n\t\td.pairbuf = append(d.pairbuf, add)\n\tcase scanValueStart:\n\t\tbeg = offset\n\t\tfallthrough\n\tcase scanQuoteClose:\n\t\toffset--\n\t\tfallthrough\n\tcase scanValue:\n\t\tadd.val = line[beg:offset]\n\t\tif esc {\n\t\t\tadd.val = bytes.Replace(add.val, []byte(\"''\"), []byte(\"'\"), -1)\n\t\t}\n\t\td.pairbuf = append(d.pairbuf, add)\n\t}\n\treturn d.pairbuf, nil\n}", "func (t *tOps) newIterator(f *tFile, slice *util.Range, ro *opt.ReadOptions) iterator.Iterator {\n\tch, err := t.open(f)\n\tif err != nil {\n\t\treturn iterator.NewEmptyIterator(err)\n\t}\n\titer := ch.Value().(*table.Reader).NewIterator(slice, ro)\n\titer.SetReleaser(ch)\n\treturn iter\n}", "func (p *parser) next() field {\n\tf, ok := <-p.fields\n\tif !ok {\n\t\treturn field{fieldEOF, \"\"}\n\t}\n\t// fmt.Println(\"field: \", f)\n\treturn f\n}", "func (w *writer) consume(r io.Reader) error {\n\tbuf := bufio.NewReader(r)\n\n\t// As `IsPageToken` will instruct us to send the _next_ line only, we\n\t// need to call it before the first iteration to allow for the case\n\t// where we want to send right from the beginning.\n\tpastPageToken := w.options.IsPageToken([]byte{})\n\tfor i := 0; i < w.options.Limit; {\n\t\tvar line []byte\n\n\t\tfor {\n\t\t\t// delim can be multiple bytes, so we read till the end byte of it ...\n\t\t\tchunk, err := buf.ReadBytes(w.delimiter())\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tline = append(line, chunk...)\n\t\t\t// ... then we check if the last bytes of line are the same as delim\n\t\t\tif bytes.HasSuffix(line, []byte{w.delimiter()}) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err == io.EOF {\n\t\t\t\ti = w.options.Limit // Implicit exit clause for the loop\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tline = bytes.TrimSuffix(line, []byte{w.delimiter()})\n\t\tif len(line) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// If a page token is given, we need to skip all lines until we've found it.\n\t\t// All remaining lines will then be sent until we reach the pagination limit.\n\t\tif !pastPageToken {\n\t\t\tpastPageToken = w.options.IsPageToken(line)\n\t\t\tcontinue\n\t\t}\n\n\t\tif w.filter() != nil && !w.filter().Match(line) {\n\t\t\tcontinue\n\t\t}\n\t\ti++ // Only increment the counter if the result wasn't skipped\n\n\t\tif err := w.addLine(line); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !pastPageToken && w.options.PageTokenError {\n\t\treturn fmt.Errorf(\"could not find page token\")\n\t}\n\n\treturn w.flush()\n}", "func ReadLineByLine(path string, output chan<- string) {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\toutput <- scanner.Text()\n\t}\n\n\tclose(output)\n}", "func (d *Dao) processHeaderLine(context *tagContext, decoder toolbox.Decoder, lineNumber int) (*toolbox.DelimitedRecord, *Tag, error) {\n\trecord := &toolbox.DelimitedRecord{Delimiter: \",\"}\n\terr := decoder.Decode(record)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\townerName := context.rootObject.GetString(\"Name\")\n\tcontext.tag = NewTag(ownerName, context.source, record.Columns[0], lineNumber)\n\terr = d.processTag(context)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn record, context.tag, nil\n}", "func parse(line string, cb *models.CircularBuffer) {\n\tif string(line[0]) == \"#\" {\n\t\tparseHeader(line, cb)\n\t\treturn\n\t}\n\tif fields != nil {\n\t\thit, err := parseToHit(line)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tcb.HitBy(hit)\n\t}\n}", "func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\tif atEOF && len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tif i := bytes.IndexByte(data, '\\r'); i >= 0 {\n\t\treturn i + 1, data[0:i], nil\n\t}\n\tif i := bytes.IndexByte(data, '\\n'); i >= 0 {\n\t\treturn i + 1, data[0:i], nil\n\t}\n\t// If we're at EOF, we have a final, non-terminated line. Return it.\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\t// Request more data.\n\treturn 0, nil, nil\n}", "func (e *ExportReader) readLine() ([]byte, error) {\n\tline, err := e.buf.ReadBytes('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// trim the trailing newline\n\treturn line[:len(line)-1], nil\n}", "func (lexer *Lexer) next() {\n lexer.current = lexer.source.ReadChar()\n if lexer.current == '\\n' {\n lexer.nextLine()\n } else {\n lexer.nextCol()\n }\n}", "func NextIntsLine() []int {\n\tints := []int{}\n\tintsStr := NextLine()\n\ttmp := strings.Split(intsStr, \" \")\n\tfor _, s := range tmp {\n\t\tinteger, _ := strconv.Atoi(s)\n\t\tints = append(ints, integer)\n\t}\n\treturn ints\n}", "func (parser *PdfParser) readTextLine() (string, error) {\n\tvar r bytes.Buffer\n\tfor {\n\t\tbb, err := parser.reader.Peek(1)\n\t\tif err != nil {\n\t\t\tcommon.Log.Debug(\"Error %s\", err.Error())\n\t\t\treturn r.String(), err\n\t\t}\n\t\tif (bb[0] != '\\r') && (bb[0] != '\\n') {\n\t\t\tb, _ := parser.reader.ReadByte()\n\t\t\tr.WriteByte(b)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn r.String(), nil\n}", "func ReadFunc(r io.Reader, fn func(Line) error) error {\n\ter := NewReader(r)\n\tfor {\n\t\tline, err := er.Read()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = fn(line)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (s *Scanner) next() {\n\tif s.rdOffset < len(s.src) {\n\t\ts.offset = s.rdOffset\n\t\tif s.ch == '\\n' {\n\t\t\ts.lineOffset = s.offset\n\t\t\ts.file.AddLine(s.offset)\n\t\t}\n\t\tr, w := rune(s.src[s.rdOffset]), 1\n\t\tswitch {\n\t\tcase r == 0:\n\t\t\ts.error(s.offset, \"illegal character NUL\")\n\t\tcase r >= utf8.RuneSelf:\n\t\t\t// not ASCII\n\t\t\tr, w = utf8.DecodeRune(s.src[s.rdOffset:])\n\t\t\tif r == utf8.RuneError && w == 1 {\n\t\t\t\ts.error(s.offset, \"illegal UTF-8 encoding\")\n\t\t\t} else if r == bom && s.offset > 0 {\n\t\t\t\ts.error(s.offset, \"illegal byte order mark\")\n\t\t\t}\n\t\t}\n\t\ts.rdOffset += w\n\t\ts.ch = r\n\t} else {\n\t\ts.offset = len(s.src)\n\t\tif s.ch == '\\n' {\n\t\t\ts.lineOffset = s.offset\n\t\t\ts.file.AddLine(s.offset)\n\t\t}\n\t\ts.ch = -1 // eof\n\t}\n}", "func (s *Scanner) Next() (item interface{}, err error) {\n\tresult := s.Parser(s.Input)\n\tsuccess := result.Success\n\tif !success && result.Error != io.EOF {\n\t\tline, col := s.Input.Position()\n\t\treturn result.Item, fmt.Errorf(\"scanner: unmatched at line %v, column %v, item: %v\", line, col, result)\n\t}\n\ts.Input.Collect()\n\treturn result.Item, result.Error\n}", "func (x *Reader) Next() (Xlog, error) {\n\tif err := x.open(); err != nil {\n\t\treturn nil, err\n\t}\n\tvar readOffset int64\n\tfor {\n\t\tline, err := x.ReadCompleteLine()\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tatEOF := err == io.EOF\n\t\tlineLen := int64(len(line))\n\t\treadOffset += lineLen\n\n\t\t// Discard trailing newline and whitespace\n\t\tif lineLen > 0 {\n\t\t\tline = strings.TrimRight(line, \" \\n\\r\\t\")\n\t\t}\n\t\tif !IsPotentialXlogLine(line) {\n\t\t\tif !atEOF {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// EOF with no parseable data: go back to last line.\n\t\t\treturn nil, x.BackToLastCompleteLine()\n\t\t}\n\n\t\tparsedXlog, err := Parse(line, x.SourceKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Xlog %s:%d skipping malformed line %#v\\n\",\n\t\t\t\tx.Path, x.Offset+readOffset-lineLen, line)\n\t\t\tcontinue\n\t\t}\n\t\tx.Offset += readOffset\n\t\tparsedXlog[\":offset\"] = strconv.FormatInt(x.Offset-lineLen, 10)\n\t\treturn parsedXlog, nil\n\t}\n}", "func AddFromReader(r io.Reader, store *Store, name string) error {\n\ts := bufio.NewScanner(r)\n\tfor s.Scan() {\n\t\trt := []rune(s.Text())\n\t\tif len(rt) > 0 {\n\t\t\tstore.Add(name, rt)\n\t\t}\n\t}\n\treturn s.Err()\n}" ]
[ "0.7972559", "0.57942057", "0.57881665", "0.57566863", "0.57329845", "0.5696105", "0.5691073", "0.56656635", "0.56530416", "0.56076425", "0.56019276", "0.5571796", "0.55443066", "0.5499758", "0.54740596", "0.5463015", "0.54396975", "0.5436191", "0.5428282", "0.54164374", "0.54053926", "0.5405193", "0.5403407", "0.53961354", "0.53765774", "0.5371537", "0.53591436", "0.5347729", "0.5297101", "0.5281944", "0.52719533", "0.52623165", "0.5262313", "0.5236448", "0.52337193", "0.5216035", "0.52134967", "0.51961493", "0.5193504", "0.51920253", "0.51758814", "0.5171716", "0.5161451", "0.51541674", "0.5153066", "0.5127051", "0.51077354", "0.5100737", "0.5088414", "0.508316", "0.5049359", "0.50440854", "0.503582", "0.50346106", "0.5032137", "0.5023261", "0.5019048", "0.5013845", "0.5011288", "0.5008679", "0.50055486", "0.50034916", "0.4983496", "0.49823764", "0.49654055", "0.49650565", "0.49530146", "0.49438164", "0.49318892", "0.49224293", "0.49216032", "0.49199042", "0.49196792", "0.4906428", "0.48957148", "0.48908085", "0.488314", "0.48801515", "0.48730594", "0.4861157", "0.48580778", "0.48550525", "0.48501885", "0.4846498", "0.4838671", "0.48376483", "0.483634", "0.48339292", "0.48308703", "0.48274082", "0.4821986", "0.4811879", "0.48118147", "0.4805714", "0.48032162", "0.4788167", "0.47879937", "0.47858047", "0.47846842", "0.477385", "0.47724658" ]
0.0
-1
Sets the bits to true that are true in other. (in place)
func (cb CommitteeBits) Or(other CommitteeBits) { for i := 0; i < len(cb); i++ { cb[i] |= other[i] } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Bitmask) Set(i int, v bool) {\n\tif n := i / 64; n < len(b) {\n\t\tif v {\n\t\t\tb[n] |= uint64(1) << uint64(i%64)\n\t\t} else {\n\t\t\tb[n] &= ^(uint64(1) << uint64(i%64))\n\t\t}\n\t}\n}", "func (z *Int) SetBit(x *Int, i int, b uint) *Int {}", "func (z *Bits) And(x, y Bits) {\n\tif x.Num != y.Num {\n\t\tpanic(\"arguments have different number of bits\")\n\t}\n\tif z.Num != x.Num {\n\t\t*z = New(x.Num)\n\t}\n\tfor i, w := range y.Bits {\n\t\tz.Bits[i] = x.Bits[i] & w\n\t}\n}", "func (b Bitmask) SetAll() {\n\tfor i := range b {\n\t\tb[i] = ^uint64(0)\n\t}\n}", "func (f *Flag) Set() { atomic.CompareAndSwapUint32((*uint32)(unsafe.Pointer(f)), 0, 1) }", "func (b Bits) SetAll() {\n\tfor i := range b.Bits {\n\t\tb.Bits[i] = ^uint64(0)\n\t}\n}", "func (b *Bit) Set(on bool) {\n\talreadyOn := b.ref != nil\n\tif on == alreadyOn {\n\t\t// nothing\n\t} else if on {\n\t\tb.enable()\n\t} else {\n\t\tb.ref.Cancel()\n\t\tb.ref = nil\n\t}\n}", "func (z *Int) SetBits(abs []Word) *Int {}", "func (b *Bitfield) Set(field Bitfield, value bool) {\n\tif value {\n\t\t*b |= field\n\t} else {\n\t\t*b &= Bitfield(^uint8(field))\n\t}\n}", "func (z *Bits) Set(b Bits) {\n\tif z.Num != b.Num {\n\t\t*z = New(b.Num)\n\t}\n\tcopy(z.Bits, b.Bits)\n}", "func (a Bits) Equal(b Bits) bool {\n\tif a.Num != b.Num {\n\t\tpanic(\"receiver and argument have different number of bits\")\n\t}\n\tif a.Num == 0 {\n\t\treturn true\n\t}\n\tlast := len(a.Bits) - 1\n\tfor i, w := range a.Bits[:last] {\n\t\tif w != b.Bits[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn (a.Bits[last]^b.Bits[last])<<uint(len(a.Bits)*64-a.Num) == 0\n}", "func (z *Bits) AndNot(x, y Bits) {\n\tif x.Num != y.Num {\n\t\tpanic(\"arguments have different number of bits\")\n\t}\n\tif z.Num != x.Num {\n\t\t*z = New(x.Num)\n\t}\n\tfor i, w := range y.Bits {\n\t\tz.Bits[i] = x.Bits[i] &^ w\n\t}\n}", "func (m *BoolMatrix) Set(x, y int64, v bool) error {\n\treturn m.bs.Set(m.index(x, y), v)\n}", "func and(c *CPU) {\nc.registers.a = c.registers.a & c.\n}", "func (ab *ABool) Set(b bool) {\n\tvar val int32\n\tif b {\n\t\tval = 1\n\t}\n\tatomic.StoreInt32(&ab.flag, val)\n}", "func SetBit(src []byte, pos uint64, size uint64) []byte {\n\tmask := uint64(1 << pos)\n\tsrcNum := binary.LittleEndian.Uint64(src)\n\n\tret := make([]byte, size)\n\tbinary.LittleEndian.PutUint64(ret, srcNum | mask)\n\treturn ret\n}", "func (b Bits) SetBits(nums ...int) {\n\tfor _, p := range nums {\n\t\tb.SetBit(p, 1)\n\t}\n}", "func and(context *Context) {\n x := context.opcode & 0x0F00 >> 8\n y := context.opcode & 0x00F0 >> 4\n context.cpu.v[x] = context.cpu.v[x] & context.cpu.v[y]\n}", "func SetUnion(s1, s2 map[int]bool) {\n\tfor k := range s2 {\n\t\ts1[k] = true\n\t}\n}", "func setBit(num int, i int) int {\n\treturn num | (1 << i)\n}", "func (m *BitPrecMat) Set(x, y int, to uint32) {\n\tbitOfs := (x + y*m.w) * m.bits\n\tdataI, maskI := bitOfs/32, bitOfs%32\n\tto64 := uint64(to) << (64 - uint64(m.bits) - uint64(maskI))\n\tmask64 := bitMasks[m.bits][maskI]\n\toldData64 := uint64(m.data[dataI])<<32 | uint64(m.data[dataI+1])\n\tnewData64 := (oldData64 & ^mask64) | to64\n\tm.data[dataI] = uint32(newData64 & 0xFFFFFFFF00000000 >> 32)\n\tm.data[dataI+1] = uint32(newData64 & 0xFFFFFFFF)\n}", "func setBit(bitmap []byte, idx int) {\n\tbitmap[idx/8] = bitmap[idx/8] | (1 << uint(idx%8))\n}", "func (pm *Map) SetAll(other *Map) {\n\troot := pm.root\n\tpm.root = union(root, other.root, pm.less, true)\n\troot.decref()\n}", "func Test_BitTwiddle(t *testing.T) {\n\tvar b byte\n\tfor i:=0; i<512; i++ {\n\t\tvar bool1 bool = ((b >> 7) == 1)\n\t\tvar bool2 bool = ((b & 0x80) == 0x80)\n\t\tif bool1 != bool2 {\n\t\t\tt.Fatal()\n\t\t}\n\t\tb++\n\t}\n}", "func setBit(addr uint32, bit uint, val uint) uint32 {\n\tif bit < 0 {\n\t\tpanic(\"negative bit index\")\n\t}\n\n\tif val == 0 {\n\t\treturn addr & ^(1 << (32 - bit))\n\t} else if val == 1 {\n\t\treturn addr | (1 << (32 - bit))\n\t} else {\n\t\tpanic(\"set bit is not 0 or 1\")\n\t}\n}", "func OnePointBool(a, b []bool) []bool {\n\tif len(a) != len(b) {\n\t\tpanic(\"expected slices to have same length\")\n\t}\n\tchild := make([]bool, len(a))\n\tcopy(child, a)\n\tfor i := rand.Intn(len(a)); i < len(a); i++ {\n\t\tchild[i] = b[i]\n\t}\n\treturn child\n}", "func (a *atomicBool) Set(boolValue bool) bool {\n\tintValue := int32(falseValue)\n\tif boolValue {\n\t\tintValue = trueValue\n\t}\n\treturn toTruthy(atomic.SwapInt32(&a.value, intValue))\n}", "func SetBit(b byte, idx uint, flag bool) byte {\n\tif idx < 0 || idx > 7 {\n\t\tlog.Panic(\"the idx must be from 0 to 7\")\n\t}\n\tif flag {\n\t\treturn b | (1 << idx)\n\t}\n\treturn b &^ (1 << idx)\n}", "func updateBit(num int, i int, valIs1 bool) int {\n\t// set our bit value\n\tval := 0\n\tif valIs1 {\n\t\tval = 1\n\t}\n\t// create a mask to clear the ith bit in our number\n\tclearMask := ^(1 << i)\n\t// create a mask to set the ith bit in our number\n\tvalueMask := val << i\n\treturn (num & clearMask) | valueMask\n}", "func (r *R1_eg) setBit(idx1 int, value int) {\n\tr.Values[idx1] = value\n}", "func BoolMap(src map[string]*bool) map[string]bool {\n\tdst := make(map[string]bool)\n\tfor k, val := range src {\n\t\tif val != nil {\n\t\t\tdst[k] = *val\n\t\t}\n\t}\n\treturn dst\n}", "func (b *bitVec) set(n uint) bool {\n\tpos, slot := b.calculateBitLocation(n)\n\tif b.get(n) { // bit was set\n\t\treturn true\n\t} else { // set the bit\n\t\tb.bits[pos] = b.bits[pos] | 1<<slot\n\t\treturn false\n\t}\n}", "func (cpu *Cpu) and(addr int) {\n\tdata := cpu.mem.Read(addr)\n\tcpu.ac &= data\n\n\t// flags: sign, zero.\n\tcpu.p.setN(cpu.ac)\n\tcpu.p.setZ(cpu.ac)\n}", "func (bs *BitSet) AndNotBit(i int32, value bool) {\n\tif (i + 1) < 1 {\n\t\tpanic(fmt.Sprintf(\"IndexOutOfBoundsException: i=%v\", i))\n\t}\n\tif value {\n\t\tbs.Clear(i)\n\t}\n}", "func Test_BitTwiddle(t *testing.T) {\n\tvar b byte\n\tfor i := 0; i < 512; i++ {\n\t\tvar bool1 bool = ((b >> 7) == 1)\n\t\tvar bool2 bool = ((b & 0x80) == 0x80)\n\t\tif bool1 != bool2 {\n\t\t\tt.Fatal()\n\t\t}\n\t\tb++\n\t}\n}", "func (bf *BloomFilter) setKeyToBool(key []byte, b bool) error {\n\tfor i := uint32(0); i < bf.hashes; i++ {\n\t\th := bf.hashPayload(key, i)\n\t\tif err := bf.db.SetBit(h, b); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f Flags) Set(v Flags) {\n\tf = f | v\n}", "func SetBits(z *big.Int, abs []big.Word) *big.Int {\n\treturn z.SetBits(abs)\n}", "func bool_xor(A, B bool) bool {\n return (A && !B) || (!A && B)\n}", "func (z *Bits) Xor(x, y Bits) {\n\tif x.Num != y.Num {\n\t\tpanic(\"arguments have different number of bits\")\n\t}\n\tif z.Num != x.Num {\n\t\t*z = New(x.Num)\n\t}\n\tfor i, w := range y.Bits {\n\t\tz.Bits[i] = x.Bits[i] ^ w\n\t}\n}", "func coalesceBool(lhs *bool, rhs *bool) {\n\t*lhs = *lhs || *rhs\n\t*rhs = false\n}", "func setBit(bitboard uint64, square int) uint64 {\n\treturn bitboard | (1 << square)\n}", "func (bitmap *bitmap) Xor(other *bitmap) *bitmap {\n\tif bitmap.Size != other.Size {\n\t\tpanic(\"size not the same\")\n\t}\n\n\tdistance := newBitmap(bitmap.Size)\n\tdiv, mod := distance.Size/8, distance.Size%8\n\n\tfor i := 0; i < div; i++ {\n\t\tdistance.data[i] = bitmap.data[i] ^ other.data[i]\n\t}\n\n\tfor i := div * 8; i < div*8+mod; i++ {\n\t\tdistance.set(i, bitmap.Bit(i)^other.Bit(i))\n\t}\n\n\treturn distance\n}", "func clearbit(addr *uint64, n uint32)", "func (z *Bits) Or(x, y Bits) {\n\tif x.Num != y.Num {\n\t\tpanic(\"arguments have different number of bits\")\n\t}\n\tif z.Num != x.Num {\n\t\t*z = New(x.Num)\n\t}\n\tfor i, w := range y.Bits {\n\t\tz.Bits[i] = x.Bits[i] | w\n\t}\n}", "func (self *AssessModule) SameBits(am *AssessModule) bool {\n if (self == am) { return true }\n for i := 0; i < 8; i++ {\n if (self.bits[i] != am.bits[i]) {\n return false\n }\n }\n return true\n}", "func (s Set) Set(i int, v bool) {\n\tif v {\n\t\ts[i>>6] |= 1 << uint(i&0x3F)\n\t} else {\n\t\ts[i>>6] &= ^(1 << uint(i&0x3F))\n\t}\n}", "func Set(data []uintptr, bitIdx int) {\n\t// Unsigned division by a power-of-2 constant compiles to a right-shift,\n\t// while signed does not due to negative nastiness.\n\tdata[uint(bitIdx)/BitsPerWord] |= 1 << (uint(bitIdx) % BitsPerWord)\n}", "func (b Bits) AllOnes() bool {\n\tlast := len(b.Bits) - 1\n\tfor _, w := range b.Bits[:last] {\n\t\tif w != ^uint64(0) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn ^b.Bits[last]<<uint(64*len(b.Bits)-b.Num) == 0\n}", "func (b1 *BitSet) And(b2 *BitSet) *BitSet {\n\tb3 := new(BitSet)\n\tb3.Bits.And(&b1.Bits, &b2.Bits)\n\treturn b3\n}", "func IntSetBits(z *big.Int, abs []big.Word,) *big.Int", "func main() {\n\tvar a uint8 = 0\n\t//a = a | 196\n\ta |= 196\n\tfmt.Printf(\"%b - %d\\n\", a, a)\n\ta |= 1\n\tfmt.Printf(\"%b - %d\\n\", a, a)\n\n}", "func union(a, b map[string]bool) {\n\tfor k, v := range b {\n\t\tif v {\n\t\t\ta[k] = v\n\t\t}\n\t}\n}", "func (am AttributeMap) UpsertBool(k string, v bool) {\n\tif av, existing := am.Get(k); existing {\n\t\tav.SetBoolVal(v)\n\t} else {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValueBool(k, v))\n\t}\n}", "func (am AttributeMap) UpsertBool(k string, v bool) {\n\tif av, existing := am.Get(k); existing {\n\t\tav.SetBoolVal(v)\n\t} else {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValueBool(k, v))\n\t}\n}", "func (z *Bits) Not(b Bits) {\n\tif z.Num != b.Num {\n\t\t*z = New(b.Num)\n\t}\n\tfor i, w := range b.Bits {\n\t\tz.Bits[i] = ^w\n\t}\n}", "func (access BoolAccess) Set(row int, val bool) {\n access.rawData[access.indices[row]] = val\n}", "func extendBoolPtr(m **bool, ext **bool) {\n\tif ext != nil && *ext != nil {\n\t\t*m = *ext\n\t}\n}", "func (b1 *BitSet) AndWith(b2 *BitSet) *BitSet {\n\tb1.Bits.And(&b1.Bits, &b2.Bits)\n\treturn b1\n}", "func (b Bits) Set(n int) Bits {\n\treturn b | (1 << uint64(n))\n}", "func (b *Array) SetBit(x *Array, i int, a uint) *Array {\n\tb.Int.SetBit(x.Int, i, a)\n\treturn b\n}", "func (bitmap *bitmap) set(index int, bit int) {\n\tif index >= bitmap.Size {\n\t\tpanic(\"index out of range\")\n\t}\n\n\tdiv, mod := index/8, index%8\n\tshift := byte(1 << uint(7-mod))\n\n\tbitmap.data[div] &= ^shift\n\tif bit > 0 {\n\t\tbitmap.data[div] |= shift\n\t}\n}", "func set(cpu *CPU, r, b byte) byte {\n\treturn r | (1 << b)\n}", "func (bs *BitSet) AndNotRangeBitSet(i, j int32, b *BitSet) {\n\tbs.setScanner(i, j, b, andNotStrategy)\n}", "func verifyAnd(a, b, and *bitmap.Wahl) error {\n\ta_map := mapArray(a.Bits())\n\tb_map := mapArray(b.Bits())\n\tand_map := mapArray(and.Bits())\n\tref_map := andMaps(a_map, b_map)\n\tcompareMaps(\"verify AND map\", and_map, ref_map)\n\tfor _, bit := range and.Bits() {\n\t\t// bit must be in both maps for AND\n\t\tif !(a_map[bit] && b_map[bit]) {\n\t\t\treturn errors.Bug(\"AND: bit %d is not set in both maps\\n\", bit)\n\t\t}\n\t}\n\treturn nil\n}", "func bitOpOnMem(a []uint32, b, c, d uint32) {\n\t// amd64:`ANDL\\s[$]200,\\s\\([A-Z][A-Z0-9]+\\)`\n\ta[0] &= 200\n\t// amd64:`ORL\\s[$]220,\\s4\\([A-Z][A-Z0-9]+\\)`\n\ta[1] |= 220\n\t// amd64:`XORL\\s[$]240,\\s8\\([A-Z][A-Z0-9]+\\)`\n\ta[2] ^= 240\n}", "func (n *Uint256) And(n2 *Uint256) *Uint256 {\n\tn.n[0] &= n2.n[0]\n\tn.n[1] &= n2.n[1]\n\tn.n[2] &= n2.n[2]\n\tn.n[3] &= n2.n[3]\n\treturn n\n}", "func (b *BoolMatrixLinear) SetBool(i, j int, value bool) bool {\n\tif i > b.heigh || j > b.width {\n\t\treturn false\n\t}\n\tb.matrix[i*b.width+j] = value\n\treturn true\n}", "func Set(value byte, bit byte) byte {\n\treturn value | (1 << bit)\n}", "func (b1 *BitSet) AndNot(b2 *BitSet) *BitSet {\n\tb3 := new(BitSet)\n\tb3.Bits.AndNot(&b1.Bits, &b2.Bits)\n\treturn b3\n}", "func clearBit_(bits *uint64, n uint64) {\n\t(*bits) &^= 1 << n\n}", "func TwoPointBool(a, b []bool) []bool {\n\tif len(a) != len(b) {\n\t\tpanic(\"expected slices to have same length\")\n\t}\n\tchild := make([]bool, len(a))\n\tcopy(child, a)\n\tstart, end := rand.Intn(len(a)), rand.Intn(len(a))\n\tif start > end {\n\t\tstart, end = end, start\n\t}\n\tfor i := start; i < end; i++ {\n\t\tchild[i] = b[i]\n\t}\n\treturn child\n}", "func testSet(i Instruction, ls *LuaState) {\n\ta, b, c := i.ABC()\n\ta += 1\n\tb += 1\n\n\tif luaToBoolean(ls, b) == (c != 0) {\n\t\tluaCopy(ls, b, a)\n\t} else {\n\t\tls.addPC(1)\n\t}\n}", "func orIdentity(a *bmatrix) {\n\tfor i := 0; i < n; i++ {\n\t\ta[i][i] = true\n\t}\n}", "func And(x, y reflect.Value) reflect.Value {\n\tmustSameType(x, y)\n\tz := reflect.New(x.Type()).Elem()\n\tswitch x.Type().Kind() {\n\tcase reflect.Int:\n\t\txx := int(x.Int())\n\t\tyy := int(y.Int())\n\t\tzz := int64(xx & yy)\n\t\tz.SetInt(zz)\n\t\treturn z\n\tcase reflect.Int8:\n\t\txx := int8(x.Int())\n\t\tyy := int8(y.Int())\n\t\tzz := int64(xx & yy)\n\t\tz.SetInt(zz)\n\t\treturn z\n\tcase reflect.Int16:\n\t\txx := int16(x.Int())\n\t\tyy := int16(y.Int())\n\t\tzz := int64(xx & yy)\n\t\tz.SetInt(zz)\n\t\treturn z\n\tcase reflect.Int32:\n\t\txx := int32(x.Int())\n\t\tyy := int32(y.Int())\n\t\tzz := int64(xx & yy)\n\t\tz.SetInt(zz)\n\t\treturn z\n\tcase reflect.Int64:\n\t\txx := int64(x.Int())\n\t\tyy := int64(y.Int())\n\t\tzz := int64(xx & yy)\n\t\tz.SetInt(zz)\n\t\treturn z\n\tcase reflect.Uint:\n\t\txx := uint(x.Uint())\n\t\tyy := uint(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\tcase reflect.Uint8:\n\t\txx := uint8(x.Uint())\n\t\tyy := uint8(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\tcase reflect.Uint16:\n\t\txx := uint16(x.Uint())\n\t\tyy := uint16(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\tcase reflect.Uint32:\n\t\txx := uint32(x.Uint())\n\t\tyy := uint32(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\tcase reflect.Uint64:\n\t\txx := uint64(x.Uint())\n\t\tyy := uint64(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\tcase reflect.Uintptr:\n\t\txx := uintptr(x.Uint())\n\t\tyy := uintptr(y.Uint())\n\t\tzz := uint64(xx & yy)\n\t\tz.SetUint(zz)\n\t\treturn z\n\t}\n\tpanic(fmt.Sprintf(\"operator & not defined on %v\", x.Type()))\n}", "func BoolPtrMap(src map[string]bool) map[string]*bool {\n\tdst := make(map[string]*bool)\n\tfor k, val := range src {\n\t\tv := val\n\t\tdst[k] = &v\n\t}\n\treturn dst\n}", "func bit(cpu *CPU, r, b byte) {\n\tbit := (r>>b)&1 == 0\n\tcpu.SetZero(bit)\n\tcpu.SetNegative(false)\n\tcpu.SetHalfCarry(true)\n}", "func BoolS(a []bool, b []bool) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (b *Boolean) Reset() {\n\tb.Value = false\n\tb.Default = false\n\tb.Initialized = false\n\tBooleanPool.Put(b)\n}", "func (bs *BitSet) AndNotBitSet(b *BitSet) {\n\tbmin := bs.bitsLength\n\tif b.bitsLength < bmin {\n\t\tbmin = b.bitsLength\n\t}\n\tbs.setScanner(0, bmin, b, andNotStrategy)\n}", "func (v *Set) Bits(subset Set) uint64 {\n\tret := uint64(0)\n\n\tif len(subset) == 0 {\n\t\treturn ret\n\t}\n\n\tfor _, cmpElem := range subset {\n\t\tfor i, elem := range *v {\n\t\t\tif bytes.Equal(elem.Bytes(), cmpElem.Bytes()) {\n\t\t\t\tret |= 1 << uint(i) // flip the i-th bit to 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret\n}", "func all_on (inp uint32, filter uint32) int8 {\n inp &= filter;\n\n if (inp == filter) {\n return 1;\n }\n\n if (inp == 0) {\n return -1;\n }\n\n return 0;\n}", "func (b Bits) SetBit(n, x int) {\n\tif n < 0 || n >= b.Num {\n\t\tpanic(\"bit number out of range\")\n\t}\n\tif x == 0 {\n\t\tb.Bits[n>>6] &^= 1 << uint(n&63)\n\t} else {\n\t\tb.Bits[n>>6] |= 1 << uint(n&63)\n\t}\n}", "func BitFieldContainsAll(a, b BitField) (bool, error) {\n\taruns, err := a.RunIterator()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tbruns, err := b.RunIterator()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Remove any elements in a from b. If b contains bits not in a, some\n\t// bits will remain.\n\tcombined, err := rlepluslazy.Subtract(bruns, aruns)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn isEmpty(combined)\n}", "func (b ButtonState) DiffMask(other ButtonState) ButtonState {\n\tvar result ButtonState\n\tresult[0] = b[0] ^ other[0]\n\tresult[1] = b[1] ^ other[1]\n\tresult[2] = b[2] ^ other[2]\n\treturn result\n}", "func xor(b1, b2 bool) bool {\n\treturn (b1 || b2) && !(b1 && b2)\n}", "func compatible(a uint32, b uint32) int8 {\n // first grab only the bits that differ\n var diff uint32 = a ^ b;\n // then check that they all differ in the same way\n return all_on(a, diff);\n}", "func SetBit(b byte, bitN int) byte {\n\tif bitN <= 0 {\n\t\treturn b\n\t}\n\treturn b | byte(1<<byte(bitN)-1)\n}", "func SetBit(n int, pos uint, val int) int {\n\tn |= (val << pos)\n\treturn n\n}", "func Bools(k string, v []bool) Field {\n\treturn Field{Key: k, Value: valf.Bools(v)}\n}", "func setBitInByte(b byte, indexInByte uint32, bit byte) byte {\n\tvar mask byte = 0x80\n\tmask = mask >> uint(indexInByte)\n\n\tif bit == 0 {\n\t\tmask = ^mask\n\t\tb = b & mask\n\t} else if bit == 1 {\n\t\tb = b | mask\n\t}\n\treturn b\n}", "func (i *SafeBool) Set(val bool) {\n\ti.m.Lock()\n\tdefer i.m.Unlock()\n\ti.val = val\n}", "func XNor(a, b Dense) Dense {\n\tshort, long := a, b\n\tif b.len < a.len {\n\t\tshort, long = b, a\n\t}\n\tr := Dense{\n\t\tbits: make([]byte, 0, BytesFor(long.len)),\n\t\tlen: long.len,\n\t\tnegated: a.negated == b.negated,\n\t}\n\tfor i := range short.bits {\n\t\tr.bits = append(r.bits, ^(a.bits[i] ^ b.bits[i]))\n\t}\n\tvar trail byte\n\tif a.negated {\n\t\ttrail = 0xFF\n\t}\n\tfor i := len(short.bits); i < len(long.bits); i++ {\n\t\tr.bits = append(r.bits, ^(trail ^ long.bits[i]))\n\t}\n\treturn r\n}", "func (b *BoolMatrixLinear) SetByNumber(num *big.Int) bool {\n\tslice := num.Bytes()\n\tdif := 0\n\n\tswitch {\n\tcase len(b.matrix) < len(slice)*8:\n\t\tdif = (len(slice)*8 - len(b.matrix))\n\t\tvar bitMask byte\n\t\tswitch dif {\n\t\tcase 1:\n\t\t\tbitMask = 128\n\t\tcase 2:\n\t\t\tbitMask = 192\n\t\tcase 3:\n\t\t\tbitMask = 224\n\t\tcase 4:\n\t\t\tbitMask = 240\n\t\tcase 5:\n\t\t\tbitMask = 248\n\t\tcase 6:\n\t\t\tbitMask = 252\n\t\tcase 7:\n\t\t\tbitMask = 254\n\t\t}\n\t\tvar subByte byte\n\t\tfor i := 1; i < len(slice); i++ {\n\t\t\tsubByte = (slice[i] & bitMask) >> (8 - dif)\n\t\t\tslice[i-1] = (slice[i-1] << dif) | subByte\n\t\t}\n\t\tslice[len(slice)-1] = slice[len(slice)-1] << dif\n\t\t//return false\n\tcase len(b.matrix) > len(slice)*8:\n\t\tslice = append(make([]byte, ((len(b.matrix)-len(slice)*8)/8)+1), slice...)\n\t\tdif = (len(slice)*8 - len(b.matrix))\n\t\tvar bitMask byte\n\t\tswitch dif {\n\t\tcase 1:\n\t\t\tbitMask = 128\n\t\tcase 2:\n\t\t\tbitMask = 192\n\t\tcase 3:\n\t\t\tbitMask = 224\n\t\tcase 4:\n\t\t\tbitMask = 240\n\t\tcase 5:\n\t\t\tbitMask = 248\n\t\tcase 6:\n\t\t\tbitMask = 252\n\t\tcase 7:\n\t\t\tbitMask = 254\n\t\t}\n\t\tvar subByte byte\n\t\tfor i := 1; i < len(slice); i++ {\n\t\t\tsubByte = (slice[i] & bitMask) >> (8 - dif)\n\t\t\tslice[i-1] = (slice[i-1] << dif) | subByte\n\t\t}\n\t\tslice[len(slice)-1] = slice[len(slice)-1] << dif\n\t}\n\tb.SetMatrix(slice)\n\treturn true\n}", "func (f BooleanField) Set(val interface{}) FieldAssignment {\n\treturn FieldAssignment{\n\t\tField: f,\n\t\tValue: val,\n\t}\n}", "func (me *TxsdRedefineTimeSyncTokenTypeComplexContentRestrictionDeviceInHand) Set(s string) {\n\t(*sac.TbooleanType)(me).Set(s)\n}", "func SetBit(x *big.Int, i int, b uint) *big.Int {\n\treturn new(big.Int).SetBit(x, i, b)\n}", "func xor(x, y bool) bool {\n\treturn (x && !y) || (!x && y)\n}", "func (cf *ComponentFilter) Allow(other *bitset.BitSet) bool {\n\tif cf == nil {\n\t\treturn false\n\t}\n\n\tif cf.Required != nil && !cf.Required.Empty() {\n\t\tif !other.ContainsAll(cf.Required) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif cf.OneRequired != nil {\n\t\tif !cf.OneRequired.Intersects(other) && !cf.OneRequired.Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif cf.Forbidden != nil && !cf.Forbidden.Empty() {\n\t\tif cf.Forbidden.Intersects(other) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (b *BitMap) Set(offset uint64) {\n\n\tb.checkOffset(offset)\n\tindex, bit := indexAndOverbit(offset)\n\tcount := uint64(1 << bit)\n\n\tb.store[index] = b.store[index] | count\n}" ]
[ "0.59725237", "0.5930509", "0.579683", "0.5777209", "0.5720275", "0.5711428", "0.56848454", "0.5675211", "0.5655252", "0.565407", "0.55666703", "0.5553205", "0.5493303", "0.54871905", "0.5435499", "0.54231036", "0.54203176", "0.54054356", "0.53756917", "0.53497154", "0.53330916", "0.5330592", "0.53260565", "0.53224874", "0.53185934", "0.5296948", "0.5288688", "0.52837956", "0.5267895", "0.52672076", "0.5250017", "0.52353185", "0.52284086", "0.52097875", "0.52051985", "0.51738167", "0.51534253", "0.51488274", "0.51413316", "0.51301104", "0.51267225", "0.5123078", "0.5118691", "0.5114936", "0.51108795", "0.51022", "0.50954723", "0.5076955", "0.5052338", "0.5042359", "0.50365335", "0.5036003", "0.50347793", "0.50236493", "0.50236493", "0.5011696", "0.50077087", "0.5003971", "0.50018907", "0.49970075", "0.4996124", "0.49898654", "0.4986861", "0.49722943", "0.49594605", "0.49561977", "0.49552143", "0.49427384", "0.49390376", "0.49211", "0.49173415", "0.49140817", "0.49122494", "0.49043", "0.49024403", "0.49011326", "0.4900917", "0.48974502", "0.48796907", "0.4872062", "0.48642808", "0.48577717", "0.48521", "0.48404455", "0.48389366", "0.4838243", "0.48237163", "0.4815116", "0.4812631", "0.48087326", "0.48069578", "0.4806472", "0.48041406", "0.48030794", "0.4802871", "0.47999462", "0.4793788", "0.4783142", "0.4779386", "0.47743267" ]
0.53828317
18
Inplace filters a list of committees indices to only keep the bitfield participants. The result is not sorted. Returns the resliced filtered participants list.
func (cb CommitteeBits) FilterParticipants(committee []ValidatorIndex) []ValidatorIndex { bitLen := cb.BitLen() out := committee[:0] if bitLen != uint64(len(committee)) { panic("committee mismatch, bitfield length does not match") } for i := uint64(0); i < bitLen; i++ { if cb.GetBit(i) { out = append(out, committee[i]) } } return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (c *Curator) filterPendingPieces(ids []core.TractID) (out []core.TractID) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tout = ids[:0]\n\tfor _, id := range ids {\n\t\tif _, ok := c.pendingPieces[id]; !ok {\n\t\t\tout = append(out, id)\n\t\t}\n\t}\n\treturn\n}", "func Filter(peers []Peer, f func(Peer) bool) []Peer {\n\tfiltered := make([]Peer, 0)\n\n\tfor _, peer := range peers {\n\t\tif f(peer) {\n\t\t\tfiltered = append(filtered, peer)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func filterPlayers(originalPlayers Players) Players {\n\tfilterPlayersMap := make(map[string]Player, len(originalPlayers))\n\tfor _, player := range originalPlayers {\n\t\tfilterPlayersMap[player.FullName] = player\n\t}\n\n\tplayers := make(Players, 0, len(filterPlayersMap))\n\tfor _, player := range filterPlayersMap {\n\t\tplayers = append(players, player)\n\t}\n\n\treturn players\n}", "func FilterOutInPlace(input []Expression, filter func(Expression) bool) (remained, filteredOut []Expression) {\n\ttrace_util_0.Count(_util_00000, 4)\n\tfor i := len(input) - 1; i >= 0; i-- {\n\t\ttrace_util_0.Count(_util_00000, 6)\n\t\tif filter(input[i]) {\n\t\t\ttrace_util_0.Count(_util_00000, 7)\n\t\t\tfilteredOut = append(filteredOut, input[i])\n\t\t\tinput = append(input[:i], input[i+1:]...)\n\t\t}\n\t}\n\ttrace_util_0.Count(_util_00000, 5)\n\treturn input, filteredOut\n}", "func (cp *MultiStrategy) Filter() ([]peer.ID, error) {\n\tpeerIDs := make([]peer.ID, 0)\n\tdupCheck := make(map[string]bool)\n\n\t// add all filters\n\tfor _, filter := range cp.filters {\n\t\tpeers, err := filter.Filter()\n\t\tif err != nil {\n\t\t\treturn peerIDs, err\n\t\t}\n\t\tfor _, peerID := range peers {\n\t\t\tif _, ok := dupCheck[peerID.Pretty()]; !ok {\n\t\t\t\tdupCheck[peerID.Pretty()] = true\n\t\t\t\tpeerIDs = append(peerIDs, peerID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// add extra peers\n\tfor _, peerID := range cp.peerIDs {\n\t\tif _, ok := dupCheck[peerID.Pretty()]; !ok {\n\t\t\tdupCheck[peerID.Pretty()] = true\n\t\t\tpeerIDs = append(peerIDs, peerID)\n\t\t}\n\t}\n\n\treturn peerIDs, nil\n}", "func filterDataMembers(mems []pubcluster.MemberInfo) []pubcluster.MemberInfo {\n\tdi := len(mems)\nloop:\n\tfor i := 0; i < di; i++ {\n\t\tif mems[i].LiteMember {\n\t\t\t// order is not important, delete by moving deleted items to the end.\n\t\t\t// find the first non-lite member\n\t\t\tdi--\n\t\t\tfor mems[di].LiteMember {\n\t\t\t\tif di <= i {\n\t\t\t\t\t// no more data members left\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t\tdi--\n\t\t\t}\n\t\t\tmems[i], mems[di] = mems[di], mems[i]\n\t\t}\n\t}\n\t// all deleted items are at the end.\n\t// shrink the slice to get rid of them.\n\treturn mems[:di]\n}", "func FilterCommits(dbName string, commits []github.RepositoryCommit) []github.RepositoryCommit {\n\tvar filtered []github.RepositoryCommit\n\n\tfor _, commit := range commits {\n\t\tif IsValidCommit(*commit.Commit.Message) &&\n\t\t\tGetSHA(dbName, *commit.SHA) == false {\n\n\t\t\tfiltered = append(filtered, commit)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func (d *Deduplicator) Filter(trans []schema.XMLTransaction) []schema.XMLTransaction {\n\tif d.state.IsZero() {\n\t\treturn trans\n\t}\n\tvar res []schema.XMLTransaction\n\tfor _, tran := range trans {\n\t\tif !d.state.Filter(tran) {\n\t\t\tres = append(res, tran)\n\t\t}\n\t}\n\treturn res\n}", "func (_Token *TokenFilterer) FilterMintFrozen(opts *bind.FilterOpts, to []common.Address) (*TokenMintFrozenIterator, error) {\n\n\tvar toRule []interface{}\n\tfor _, toItem := range to {\n\t\ttoRule = append(toRule, toItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.FilterLogs(opts, \"MintFrozen\", toRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenMintFrozenIterator{contract: _Token.contract, event: \"MintFrozen\", logs: logs, sub: sub}, nil\n}", "func filter_by_non_replica(membership_server *Server, active_replicas []string) []string{\n\tvar result []string\n\tfor _, node := range FS_NODES {\n\t\tif membership_server.MembershipMap[to_membership_node(node)].Status == FAILED_REMOVAL {\n\t\t\tcontinue\n\t\t}\n\t\tflag := 1\n\t\tfor _, replica := range active_replicas {\n\t\t\tif replica == node {\n\t\t\t\tflag = 0\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif flag == 1 {\n\t\t\tresult = append(result, node)\n\t\t}\n\t}\n\treturn result\n}", "func FilterInts(x []int, filter func(int) bool) []int {\n\ty := x[:0]\n\tfor _, v := range x {\n\t\tif filter(v) {\n\t\t\ty = append(y, v)\n\t\t}\n\t}\n\treturn y\n}", "func filterClustersWithIndices(elements [][]float64, indices []int) [][]float64 {\n\tvar ret [][]float64\n\tfor index, value := range elements {\n\t\tvar includes bool\n\t\tfor _, idx := range indices {\n\t\t\tif index == idx {\n\t\t\t\tincludes = true\n\t\t\t}\n\t\t}\n\n\t\tif !includes {\n\t\t\tret = append(ret, value)\n\t\t}\n\t}\n\treturn ret\n}", "func Filter(vs []int, f func(int) bool) []int {\n\tvsf := make([]int, 0)\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\tvsf = append(vsf, v)\n\t\t}\n\t}\n\treturn vsf\n}", "func filterAddrs(addrs []ma.Multiaddr, f func(a ma.Multiaddr) bool) (filtered, rest []ma.Multiaddr) {\n\tj := 0\n\tfor i := 0; i < len(addrs); i++ {\n\t\tif f(addrs[i]) {\n\t\t\taddrs[i], addrs[j] = addrs[j], addrs[i]\n\t\t\tj++\n\t\t}\n\t}\n\treturn addrs[:j], addrs[j:]\n}", "func (s *SliceOfUint) Filter(filterFunc func(uint) bool) *SliceOfUint {\n\tvar newItems []uint\n\tfor _, value := range s.items {\n\t\tif filterFunc(value) {\n\t\t\tnewItems = append(newItems, value)\n\t\t}\n\t}\n\treturn s\n}", "func Filter(peptides types.Peptides, genes types.Genes) types.Peptides {\n\tfilteredPeptides := make(types.Peptides, len(peptides))\n\tfor peptide := range peptides {\n\t\tfilteredPeptides[peptide] = peptides[peptide].Copy()\n\t\tkeepGenes := make([]string, 0)\n\t\tfor _, gene := range filteredPeptides[peptide].Genes {\n\t\t\tif _, ok := genes[gene]; ok {\n\t\t\t\tkeepGenes = append(keepGenes, gene)\n\t\t\t}\n\t\t}\n\t\tfilteredPeptides[peptide].Genes = keepGenes\n\t}\n\treturn filteredPeptides\n}", "func removeSliceElements(txOuts []*apitypes.AddressTxnOutput, inds []int) []*apitypes.AddressTxnOutput {\n\t// Remove entries from the end to the beginning of the slice.\n\tsort.Slice(inds, func(i, j int) bool { return inds[i] > inds[j] }) // descending indexes\n\tfor _, g := range inds {\n\t\tif g > len(txOuts)-1 {\n\t\t\tcontinue\n\t\t}\n\t\ttxOuts[g] = txOuts[len(txOuts)-1] // overwrite element g with last element\n\t\ttxOuts[len(txOuts)-1] = nil // nil out last element\n\t\ttxOuts = txOuts[:len(txOuts)-1]\n\t}\n\treturn txOuts\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) FilterConflictingPublicKeySubmitted(opts *bind.FilterOpts, submittingMember []common.Address) (*BondedECDSAKeepConflictingPublicKeySubmittedIterator, error) {\n\n\tvar submittingMemberRule []interface{}\n\tfor _, submittingMemberItem := range submittingMember {\n\t\tsubmittingMemberRule = append(submittingMemberRule, submittingMemberItem)\n\t}\n\n\tlogs, sub, err := _BondedECDSAKeep.contract.FilterLogs(opts, \"ConflictingPublicKeySubmitted\", submittingMemberRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BondedECDSAKeepConflictingPublicKeySubmittedIterator{contract: _BondedECDSAKeep.contract, event: \"ConflictingPublicKeySubmitted\", logs: logs, sub: sub}, nil\n}", "func (xdcrf *XDCRFactory) filterVBList(targetkvVBList []uint16, kv_vb_map map[string][]uint16) []uint16 {\n\tret := []uint16{}\n\tfor _, vb := range targetkvVBList {\n\t\tfor _, sourcevblist := range kv_vb_map {\n\t\t\tfor _, sourcevb := range sourcevblist {\n\t\t\t\tif sourcevb == vb {\n\t\t\t\t\tret = append(ret, vb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret\n}", "func (w *WaitSet) Filter(l []int) []int {\n\tret := make([]int, 0, len(l))\n\tw.m.RLock()\n\tdefer w.m.RUnlock()\n\tfor _, v := range l {\n\t\tidx, prev := w.Index(v)\n\t\tif w.check(v, idx, prev) {\n\t\t\tret = append(ret, v)\n\t\t}\n\t}\n\tif len(ret) == 0 {\n\t\treturn nil\n\t}\n\treturn ret\n}", "func (candidate *Candidate) getFilteredUpdates() []*stake {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\tvar updates []*stake\n\tfor _, update := range candidate.updates {\n\t\t// skip updates with 0 stakes\n\t\tupdate.lock.RLock()\n\t\tif update.Value.Cmp(big.NewInt(0)) != 1 {\n\t\t\tupdate.lock.RUnlock()\n\t\t\tcontinue\n\t\t}\n\n\t\t// merge updates\n\t\tmerged := false\n\t\tfor _, u := range updates {\n\n\t\t\tu.lock.Lock()\n\t\t\tif u.Coin == update.Coin && u.Owner == update.Owner {\n\t\t\t\tu.Value = big.NewInt(0).Add(u.Value, update.Value)\n\t\t\t\tu.lock.Unlock()\n\n\t\t\t\tmerged = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tu.lock.Unlock()\n\t\t}\n\n\t\tupdate.lock.RUnlock()\n\n\t\tif !merged {\n\t\t\tupdates = append(updates, update)\n\t\t}\n\t}\n\n\treturn updates\n}", "func (_Contracts *ContractsFilterer) FilterVerified(opts *bind.FilterOpts, _voter []*big.Int, _proposal []*big.Int, _position []*big.Int) (*ContractsVerifiedIterator, error) {\n\n\tvar _voterRule []interface{}\n\tfor _, _voterItem := range _voter {\n\t\t_voterRule = append(_voterRule, _voterItem)\n\t}\n\tvar _proposalRule []interface{}\n\tfor _, _proposalItem := range _proposal {\n\t\t_proposalRule = append(_proposalRule, _proposalItem)\n\t}\n\tvar _positionRule []interface{}\n\tfor _, _positionItem := range _position {\n\t\t_positionRule = append(_positionRule, _positionItem)\n\t}\n\n\tlogs, sub, err := _Contracts.contract.FilterLogs(opts, \"Verified\", _voterRule, _proposalRule, _positionRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractsVerifiedIterator{contract: _Contracts.contract, event: \"Verified\", logs: logs, sub: sub}, nil\n}", "func filterTargets(peers []fab.Peer, filter resmgmt.TargetFilter) []fab.Peer {\n\n\tif filter == nil {\n\t\treturn peers\n\t}\n\n\tfilteredPeers := []fab.Peer{}\n\tfor _, peer := range peers {\n\t\tif filter.Accept(peer) {\n\t\t\tfilteredPeers = append(filteredPeers, peer)\n\t\t}\n\t}\n\n\treturn filteredPeers\n}", "func FilterCommits(commits Commits, grep string, includeAll bool) Commits {\n\tresponse := Commits{}\n\n\tregex := regexp.MustCompile(grep)\n\tfor i := range commits {\n\t\tif includeAll || (!includeAll && regex.MatchString(commits[i].rawCommitType)) {\n\t\t\tresponse = append(response, commits[i])\n\t\t}\n\t}\n\treturn response\n}", "func ApplyFilter(u *task.List, f func(uint64, int) bool) {\n\tout := u.Uids[:0]\n\tfor i, uid := range u.Uids {\n\t\tif f(uid, i) {\n\t\t\tout = append(out, uid)\n\t\t}\n\t}\n\tu.Uids = out\n}", "func Filter(result []Expression, input []Expression, filter func(Expression) bool) []Expression {\n\ttrace_util_0.Count(_util_00000, 0)\n\tfor _, e := range input {\n\t\ttrace_util_0.Count(_util_00000, 2)\n\t\tif filter(e) {\n\t\t\ttrace_util_0.Count(_util_00000, 3)\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\ttrace_util_0.Count(_util_00000, 1)\n\treturn result\n}", "func DetachIndexConditions(conditions []expression.Expression, cols []*expression.Column,\n\tlengths []int) (accessConds []expression.Expression, filterConds []expression.Expression) {\n\taccessConds = make([]expression.Expression, len(cols))\n\tvar equalOrInCount int\n\tfor _, cond := range conditions {\n\t\toffset := getEqOrInColOffset(cond, cols)\n\t\tif offset != -1 {\n\t\t\taccessConds[offset] = cond\n\t\t}\n\t}\n\tfor i, cond := range accessConds {\n\t\tif cond == nil {\n\t\t\taccessConds = accessConds[:i]\n\t\t\tequalOrInCount = i\n\t\t\tbreak\n\t\t}\n\t\tif lengths[i] != types.UnspecifiedLength {\n\t\t\tfilterConds = append(filterConds, cond)\n\t\t}\n\t\tif i == len(accessConds)-1 {\n\t\t\tequalOrInCount = len(accessConds)\n\t\t}\n\t}\n\t// We should remove all accessConds, so that they will not be added to filter conditions.\n\tconditions = removeAccessConditions(conditions, accessConds)\n\tif equalOrInCount == len(cols) {\n\t\t// If curIndex equals to len of index columns, it means the rest conditions haven't been appended to filter conditions.\n\t\tfilterConds = append(filterConds, conditions...)\n\t\treturn accessConds, filterConds\n\t}\n\treturn extractAccessAndFilterConds(conditions, accessConds, filterConds, cols[equalOrInCount], lengths[equalOrInCount])\n}", "func (f *fragment) unprotectedRows(start uint64, filters ...rowFilter) []uint64 {\n\tstartKey := rowToKey(start)\n\ti, _ := f.storage.Containers.Iterator(startKey)\n\trows := make([]uint64, 0)\n\tvar lastRow uint64 = math.MaxUint64\n\n\t// Loop over the existing containers.\n\tfor i.Next() {\n\t\tkey, c := i.Value()\n\n\t\t// virtual row for the current container\n\t\tvRow := key >> shardVsContainerExponent\n\n\t\t// skip dups\n\t\tif vRow == lastRow {\n\t\t\tcontinue\n\t\t}\n\n\t\t// apply filters\n\t\taddRow, done := true, false\n\t\tfor _, filter := range filters {\n\t\t\tvar d bool\n\t\t\taddRow, d = filter(vRow, key, c)\n\t\t\tdone = done || d\n\t\t\tif !addRow {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif addRow {\n\t\t\tlastRow = vRow\n\t\t\trows = append(rows, vRow)\n\t\t}\n\t\tif done {\n\t\t\treturn rows\n\t\t}\n\t}\n\treturn rows\n}", "func FilterOut(t transport.Transport, filePath string, toBan []string) (filtered int, duplicates int, nbMatch int) {\n\tfor i := 0; i < len(toBan); i++ {\n\t\tlogger.Debugf(\"Should ban: %s\", toBan[i])\n\t}\n\n\ttmpfile, err := ioutil.TempFile(\"\", t.GetID())\n\tlogger.Debugf(\"Write filtered file: %s\", tmpfile.Name())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfiltered = 0\n\tduplicates = 0\n\tnbMatch = 0\n\tscanner := bufio.NewScanner(file)\n\tprevMatch := \"\"\n\tfor scanner.Scan() {\n\t\tmatch := [][]logol.Match{}\n\t\tjsonMatch := scanner.Text()\n\t\tif jsonMatch == prevMatch {\n\t\t\tduplicates++\n\t\t\tcontinue\n\t\t}\n\t\tprevMatch = jsonMatch\n\t\t// fmt.Println(jsonMatch)\n\t\terr := json.Unmarshal([]byte(jsonMatch), &match)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to load a match, skipping it: %s\", jsonMatch)\n\t\t\tcontinue\n\t\t}\n\t\tmustBeRemoved := false\n\t\tfor i := 0; i < len(match); i++ {\n\t\t\tsmatch := match[i]\n\t\t\tfor j := 0; j < len(smatch); j++ {\n\t\t\t\tssmatch := smatch[j]\n\t\t\t\tfor t := 0; t < len(toBan); t++ {\n\t\t\t\t\tmToBan := toBan[t]\n\t\t\t\t\t_, found := ssmatch.GetByUid(mToBan)\n\t\t\t\t\tif found {\n\t\t\t\t\t\tmustBeRemoved = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif mustBeRemoved {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif mustBeRemoved {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !mustBeRemoved {\n\t\t\tfmt.Fprintln(tmpfile, \"\", jsonMatch)\n\t\t\tnbMatch++\n\t\t} else {\n\t\t\tfiltered++\n\t\t}\n\t}\n\tos.Rename(tmpfile.Name(), filePath)\n\treturn filtered, duplicates, nbMatch\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserFilterer) FilterOwnershipRenounced(opts *bind.FilterOpts, previousOwner []common.Address) (*ProjectWalletAuthoriserOwnershipRenouncedIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\n\tlogs, sub, err := _ProjectWalletAuthoriser.contract.FilterLogs(opts, \"OwnershipRenounced\", previousOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ProjectWalletAuthoriserOwnershipRenouncedIterator{contract: _ProjectWalletAuthoriser.contract, event: \"OwnershipRenounced\", logs: logs, sub: sub}, nil\n}", "func DiscardAbundantPartners(\n\tcandidatesPtr *[]Candidate,\n\tmaxGenePartners int) {\n\tcandidates := *candidatesPtr\n\n\t// First pass, record every gene and its partners\n\tpartners := map[GeneID]map[GeneID]struct{}{}\n\taddGenePair := func(g1, g2 GeneID) {\n\t\tif partners[g1] == nil {\n\t\t\tpartners[g1] = map[GeneID]struct{}{}\n\t\t}\n\t\tpartners[g1][g2] = struct{}{}\n\t}\n\n\tfor _, c := range candidates {\n\t\tfor _, fusion := range c.Fusions {\n\t\t\taddGenePair(fusion.G1ID, fusion.G2ID)\n\t\t\taddGenePair(fusion.G2ID, fusion.G1ID)\n\t\t}\n\t}\n\n\t// Now that we have an idea of the number of unique partners per gene, we can\n\t// discard those with > cap partners.\n\tisGeneWithAbundantPartners := func(g GeneID) bool {\n\t\treturn len(partners[g]) > maxGenePartners\n\t}\n\tvar (\n\t\tj int\n\t\tnDiscardedFusion int\n\t\tnTotalFusion int\n\t)\n\tfor _, c := range candidates {\n\t\tvar k int\n\t\tfor _, fusion := range c.Fusions {\n\t\t\tnTotalFusion++\n\t\t\tif isGeneWithAbundantPartners(fusion.G1ID) || isGeneWithAbundantPartners(fusion.G2ID) {\n\t\t\t\tnDiscardedFusion++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Fusions[k] = fusion\n\t\t\tk++\n\t\t}\n\t\tc.Fusions = c.Fusions[:k]\n\t\tif len(c.Fusions) > 0 {\n\t\t\tcandidates[j] = c\n\t\t\tj++\n\t\t}\n\t}\n\tlog.Printf(\n\t\t\"Discarding %d of %d candidates, %d of %d fusions for having too many fusion partners\",\n\t\tlen(candidates)-j, len(candidates), nDiscardedFusion, nTotalFusion)\n\t*candidatesPtr = candidates[:j]\n}", "func FilterSlice(in []int) ([]int, error) {\n\tif in == nil {\n\t\treturn nil, errors.New(\"input slice is nil\")\n\t}\n\n\tfilterList := map[int]bool{\n\t\t1: true,\n\t\t3: true,\n\t}\n\n\tinLen := len(in)\n\tfilteredSlice := make([]int, 0, inLen)\n\n\tfor _, value := range in {\n\t\tif _, ok := filterList[value]; ok {\n\t\t\tfilteredSlice = append(filteredSlice, value)\n\t\t}\n\t}\n\n\treturn filteredSlice, nil\n}", "func removeBooleanListener(list []BooleanListener, index int) []BooleanListener {\n\tcopy(list[index:], list[index+1:])\n\treturn list[:len(list)-1]\n}", "func filter(src <-chan int, dst chan<- int, prime int) {\n\tfor i := range src { // Loop over values received from 'src'.\n\t\tif i%prime != 0 {\n\t\t\tdst <- i // Send 'i' to channel 'dst'.\n\t\t}\n\t}\n}", "func (fn FilterNone) Filter(incidnetsChan <-chan Incident, filteredIncidnetsChan chan<- Incident) {\n\tfn.l.WithFields(log.Fields{\n\t\t\"source\": \"FilterNone\",\n\t\t\"stage\": \"filter\",\n\t}).Info(\"starting FilterNone\")\n\n\tfor v := range incidnetsChan {\n\t\tfn.l.WithFields(log.Fields{\n\t\t\t\"source\": \"FilterNone\",\n\t\t\t\"stage\": \"filter\",\n\t\t\t\"content\": fmt.Sprintf(\"%#v\", v),\n\t\t}).Trace(\"passing through value\")\n\t\tfn.l.WithFields(log.Fields{\n\t\t\t\"source\": \"FilterNone\",\n\t\t\t\"stage\": \"filter\",\n\t\t\t\"Incidnet\": v.Summary,\n\t\t}).Debug(\"Filter Incident\")\n\t\tfilteredIncidnetsChan <- v\n\t}\n}", "func PublicFilter(users Users) Users {\n\tfilteredUsers := Users{}\n\n\tfor _, user := range users {\n\t\tuser.Password = \"*** ***\"\n\t\tfilteredUsers = append(filteredUsers, user)\n\t}\n\n\treturn filteredUsers\n}", "func (v *IntVec) Filter(filter func(e int) bool) {\n\tdv := *v\n\n\tvar i int\n\tfor _, e := range dv {\n\t\tif filter(e) {\n\t\t\tdv[i] = e\n\t\t\ti++\n\t\t}\n\t}\n\n\tv.Truncate(i)\n}", "func (_BaseAccessWallet *BaseAccessWalletFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseAccessWalletCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseAccessWallet.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletCommitPendingIterator{contract: _BaseAccessWallet.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func (pool *ComplexPool) Filter(filters ...Filter) {\n\tall := ApplyFilters(pool.All.List(), filters)\n\tunused := ApplyFilters(pool.Unused.List(), filters)\n\n\tpool.All = providers.NewSet()\n\tpool.Unused = providers.NewSet()\n\n\tfor _, p := range all {\n\t\tpool.All.Add(p)\n\t}\n\n\tfor _, p := range unused {\n\t\tpool.Unused.Add(p)\n\t}\n}", "func (candidate *Candidate) filterUpdates() {\n\n\tcandidate.lock.RLock()\n\tif len(candidate.updates) == 0 {\n\t\tcandidate.lock.RUnlock()\n\t\treturn\n\t}\n\tcandidate.lock.RUnlock()\n\n\tupdates := candidate.getFilteredUpdates()\n\n\tsort.SliceStable(updates, func(i, j int) bool {\n\t\treturn updates[i].BipValue.Cmp(updates[j].BipValue) == 1\n\t})\n\n\tcandidate.lock.Lock()\n\tcandidate.updates = updates\n\tcandidate.isUpdatesDirty = true\n\tcandidate.lock.Unlock()\n}", "func (_BaseContent *BaseContentFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseContentCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseContent.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentCommitPendingIterator{contract: _BaseContent.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func MultipleFilter(num int, in <-chan int, out chan<- int) {\n\tfor i := range in {\n\t\tif i%num != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n}", "func Filter(nums []int, filter Condition) []int {\n\ts := make([]int, 0)\n\tfor _, num := range nums {\n\t\tif filter(num) {\n\t\t\ts = append(s, num)\n\t\t}\n\t}\n\n\treturn s\n}", "func FilterOut(done <-chan interface{}, fragmentStream <-chan types.DocumentFragment) <-chan types.DocumentFragment {\n\tresultStream := make(chan types.DocumentFragment, bufferSize)\n\tgo func() {\n\t\tdefer close(resultStream)\n\t\tfor fragment := range fragmentStream {\n\t\t\tselect {\n\t\t\tcase resultStream <- filterOut(fragment, allMatchers...):\n\t\t\tcase <-done:\n\t\t\t\tlog.WithField(\"pipeline_task\", \"filter_out\").Debug(\"received 'done' signal\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tlog.WithField(\"pipeline_task\", \"filter_out\").Debug(\"done\")\n\t}()\n\treturn resultStream\n}", "func (_BaseLibrary *BaseLibraryFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseLibraryCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseLibrary.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseLibraryCommitPendingIterator{contract: _BaseLibrary.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func remove(list []*IPRange, index int) []*IPRange {\n\tfor i := index + 1; i < len(list); i++ {\n\t\tlist[i-1] = list[i]\n\t}\n\treturn list[:len(list)-1]\n}", "func (_BaseContentType *BaseContentTypeFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseContentTypeCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseContentType.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentTypeCommitPendingIterator{contract: _BaseContentType.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func (_Container *ContainerFilterer) FilterCommitPending(opts *bind.FilterOpts) (*ContainerCommitPendingIterator, error) {\n\n\tlogs, sub, err := _Container.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContainerCommitPendingIterator{contract: _Container.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func ReorderParticipants(mctx libkb.MetaContext, g libkb.UIDMapperContext, umapper libkb.UIDMapper,\n\ttlfName string, verifiedMembers []string, activeList []gregor1.UID) (writerNames []chat1.ConversationLocalParticipant, err error) {\n\tsrcWriterNames, _, _, err := splitAndNormalizeTLFNameCanonicalize(mctx, tlfName, false)\n\tif err != nil {\n\t\treturn writerNames, err\n\t}\n\tactiveKuids := make([]keybase1.UID, 0, len(activeList))\n\tfor _, a := range activeList {\n\t\tactiveKuids = append(activeKuids, keybase1.UID(a.String()))\n\t}\n\tallowedWriters := make(map[string]bool, len(verifiedMembers)+len(srcWriterNames))\n\tfor _, user := range verifiedMembers {\n\t\tallowedWriters[user] = true\n\t}\n\tconvNameUsers := make(map[string]bool, len(srcWriterNames))\n\tfor _, user := range srcWriterNames {\n\t\tconvNameUsers[user] = true\n\t\tallowedWriters[user] = true\n\t}\n\n\tpackages, err := umapper.MapUIDsToUsernamePackages(mctx.Ctx(), g, activeKuids, time.Hour*24,\n\t\t10*time.Second, true)\n\tactiveMap := make(map[string]chat1.ConversationLocalParticipant)\n\tif err == nil {\n\t\tfor i := 0; i < len(activeKuids); i++ {\n\t\t\tpart := UsernamePackageToParticipant(packages[i])\n\t\t\tpart.InConvName = convNameUsers[part.Username]\n\t\t\tactiveMap[activeKuids[i].String()] = part\n\t\t}\n\t}\n\n\t// Fill from the active list first.\n\tfor _, uid := range activeList {\n\t\tkbUID := keybase1.UID(uid.String())\n\t\tp, ok := activeMap[kbUID.String()]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif allowed := allowedWriters[p.Username]; allowed {\n\t\t\twriterNames = append(writerNames, p)\n\t\t\t// Allow only one occurrence.\n\t\t\tallowedWriters[p.Username] = false\n\t\t}\n\t}\n\n\t// Include participants even if they weren't in the active list, in stable order.\n\tvar leftOvers []chat1.ConversationLocalParticipant\n\tfor user, available := range allowedWriters {\n\t\tif !available {\n\t\t\tcontinue\n\t\t}\n\t\tpart := UsernamePackageToParticipant(libkb.UsernamePackage{\n\t\t\tNormalizedUsername: libkb.NewNormalizedUsername(user),\n\t\t\tFullName: nil,\n\t\t})\n\t\tpart.InConvName = convNameUsers[part.Username]\n\t\tleftOvers = append(leftOvers, part)\n\t\tallowedWriters[user] = false\n\t}\n\tsort.Slice(leftOvers, func(i, j int) bool {\n\t\treturn strings.Compare(leftOvers[i].Username, leftOvers[j].Username) < 0\n\t})\n\twriterNames = append(writerNames, leftOvers...)\n\n\treturn writerNames, nil\n}", "func (sm *SharedManager) unprocessedIndexBlobsUnlocked(ctx context.Context, contents []IndexBlobInfo) (resultCh <-chan blob.ID, totalSize int64, err error) {\n\tch := make(chan blob.ID, len(contents))\n\tdefer close(ch)\n\n\tfor _, c := range contents {\n\t\thas, err := sm.committedContents.cache.hasIndexBlobID(ctx, c.BlobID)\n\t\tif err != nil {\n\t\t\treturn nil, 0, errors.Wrapf(err, \"error determining whether index blob %v has been downloaded\", c.BlobID)\n\t\t}\n\n\t\tif has {\n\t\t\tformatLog(ctx).Debugf(\"index-already-cached %v\", c.BlobID)\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- c.BlobID\n\t\ttotalSize += c.Length\n\t}\n\n\treturn ch, totalSize, nil\n}", "func (s *SliceOfUint32) Filter(filterFunc func(uint32) bool) *SliceOfUint32 {\n\tvar newItems []uint32\n\tfor _, value := range s.items {\n\t\tif filterFunc(value) {\n\t\t\tnewItems = append(newItems, value)\n\t\t}\n\t}\n\treturn s\n}", "func filter(source <-chan int, destination chan<- int, prime int) {\n\tfor i := range source {\n\t\tif i%prime != 0 {\n\t\t\tdestination <- i // Send 'i' to 'destination'.\n\t\t}\n\t}\n}", "func (_Erc777 *Erc777Filterer) FilterMinted(opts *bind.FilterOpts, operator []common.Address, to []common.Address) (*Erc777MintedIterator, error) {\n\n\tvar operatorRule []interface{}\n\tfor _, operatorItem := range operator {\n\t\toperatorRule = append(operatorRule, operatorItem)\n\t}\n\tvar toRule []interface{}\n\tfor _, toItem := range to {\n\t\ttoRule = append(toRule, toItem)\n\t}\n\n\tlogs, sub, err := _Erc777.contract.FilterLogs(opts, \"Minted\", operatorRule, toRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Erc777MintedIterator{contract: _Erc777.contract, event: \"Minted\", logs: logs, sub: sub}, nil\n}", "func (m *InviteeMutation) ClearedFields() []string {\n\tvar fields []string\n\tif m.FieldCleared(invitee.FieldIsChild) {\n\t\tfields = append(fields, invitee.FieldIsChild)\n\t}\n\tif m.FieldCleared(invitee.FieldPlusOneName) {\n\t\tfields = append(fields, invitee.FieldPlusOneName)\n\t}\n\tif m.FieldCleared(invitee.FieldPhone) {\n\t\tfields = append(fields, invitee.FieldPhone)\n\t}\n\tif m.FieldCleared(invitee.FieldEmail) {\n\t\tfields = append(fields, invitee.FieldEmail)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressLine1) {\n\t\tfields = append(fields, invitee.FieldAddressLine1)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressLine2) {\n\t\tfields = append(fields, invitee.FieldAddressLine2)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressCity) {\n\t\tfields = append(fields, invitee.FieldAddressCity)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressState) {\n\t\tfields = append(fields, invitee.FieldAddressState)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressPostalCode) {\n\t\tfields = append(fields, invitee.FieldAddressPostalCode)\n\t}\n\tif m.FieldCleared(invitee.FieldAddressCountry) {\n\t\tfields = append(fields, invitee.FieldAddressCountry)\n\t}\n\tif m.FieldCleared(invitee.FieldRsvpResponse) {\n\t\tfields = append(fields, invitee.FieldRsvpResponse)\n\t}\n\treturn fields\n}", "func scopeTrees(filters []interface{}) ([]string, error) {\n\tcommitIDs := map[string]struct{}{}\n\teverHadAny := false // whether unitIDs ever contained any commitIDs\n\n\tfor _, f := range filters {\n\t\tswitch f := f.(type) {\n\t\tcase ByCommitIDsFilter:\n\t\t\tif len(commitIDs) == 0 && !everHadAny {\n\t\t\t\teverHadAny = true\n\t\t\t\tfor _, c := range f.ByCommitIDs() {\n\t\t\t\t\tcommitIDs[c] = struct{}{}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Intersect.\n\t\t\t\tnewCommitIDs := make(map[string]struct{}, (len(commitIDs)+len(f.ByCommitIDs()))/2)\n\t\t\t\tfor _, c := range f.ByCommitIDs() {\n\t\t\t\t\tif _, present := commitIDs[c]; present {\n\t\t\t\t\t\tnewCommitIDs[c] = struct{}{}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcommitIDs = newCommitIDs\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(commitIDs) == 0 && !everHadAny {\n\t\t// No unit scoping filters were present, so scope includes\n\t\t// potentially all commitIDs.\n\t\treturn nil, nil\n\t}\n\n\tids := make([]string, 0, len(commitIDs))\n\tfor commitID := range commitIDs {\n\t\tids = append(ids, commitID)\n\t}\n\treturn ids, nil\n}", "func VectorizedFilter(ctx sessionctx.Context, filters []Expression, iterator *chunk.Iterator4Chunk, selected []bool) (_ []bool, err error) {\n\tselected, _, err = VectorizedFilterConsiderNull(ctx, filters, iterator, selected, nil)\n\treturn selected, err\n}", "func (_Editable *EditableFilterer) FilterCommitPending(opts *bind.FilterOpts) (*EditableCommitPendingIterator, error) {\n\n\tlogs, sub, err := _Editable.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EditableCommitPendingIterator{contract: _Editable.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseAccessControlGroupCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseAccessControlGroup.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessControlGroupCommitPendingIterator{contract: _BaseAccessControlGroup.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func Filter(in []Record, predicate func(Record) bool) []Record {\n\tout := make([]Record, 0, len(in))\n\tfor _, record := range in {\n\t\tif predicate(record) {\n\t\t\tout = append(out, record)\n\t\t}\n\t}\n\n\treturn out\n}", "func FilterUsingExclusionList(inputData InputData, dependents []Dependent) []Dependent {\n\tresult := []Dependent{}\n\n\tindex, err := spreadsheet.CreateIndex(inputData.filter, \"claim ref\", func(cellValue string) string {\n\t\treturn cellValue\n\t})\n\n\tif err != nil {\n\t\treturn result\n\t}\n\n\tfor _, d := range dependents {\n\t\tclaimStr := fmt.Sprintf(\"%d\", d.Person.ClaimNumber)\n\t\tisFiltered := false\n\t\tif rows, ok := index[claimStr]; ok {\n\t\t\tfor _, row := range rows {\n\t\t\t\tseemis := spreadsheet.ColByName(row, \"seemis ID\")\n\t\t\t\tfilteredByThisRow := seemis != \"\" && seemis == d.Seemis\n\t\t\t\tisFiltered = isFiltered || filteredByThisRow\n\t\t\t}\n\t\t}\n\n\t\tif !isFiltered {\n\t\t\tresult = append(result, d)\n\t\t}\n\t}\n\n\treturn result\n}", "func Filter(x interface{}, filter func(i int) bool) {\n\tptr := reflect.ValueOf(x)\n\tvalidateReflection(\"Filter\", reflect.Ptr, ptr)\n\n\tv := ptr.Elem()\n\tvalidateReflection(\"Filter\", reflect.Slice, v)\n\n\tfor i := v.Len() - 1; i >= 0; i-- {\n\t\tif filter(i) {\n\t\t\tv.Set(reflect.AppendSlice(v.Slice(0, i), v.Slice(i+1, v.Len())))\n\t\t}\n\t}\n}", "func filter(s []int, fn func(int) bool) []int {\n\tvar p []int\n\tfor _, v := range s {\n\t\tif fn(v) {\n\t\t\tp = append(p, v)\n\t\t}\n\t}\n\treturn p\n}", "func (_BaseContentSpace *BaseContentSpaceFilterer) FilterCommitPending(opts *bind.FilterOpts) (*BaseContentSpaceCommitPendingIterator, error) {\n\n\tlogs, sub, err := _BaseContentSpace.contract.FilterLogs(opts, \"CommitPending\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentSpaceCommitPendingIterator{contract: _BaseContentSpace.contract, event: \"CommitPending\", logs: logs, sub: sub}, nil\n}", "func (p Paygen) FilterMilestone(milestone int) *Paygen {\n\tvar filtered Paygen\n\tfor _, delta := range p.Deltas {\n\t\tif delta.Milestone == milestone {\n\t\t\tfiltered.Deltas = append(filtered.Deltas, delta)\n\t\t}\n\t}\n\n\treturn &filtered\n}", "func (ap *actPool) removeCommittedTxs() {\n\tap.mutex.Lock()\n\tdefer ap.mutex.Unlock()\n\tfor addrHash, queue := range ap.accountTxs {\n\t\tcommittedNonce, err := ap.pendingSF.Nonce(hashToAddr[addrHash])\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error when removing committed Txs: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t\t// Remove all transactions that are committed to new block\n\t\tfor _, tx := range queue.FilterNonce(committedNonce) {\n\t\t\thash := tx.Hash()\n\t\t\tglog.Info(\"Removed committed transaction\", \"hash\", hash)\n\t\t\tdelete(ap.allTxs, hash)\n\t\t}\n\t\t// Delete the queue entry if it becomes empty\n\t\tif queue.Empty() {\n\t\t\tdelete(ap.accountTxs, addrHash)\n\t\t}\n\t}\n}", "func (j *baseJoiner) filter(input, output *chunk.Chunk, outerColLen int, lUsed, rUsed []int) (bool, error) {\n\tvar err error\n\tj.selected, err = expression.VectorizedFilter(j.ctx, j.conditions, chunk.NewIterator4Chunk(input), j.selected)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// Batch copies selected rows to output chunk.\n\tinnerColOffset, outerColOffset := 0, input.NumCols()-outerColLen\n\tinnerColLen := input.NumCols() - outerColLen\n\tif !j.outerIsRight {\n\t\tinnerColOffset, outerColOffset = outerColLen, 0\n\t}\n\tif lUsed != nil || rUsed != nil {\n\t\tlSize := outerColOffset\n\t\tif !j.outerIsRight {\n\t\t\tlSize = innerColOffset\n\t\t}\n\t\tused := make([]int, len(lUsed)+len(rUsed))\n\t\tcopy(used, lUsed)\n\t\tfor i := range rUsed {\n\t\t\tused[i+len(lUsed)] = rUsed[i] + lSize\n\t\t}\n\t\tinput = input.Prune(used)\n\n\t\tinnerColOffset, outerColOffset = 0, len(lUsed)\n\t\tinnerColLen, outerColLen = len(lUsed), len(rUsed)\n\t\tif !j.outerIsRight {\n\t\t\tinnerColOffset, outerColOffset = len(lUsed), 0\n\t\t\tinnerColLen, outerColLen = outerColLen, innerColLen\n\t\t}\n\t}\n\treturn chunk.CopySelectedJoinRowsWithSameOuterRows(input, innerColOffset, innerColLen, outerColOffset, outerColLen, j.selected, output)\n}", "func Filter(in <-chan int, out chan<- int, prime int) {\n\tfor {\n\t\ti := <-in\n\t\tif i%prime != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n}", "func (s ChatParticipantAdminArray) Retain(keep func(x ChatParticipantAdmin) bool) ChatParticipantAdminArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func Compact(in []H3Index) []H3Index {\n\tcin := h3SliceToC(in)\n\tcsz := C.int(len(in))\n\t// worst case no compaction so we need a set **at least** as large as the\n\t// input\n\tcout := make([]C.H3Index, csz)\n\tC.compact(&cin[0], &cout[0], csz)\n\treturn h3SliceFromC(cout)\n}", "func Compact(in []H3Index) []H3Index {\n\tcin := h3SliceToC(in)\n\tcsz := C.int(len(in))\n\t// worst case no compaction so we need a set **at least** as large as the\n\t// input\n\tcout := make([]C.H3Index, csz)\n\tC.compact(&cin[0], &cout[0], csz)\n\treturn h3SliceFromC(cout)\n}", "func (m *Migrator) filter(current int64, direction MigrationDirection) []*Migration {\n\tvar index = -1\n\tif current > 0 {\n\t\tfor index < len(m.migrations)-1 {\n\t\t\tindex++\n\t\t\tif m.migrations[index].Id == current {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif direction == Up {\n\t\treturn m.migrations[index+1:]\n\t}\n\n\tif index == -1 {\n\t\treturn []*Migration{}\n\t}\n\n\t// Add in reverse order\n\ttoApply := make([]*Migration, index+1)\n\tfor i := 0; i < index+1; i++ {\n\t\ttoApply[index-i] = m.migrations[i]\n\t}\n\treturn toApply\n}", "func Filter(in <-chan uint, out chan<- uint, prime uint) {\n\tfor {\n\t\ti := <-in // Receive value from 'in'.\n\t\tif i%prime != 0 {\n\t\t\tout <- i // Send 'i' to 'out'.\n\t\t}\n\t}\n}", "func rescanBlockFilter(filter *wsClientFilter, block *btcutil.Block, params *chaincfg.Params) []string {\n\tvar transactions []string\n\n\tfilter.mu.Lock()\n\tfor _, tx := range block.Transactions() {\n\t\tmsgTx := tx.MsgTx()\n\n\t\t// Keep track of whether the transaction has already been added\n\t\t// to the result. It shouldn't be added twice.\n\t\tadded := false\n\n\t\t// Scan inputs if not a coinbase transaction.\n\t\tif !blockchain.IsCoinBaseTx(msgTx) {\n\t\t\tfor _, input := range msgTx.TxIn {\n\t\t\t\tif !filter.existsUnspentOutPoint(&input.PreviousOutPoint) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !added {\n\t\t\t\t\ttransactions = append(\n\t\t\t\t\t\ttransactions,\n\t\t\t\t\t\ttxHexString(msgTx))\n\t\t\t\t\tadded = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Scan outputs.\n\t\tfor i, output := range msgTx.TxOut {\n\t\t\t_, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, a := range addrs {\n\t\t\t\tif !filter.existsAddress(a) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\top := wire.OutPoint{\n\t\t\t\t\tHash: *tx.Hash(),\n\t\t\t\t\tIndex: uint32(i),\n\t\t\t\t}\n\t\t\t\tfilter.addUnspentOutPoint(&op)\n\n\t\t\t\tif !added {\n\t\t\t\t\ttransactions = append(\n\t\t\t\t\t\ttransactions,\n\t\t\t\t\t\ttxHexString(msgTx))\n\t\t\t\t\tadded = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfilter.mu.Unlock()\n\n\treturn transactions\n}", "func (s ChatParticipantArray) Retain(keep func(x ChatParticipant) bool) ChatParticipantArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (la *Allocator) filter(lcores []eal.LCore, predicates ...lCorePredicate) (filtered []eal.LCore) {\nL:\n\tfor _, lc := range lcores {\n\t\tfor _, pred := range predicates {\n\t\t\tif !pred(lc) {\n\t\t\t\tcontinue L\n\t\t\t}\n\t\t}\n\t\tfiltered = append(filtered, lc)\n\t}\n\treturn filtered\n}", "func Filter(in <-chan int, out chan<- int, prime int) {\n\tfor i := <-in; i != -1; i = <-in {\n\t\tif i%prime != 0 {\n\t\t\tout <- i\n\t\t}\n\t}\n\tout <- -1 //channel signal that he end has been reached\n}", "func vectorizedFilter(ctx sessionctx.Context, filters []Expression, iterator *chunk.Iterator4Chunk, selected []bool, isNull []bool) ([]bool, []bool, error) {\n\tselected, isNull, err := VecEvalBool(ctx, filters, iterator.GetChunk(), selected, isNull)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn selected, isNull, nil\n}", "func (_Lmc *LmcFilterer) FilterExitedAndUnlocked(opts *bind.FilterOpts, _userAddress []common.Address) (*LmcExitedAndUnlockedIterator, error) {\n\n\tvar _userAddressRule []interface{}\n\tfor _, _userAddressItem := range _userAddress {\n\t\t_userAddressRule = append(_userAddressRule, _userAddressItem)\n\t}\n\n\tlogs, sub, err := _Lmc.contract.FilterLogs(opts, \"ExitedAndUnlocked\", _userAddressRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LmcExitedAndUnlockedIterator{contract: _Lmc.contract, event: \"ExitedAndUnlocked\", logs: logs, sub: sub}, nil\n}", "func (s *SliceOfUint64) Filter(filterFunc func(uint64) bool) *SliceOfUint64 {\n\tvar newItems []uint64\n\tfor _, value := range s.items {\n\t\tif filterFunc(value) {\n\t\t\tnewItems = append(newItems, value)\n\t\t}\n\t}\n\treturn s\n}", "func filterOutPermissions(permList, filterOutList []string) []string {\n\tfilteredPerms := []string{}\n\tfor _, perm := range permList {\n\t\tfilterOut := false\n\t\tfor _, filterPerm := range filterOutList {\n\t\t\tif perm == filterPerm {\n\t\t\t\tfilterOut = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif filterOut {\n\t\t\tcontinue\n\t\t}\n\t\tfilteredPerms = append(filteredPerms, perm)\n\t}\n\treturn filteredPerms\n}", "func (m *hasher) maskIndex(index []byte, depth int) []byte {\n\tif got, want := len(index), m.Size(); got != want {\n\t\tpanic(fmt.Sprintf(\"index len: %d, want %d\", got, want))\n\t}\n\tif got, want := depth, m.BitLen(); got < 0 || got > want {\n\t\tpanic(fmt.Sprintf(\"depth: %d, want <= %d && > 0\", got, want))\n\t}\n\n\t// Create an empty index Size() bytes long.\n\tret := make([]byte, m.Size())\n\tif depth > 0 {\n\t\t// Copy the first depthBytes.\n\t\tdepthBytes := (depth + 7) >> 3\n\t\tcopy(ret, index[:depthBytes])\n\t\t// Mask off unwanted bits in the last byte.\n\t\tret[depthBytes-1] = ret[depthBytes-1] & leftmask[depth%8]\n\t}\n\treturn ret\n}", "func (_WyvernExchange *WyvernExchangeFilterer) FilterOwnershipRenounced(opts *bind.FilterOpts, previousOwner []common.Address) (*WyvernExchangeOwnershipRenouncedIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.FilterLogs(opts, \"OwnershipRenounced\", previousOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WyvernExchangeOwnershipRenouncedIterator{contract: _WyvernExchange.contract, event: \"OwnershipRenounced\", logs: logs, sub: sub}, nil\n}", "func (or DisjunctionFilter) Candidates() []string {\n\n\t// gather a list of candidates\n\tcandidates := make([]string, 0, len(or.Clauses))\n\tfor _, clause := range or.Clauses { // most clauses will have exactly one candidate, hence len(or.Clauses) should be enough to never reallocate\n\t\tcandidates = append(candidates, Candidates(clause)...)\n\t}\n\n\t// remove duplicates from the result\n\treturn collection.Deduplicate(candidates)\n}", "func (_AuthContract *AuthContractFilterer) FilterOwnershipRenounced(opts *bind.FilterOpts, previousOwner []common.Address) (*AuthContractOwnershipRenouncedIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\n\tlogs, sub, err := _AuthContract.contract.FilterLogs(opts, \"OwnershipRenounced\", previousOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AuthContractOwnershipRenouncedIterator{contract: _AuthContract.contract, event: \"OwnershipRenounced\", logs: logs, sub: sub}, nil\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigFilterer) FilterOwnerRemoval(opts *bind.FilterOpts, owner []common.Address) (*ReserveSpenderMultiSigOwnerRemovalIterator, error) {\n\n\tvar ownerRule []interface{}\n\tfor _, ownerItem := range owner {\n\t\townerRule = append(ownerRule, ownerItem)\n\t}\n\n\tlogs, sub, err := _ReserveSpenderMultiSig.contract.FilterLogs(opts, \"OwnerRemoval\", ownerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ReserveSpenderMultiSigOwnerRemovalIterator{contract: _ReserveSpenderMultiSig.contract, event: \"OwnerRemoval\", logs: logs, sub: sub}, nil\n}", "func ConcurrentEdgeFilter(imgSrc image.Image) image.Image {\n\tngo:=runtime.NumCPU()\n\tout := make(chan portion)\n\tslices := imagetools.CropChevauchement(imgSrc, ngo, 10) //on laisse 5 pixels de chevauchement\n\n\tfor i := 0; i < ngo; i++ {\n\t\tgo edgWorker(i, out, slices[i][0])\n\t}\n\n\tfor i := 0; i < ngo; i++ {\n\t\tslice := <-out\n\t\tslices[slice.id][0] = slice.img\n\t}\n\n\timgEnd := imagetools.RebuildChevauchement(slices, 10)\n\n\treturn imgEnd\n\n}", "func filterContainers(filterMap map[string]string, conts []types.Container) []types.Container {\n\tvar res []types.Container\n\n\tfor _, cont := range conts {\n\t\tmatchesAll := true\n\t\tfor k, v := range filterMap {\n\t\t\tif iv, ok := cont.Labels[k]; !ok || v != iv {\n\t\t\t\tmatchesAll = false\n\t\t\t}\n\t\t}\n\t\tif matchesAll {\n\t\t\tres = append(res, cont)\n\t\t}\n\t}\n\n\treturn res\n}", "func removeIndex(slice []int, index int) []int {\n\tret := make([]int, 0)\n\tret = append(ret, slice[:index]...)\n\treturn append(ret, slice[index+1:]...)\n}", "func (sim *SessionInterestManager) FilterSessionInterested(ses uint64, ksets ...[]cid.Cid) [][]cid.Cid {\n\tsim.lk.RLock()\n\tdefer sim.lk.RUnlock()\n\n\t// For each set of keys\n\tkres := make([][]cid.Cid, len(ksets))\n\tfor i, ks := range ksets {\n\t\t// The set of keys that at least one session is interested in\n\t\thas := make([]cid.Cid, 0, len(ks))\n\n\t\t// For each key in the list\n\t\tfor _, c := range ks {\n\t\t\t// If there is a session that's interested, add the key to the set\n\t\t\tif _, ok := sim.wants[c][ses]; ok {\n\t\t\t\thas = append(has, c)\n\t\t\t}\n\t\t}\n\t\tkres[i] = has\n\t}\n\treturn kres\n}", "func main() {\n\tvisit([]int{1, 2, 3, 4}, func(n int) {\n\t\tfmt.Println(n)\n\t})\n\n\t// Filter part\n\txs := filter([]int{1, 2, 3, 4}, func(n int) bool {\n\t\treturn n > 1\n\t})\n\tfmt.Println(xs) // [2, 3, 4]\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserFilterer) FilterOwnershipTransferred(opts *bind.FilterOpts, previousOwner []common.Address, newOwner []common.Address) (*ProjectWalletAuthoriserOwnershipTransferredIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\tvar newOwnerRule []interface{}\n\tfor _, newOwnerItem := range newOwner {\n\t\tnewOwnerRule = append(newOwnerRule, newOwnerItem)\n\t}\n\n\tlogs, sub, err := _ProjectWalletAuthoriser.contract.FilterLogs(opts, \"OwnershipTransferred\", previousOwnerRule, newOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ProjectWalletAuthoriserOwnershipTransferredIterator{contract: _ProjectWalletAuthoriser.contract, event: \"OwnershipTransferred\", logs: logs, sub: sub}, nil\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigFilterer) FilterSubmission(opts *bind.FilterOpts, transactionId []*big.Int) (*ReserveSpenderMultiSigSubmissionIterator, error) {\n\n\tvar transactionIdRule []interface{}\n\tfor _, transactionIdItem := range transactionId {\n\t\ttransactionIdRule = append(transactionIdRule, transactionIdItem)\n\t}\n\n\tlogs, sub, err := _ReserveSpenderMultiSig.contract.FilterLogs(opts, \"Submission\", transactionIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ReserveSpenderMultiSigSubmissionIterator{contract: _ReserveSpenderMultiSig.contract, event: \"Submission\", logs: logs, sub: sub}, nil\n}", "func (es Entities) FilterAll(t Type) {\n\ti := 0\n\tfor j := 0; j < len(es.IDs); j++ {\n\t\tif es.Entity(j).Type().HasAll(t) {\n\t\t\tes.IDs[i] = es.IDs[j]\n\t\t\ti++\n\t\t}\n\t}\n\tes.IDs = es.IDs[:i]\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigFilterer) FilterRevocation(opts *bind.FilterOpts, sender []common.Address, transactionId []*big.Int) (*ReserveSpenderMultiSigRevocationIterator, error) {\n\n\tvar senderRule []interface{}\n\tfor _, senderItem := range sender {\n\t\tsenderRule = append(senderRule, senderItem)\n\t}\n\tvar transactionIdRule []interface{}\n\tfor _, transactionIdItem := range transactionId {\n\t\ttransactionIdRule = append(transactionIdRule, transactionIdItem)\n\t}\n\n\tlogs, sub, err := _ReserveSpenderMultiSig.contract.FilterLogs(opts, \"Revocation\", senderRule, transactionIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ReserveSpenderMultiSigRevocationIterator{contract: _ReserveSpenderMultiSig.contract, event: \"Revocation\", logs: logs, sub: sub}, nil\n}", "func filter(in chan int, prime int) chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tfor {\n\t\t\tif i := <-in; i%prime != 0 {\n\t\t\t\tout <- i\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigFilterer) FilterConfirmation(opts *bind.FilterOpts, sender []common.Address, transactionId []*big.Int) (*ReserveSpenderMultiSigConfirmationIterator, error) {\n\n\tvar senderRule []interface{}\n\tfor _, senderItem := range sender {\n\t\tsenderRule = append(senderRule, senderItem)\n\t}\n\tvar transactionIdRule []interface{}\n\tfor _, transactionIdItem := range transactionId {\n\t\ttransactionIdRule = append(transactionIdRule, transactionIdItem)\n\t}\n\n\tlogs, sub, err := _ReserveSpenderMultiSig.contract.FilterLogs(opts, \"Confirmation\", senderRule, transactionIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ReserveSpenderMultiSigConfirmationIterator{contract: _ReserveSpenderMultiSig.contract, event: \"Confirmation\", logs: logs, sub: sub}, nil\n}", "func (_Contracts *ContractsFilterer) FilterAccredited(opts *bind.FilterOpts, _candidate []*big.Int, _proposal []*big.Int, _position []*big.Int) (*ContractsAccreditedIterator, error) {\n\n\tvar _candidateRule []interface{}\n\tfor _, _candidateItem := range _candidate {\n\t\t_candidateRule = append(_candidateRule, _candidateItem)\n\t}\n\tvar _proposalRule []interface{}\n\tfor _, _proposalItem := range _proposal {\n\t\t_proposalRule = append(_proposalRule, _proposalItem)\n\t}\n\tvar _positionRule []interface{}\n\tfor _, _positionItem := range _position {\n\t\t_positionRule = append(_positionRule, _positionItem)\n\t}\n\n\tlogs, sub, err := _Contracts.contract.FilterLogs(opts, \"Accredited\", _candidateRule, _proposalRule, _positionRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractsAccreditedIterator{contract: _Contracts.contract, event: \"Accredited\", logs: logs, sub: sub}, nil\n}", "func FilterExploded(conv types.UnboxConversationInfo, msgs []chat1.MessageUnboxed, now time.Time) (res []chat1.MessageUnboxed) {\n\tupto := conv.GetMaxDeletedUpTo()\n\tfor _, msg := range msgs {\n\t\tif msg.IsEphemeral() && msg.HideExplosion(upto, now) {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, msg)\n\t}\n\treturn res\n}", "func onlyPublic(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPublicAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t}\n\t}\n\treturn routable\n}" ]
[ "0.669581", "0.55047035", "0.51366824", "0.50197536", "0.50193655", "0.49617875", "0.48063084", "0.47176096", "0.4714836", "0.46558598", "0.46235752", "0.46222484", "0.4618891", "0.45929018", "0.45732638", "0.45470276", "0.45158985", "0.45022804", "0.44857106", "0.44759148", "0.4463891", "0.4462463", "0.44607046", "0.44530925", "0.44404706", "0.44344535", "0.43933392", "0.4385536", "0.43813664", "0.43741274", "0.4359003", "0.43577614", "0.43553028", "0.43496412", "0.43492222", "0.43059057", "0.42904487", "0.4281311", "0.42791614", "0.42755672", "0.42710963", "0.42644677", "0.4263738", "0.42602393", "0.42576927", "0.42455596", "0.4238569", "0.42308068", "0.4225784", "0.42247772", "0.4219508", "0.42190984", "0.42155933", "0.42124748", "0.42094454", "0.42072067", "0.4207137", "0.41998994", "0.41979688", "0.41890383", "0.41762882", "0.41691145", "0.4164663", "0.41631633", "0.41627666", "0.4156387", "0.4156109", "0.41504836", "0.41489017", "0.41425183", "0.41425183", "0.41404477", "0.4124876", "0.41187364", "0.41085503", "0.41074046", "0.4102776", "0.4099503", "0.40972364", "0.4083314", "0.40760425", "0.40710828", "0.4070671", "0.40693328", "0.4065293", "0.40640676", "0.40624988", "0.4059235", "0.40566304", "0.40556717", "0.403294", "0.40289265", "0.40270522", "0.4025106", "0.40239435", "0.4023331", "0.40207085", "0.40189356", "0.4009994", "0.4004925" ]
0.6901887
0
Inplace filters a list of committees indices to only keep the bitfield NONparticipants. The result is not sorted. Returns the resliced filtered nonparticipants list.
func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex { bitLen := cb.BitLen() out := committee[:0] if bitLen != uint64(len(committee)) { panic("committee mismatch, bitfield length does not match") } for i := uint64(0); i < bitLen; i++ { if !cb.GetBit(i) { out = append(out, committee[i]) } } return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cb CommitteeBits) FilterParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func filter_by_non_replica(membership_server *Server, active_replicas []string) []string{\n\tvar result []string\n\tfor _, node := range FS_NODES {\n\t\tif membership_server.MembershipMap[to_membership_node(node)].Status == FAILED_REMOVAL {\n\t\t\tcontinue\n\t\t}\n\t\tflag := 1\n\t\tfor _, replica := range active_replicas {\n\t\t\tif replica == node {\n\t\t\t\tflag = 0\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif flag == 1 {\n\t\t\tresult = append(result, node)\n\t\t}\n\t}\n\treturn result\n}", "func (c *Curator) filterPendingPieces(ids []core.TractID) (out []core.TractID) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tout = ids[:0]\n\tfor _, id := range ids {\n\t\tif _, ok := c.pendingPieces[id]; !ok {\n\t\t\tout = append(out, id)\n\t\t}\n\t}\n\treturn\n}", "func filterPlayers(originalPlayers Players) Players {\n\tfilterPlayersMap := make(map[string]Player, len(originalPlayers))\n\tfor _, player := range originalPlayers {\n\t\tfilterPlayersMap[player.FullName] = player\n\t}\n\n\tplayers := make(Players, 0, len(filterPlayersMap))\n\tfor _, player := range filterPlayersMap {\n\t\tplayers = append(players, player)\n\t}\n\n\treturn players\n}", "func IndexNotIn(vs ...int) predicate.Step {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Step(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldIndex), v...))\n\t})\n}", "func FilterOutInPlace(input []Expression, filter func(Expression) bool) (remained, filteredOut []Expression) {\n\ttrace_util_0.Count(_util_00000, 4)\n\tfor i := len(input) - 1; i >= 0; i-- {\n\t\ttrace_util_0.Count(_util_00000, 6)\n\t\tif filter(input[i]) {\n\t\t\ttrace_util_0.Count(_util_00000, 7)\n\t\t\tfilteredOut = append(filteredOut, input[i])\n\t\t\tinput = append(input[:i], input[i+1:]...)\n\t\t}\n\t}\n\ttrace_util_0.Count(_util_00000, 5)\n\treturn input, filteredOut\n}", "func filterTasksByNOCAccsess(tasks []models.Task, isNOCUser bool) (filteredTasks []models.Task) {\n\tfor _, task := range tasks {\n\t\tif !isNOCUser && task.IsRequireNOCAccess {\n\t\t\tcontinue\n\t\t}\n\t\tfilteredTasks = append(filteredTasks, task)\n\t}\n\treturn\n}", "func OutcomeOverviewParticipantsNotIn(vs ...string) predicate.OutcomeOverview {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldOutcomeOverviewParticipants), v...))\n\t})\n}", "func (d *Deduplicator) Filter(trans []schema.XMLTransaction) []schema.XMLTransaction {\n\tif d.state.IsZero() {\n\t\treturn trans\n\t}\n\tvar res []schema.XMLTransaction\n\tfor _, tran := range trans {\n\t\tif !d.state.Filter(tran) {\n\t\t\tres = append(res, tran)\n\t\t}\n\t}\n\treturn res\n}", "func Filter(peers []Peer, f func(Peer) bool) []Peer {\n\tfiltered := make([]Peer, 0)\n\n\tfor _, peer := range peers {\n\t\tif f(peer) {\n\t\t\tfiltered = append(filtered, peer)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func Without[T comparable](collection []T, exclude ...T) []T {\n\tresult := make([]T, 0, len(collection))\n\tfor _, e := range collection {\n\t\tif !Contains(exclude, e) {\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\treturn result\n}", "func (d *Demo) FilterNin(g *gom.Gom) {\n\ttoolkit.Println(\"===== Not In =====\")\n\tres := []models.Hero{}\n\tnames := []interface{}{\"Green Arrow\", \"Red Arrow\"}\n\n\tvar err error\n\tif d.useParams {\n\t\t_, err = g.Set(&gom.SetParams{\n\t\t\tTableName: \"hero\",\n\t\t\tResult: &res,\n\t\t\tFilter: gom.Nin(\"Name\", names...),\n\t\t\tTimeout: 10,\n\t\t}).Cmd().Get()\n\t} else {\n\t\t_, err = g.Set(nil).Table(\"hero\").Timeout(10).Result(&res).Filter(gom.Nin(\"Name\", names...)).Cmd().Get()\n\t}\n\n\tif err != nil {\n\t\ttoolkit.Println(err.Error())\n\t\treturn\n\t}\n\n\tfor _, h := range res {\n\t\ttoolkit.Println(h)\n\t}\n}", "func (l *Log) SliceNotApplied() (ents []pb.Entry) {\n\treturn l.sliceSince(l.applied)\n}", "func DiscardAbundantPartners(\n\tcandidatesPtr *[]Candidate,\n\tmaxGenePartners int) {\n\tcandidates := *candidatesPtr\n\n\t// First pass, record every gene and its partners\n\tpartners := map[GeneID]map[GeneID]struct{}{}\n\taddGenePair := func(g1, g2 GeneID) {\n\t\tif partners[g1] == nil {\n\t\t\tpartners[g1] = map[GeneID]struct{}{}\n\t\t}\n\t\tpartners[g1][g2] = struct{}{}\n\t}\n\n\tfor _, c := range candidates {\n\t\tfor _, fusion := range c.Fusions {\n\t\t\taddGenePair(fusion.G1ID, fusion.G2ID)\n\t\t\taddGenePair(fusion.G2ID, fusion.G1ID)\n\t\t}\n\t}\n\n\t// Now that we have an idea of the number of unique partners per gene, we can\n\t// discard those with > cap partners.\n\tisGeneWithAbundantPartners := func(g GeneID) bool {\n\t\treturn len(partners[g]) > maxGenePartners\n\t}\n\tvar (\n\t\tj int\n\t\tnDiscardedFusion int\n\t\tnTotalFusion int\n\t)\n\tfor _, c := range candidates {\n\t\tvar k int\n\t\tfor _, fusion := range c.Fusions {\n\t\t\tnTotalFusion++\n\t\t\tif isGeneWithAbundantPartners(fusion.G1ID) || isGeneWithAbundantPartners(fusion.G2ID) {\n\t\t\t\tnDiscardedFusion++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Fusions[k] = fusion\n\t\t\tk++\n\t\t}\n\t\tc.Fusions = c.Fusions[:k]\n\t\tif len(c.Fusions) > 0 {\n\t\t\tcandidates[j] = c\n\t\t\tj++\n\t\t}\n\t}\n\tlog.Printf(\n\t\t\"Discarding %d of %d candidates, %d of %d fusions for having too many fusion partners\",\n\t\tlen(candidates)-j, len(candidates), nDiscardedFusion, nTotalFusion)\n\t*candidatesPtr = candidates[:j]\n}", "func (vi *Index) NoCheaters(selfParent *hash.Event, options hash.Events) hash.Events {\n\tif selfParent == nil {\n\t\treturn options\n\t}\n\tvi.initBranchesInfo()\n\n\t// no need to merge, because every branch is marked by IsForkDetected if fork is observed\n\thighest := vi.GetHighestBeforeSeq(*selfParent)\n\tfiltered := make(hash.Events, 0, len(options))\n\tfor _, id := range options {\n\t\theader := vi.getEvent(id)\n\t\tif header == nil {\n\t\t\tvi.Log.Crit(\"Event not found\", \"id\", id.String())\n\t\t}\n\t\tif !highest.Get(vi.validatorIdxs[header.Creator]).IsForkDetected() {\n\t\t\tfiltered.Add(id)\n\t\t}\n\t}\n\treturn filtered\n}", "func GetIndicesWithoutIgnored() (parsedIndices []types.Index, err string) {\n\tvar indices, getErr = GetIndices()\n\tcleanIndices := make([]types.Index, len(parsedIndices))\n\tfor _, indexed := range indices {\n\t\tvar ignorable bool\n\t\tfor _, ignored := range singleton.GetConfig().Parser.Ignorelist {\n\t\t\tif ignored != \"\" {\n\t\t\t\tr, _ := regexp.Compile(ignored)\n\n\t\t\t\tif r.MatchString(indexed.Name) {\n\n\t\t\t\t\tignorable = true\n\t\t\t\t\tif singleton.GetVerbose() {\n\t\t\t\t\t\tlog.Println(\"Index name: \" + indexed.Name + \" matches the regex: \" + ignored)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !ignorable {\n\t\t\tcleanIndices = append(cleanIndices, indexed)\n\t\t}\n\t\tignorable = false\n\t}\n\treturn cleanIndices, getErr\n}", "func Filter(peptides types.Peptides, genes types.Genes) types.Peptides {\n\tfilteredPeptides := make(types.Peptides, len(peptides))\n\tfor peptide := range peptides {\n\t\tfilteredPeptides[peptide] = peptides[peptide].Copy()\n\t\tkeepGenes := make([]string, 0)\n\t\tfor _, gene := range filteredPeptides[peptide].Genes {\n\t\t\tif _, ok := genes[gene]; ok {\n\t\t\t\tkeepGenes = append(keepGenes, gene)\n\t\t\t}\n\t\t}\n\t\tfilteredPeptides[peptide].Genes = keepGenes\n\t}\n\treturn filteredPeptides\n}", "func ResponsibilitiesNotIn(vs ...string) predicate.Job {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldResponsibilities), v...))\n\t})\n}", "func UnexcludedRange(handRange []HoleCards, runout map[string]bool) []HoleCards {\n\tres := make([]HoleCards, 0, len(handRange))\n\tfor _, hand := range handRange {\n\t\tif !runout[hand[0]] && !runout[hand[1]] {\n\t\t\tres = append(res, hand)\n\t\t}\n\t}\n\treturn res\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecOutput) ExcludedFilterKeys() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaSearchRequestFacetSpec) []string { return v.ExcludedFilterKeys }).(pulumi.StringArrayOutput)\n}", "func removeSliceElements(txOuts []*apitypes.AddressTxnOutput, inds []int) []*apitypes.AddressTxnOutput {\n\t// Remove entries from the end to the beginning of the slice.\n\tsort.Slice(inds, func(i, j int) bool { return inds[i] > inds[j] }) // descending indexes\n\tfor _, g := range inds {\n\t\tif g > len(txOuts)-1 {\n\t\t\tcontinue\n\t\t}\n\t\ttxOuts[g] = txOuts[len(txOuts)-1] // overwrite element g with last element\n\t\ttxOuts[len(txOuts)-1] = nil // nil out last element\n\t\ttxOuts = txOuts[:len(txOuts)-1]\n\t}\n\treturn txOuts\n}", "func (_IStaking *IStakingFilterer) FilterUnregistered(opts *bind.FilterOpts, oracle []common.Address) (*IStakingUnregisteredIterator, error) {\n\n\tvar oracleRule []interface{}\n\tfor _, oracleItem := range oracle {\n\t\toracleRule = append(oracleRule, oracleItem)\n\t}\n\n\tlogs, sub, err := _IStaking.contract.FilterLogs(opts, \"Unregistered\", oracleRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &IStakingUnregisteredIterator{contract: _IStaking.contract, event: \"Unregistered\", logs: logs, sub: sub}, nil\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecPtrOutput) ExcludedFilterKeys() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *GoogleCloudRetailV2alphaSearchRequestFacetSpec) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ExcludedFilterKeys\n\t}).(pulumi.StringArrayOutput)\n}", "func (n *Uint256) Not() *Uint256 {\n\tn.n[0] = ^n.n[0]\n\tn.n[1] = ^n.n[1]\n\tn.n[2] = ^n.n[2]\n\tn.n[3] = ^n.n[3]\n\treturn n\n}", "func NotInvoicedGTE(v float32) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldNotInvoiced), v))\n\t})\n}", "func (cp *MultiStrategy) Filter() ([]peer.ID, error) {\n\tpeerIDs := make([]peer.ID, 0)\n\tdupCheck := make(map[string]bool)\n\n\t// add all filters\n\tfor _, filter := range cp.filters {\n\t\tpeers, err := filter.Filter()\n\t\tif err != nil {\n\t\t\treturn peerIDs, err\n\t\t}\n\t\tfor _, peerID := range peers {\n\t\t\tif _, ok := dupCheck[peerID.Pretty()]; !ok {\n\t\t\t\tdupCheck[peerID.Pretty()] = true\n\t\t\t\tpeerIDs = append(peerIDs, peerID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// add extra peers\n\tfor _, peerID := range cp.peerIDs {\n\t\tif _, ok := dupCheck[peerID.Pretty()]; !ok {\n\t\t\tdupCheck[peerID.Pretty()] = true\n\t\t\tpeerIDs = append(peerIDs, peerID)\n\t\t}\n\t}\n\n\treturn peerIDs, nil\n}", "func ClientidNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldClientid), v...))\n\t})\n}", "func (_Token *TokenFilterer) FilterMintFrozen(opts *bind.FilterOpts, to []common.Address) (*TokenMintFrozenIterator, error) {\n\n\tvar toRule []interface{}\n\tfor _, toItem := range to {\n\t\ttoRule = append(toRule, toItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.FilterLogs(opts, \"MintFrozen\", toRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenMintFrozenIterator{contract: _Token.contract, event: \"MintFrozen\", logs: logs, sub: sub}, nil\n}", "func filterDataMembers(mems []pubcluster.MemberInfo) []pubcluster.MemberInfo {\n\tdi := len(mems)\nloop:\n\tfor i := 0; i < di; i++ {\n\t\tif mems[i].LiteMember {\n\t\t\t// order is not important, delete by moving deleted items to the end.\n\t\t\t// find the first non-lite member\n\t\t\tdi--\n\t\t\tfor mems[di].LiteMember {\n\t\t\t\tif di <= i {\n\t\t\t\t\t// no more data members left\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t\tdi--\n\t\t\t}\n\t\t\tmems[i], mems[di] = mems[di], mems[i]\n\t\t}\n\t}\n\t// all deleted items are at the end.\n\t// shrink the slice to get rid of them.\n\treturn mems[:di]\n}", "func (lp *logPoller) IndexedLogsWithSigsExcluding(address common.Address, eventSigA, eventSigB common.Hash, topicIndex int, fromBlock, toBlock int64, confs int, qopts ...pg.QOpt) ([]Log, error) {\n\treturn lp.orm.SelectIndexedLogsWithSigsExcluding(eventSigA, eventSigB, topicIndex, address, fromBlock, toBlock, confs, qopts...)\n}", "func (mi *MasterIndex) FinalizeNotFinalIndexes() []*Index {\n\tmi.idxMutex.Lock()\n\tdefer mi.idxMutex.Unlock()\n\n\tvar list []*Index\n\n\tfor _, idx := range mi.idx {\n\t\tif !idx.Final() {\n\t\t\tidx.Finalize()\n\t\t\tlist = append(list, idx)\n\t\t}\n\t}\n\n\tdebug.Log(\"return %d indexes\", len(list))\n\treturn list\n}", "func Not(p predicate.Bulk) predicate.Bulk {\n\treturn predicate.Bulk(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func XNotIn(vs ...int) predicate.Road {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Road(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldX), v...))\n\t})\n}", "func (_Contracts *ContractsFilterer) FilterVerified(opts *bind.FilterOpts, _voter []*big.Int, _proposal []*big.Int, _position []*big.Int) (*ContractsVerifiedIterator, error) {\n\n\tvar _voterRule []interface{}\n\tfor _, _voterItem := range _voter {\n\t\t_voterRule = append(_voterRule, _voterItem)\n\t}\n\tvar _proposalRule []interface{}\n\tfor _, _proposalItem := range _proposal {\n\t\t_proposalRule = append(_proposalRule, _proposalItem)\n\t}\n\tvar _positionRule []interface{}\n\tfor _, _positionItem := range _position {\n\t\t_positionRule = append(_positionRule, _positionItem)\n\t}\n\n\tlogs, sub, err := _Contracts.contract.FilterLogs(opts, \"Verified\", _voterRule, _proposalRule, _positionRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractsVerifiedIterator{contract: _Contracts.contract, event: \"Verified\", logs: logs, sub: sub}, nil\n}", "func filterOutPermissions(permList, filterOutList []string) []string {\n\tfilteredPerms := []string{}\n\tfor _, perm := range permList {\n\t\tfilterOut := false\n\t\tfor _, filterPerm := range filterOutList {\n\t\t\tif perm == filterPerm {\n\t\t\t\tfilterOut = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif filterOut {\n\t\t\tcontinue\n\t\t}\n\t\tfilteredPerms = append(filteredPerms, perm)\n\t}\n\treturn filteredPerms\n}", "func FilterOnlyNewEntitlements(dependents []Dependent) []Dependent {\n\twithNewEntitlements := []Dependent{}\n\n\tfor _, d := range dependents {\n\n\t\tif d.HasNewEntitlements() {\n\t\t\twithNewEntitlements = append(withNewEntitlements, d)\n\t\t}\n\t}\n\n\treturn withNewEntitlements\n}", "func filteredByNOCMap(tasks []models.Task, isNOCUser bool) (filteredTasks map[gocql.UUID]models.Task) {\n\tfilteredTasks = make(map[gocql.UUID]models.Task)\n\tfor _, task := range tasks {\n\t\tif !isNOCUser && task.IsRequireNOCAccess {\n\t\t\tcontinue\n\t\t}\n\n\t\tgotTask, ok := filteredTasks[task.ID]\n\t\tif !ok {\n\t\t\tfilteredTasks[task.ID] = task\n\t\t\tcontinue\n\t\t}\n\n\t\t// find the nearest ModifiedAt\n\t\tif task.ModifiedAt.After(gotTask.ModifiedAt) {\n\t\t\tfilteredTasks[task.ID] = task\n\t\t}\n\t}\n\treturn\n}", "func excludePeer(peers []net.Addr, peer net.Addr) []net.Addr {\n\totherPeers := make([]net.Addr, 0, len(peers))\n\tfor _, p := range peers {\n\t\tif p.String() != peer.String() {\n\t\t\totherPeers = append(otherPeers, p)\n\t\t}\n\t}\n\treturn otherPeers\n}", "func filterClustersWithIndices(elements [][]float64, indices []int) [][]float64 {\n\tvar ret [][]float64\n\tfor index, value := range elements {\n\t\tvar includes bool\n\t\tfor _, idx := range indices {\n\t\t\tif index == idx {\n\t\t\t\tincludes = true\n\t\t\t}\n\t\t}\n\n\t\tif !includes {\n\t\t\tret = append(ret, value)\n\t\t}\n\t}\n\treturn ret\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecResponseOutput) ExcludedFilterKeys() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaSearchRequestFacetSpecResponse) []string { return v.ExcludedFilterKeys }).(pulumi.StringArrayOutput)\n}", "func solvedNoPossible(cluster []cell) (changes []cell) {\n\tfor id, each := range cluster {\n\t\tif each.actual != 0 && len(each.excluded) < len(fullArray) {\n\t\t\tnewExclusion := subArr(fullArray, each.excluded)\n\t\t\tchanges = append(changes, cell{location: each.location, excluded: newExclusion})\n\t\t}\n\t}\n\treturn\n}", "func WorkplaceNotIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldWorkplace), v...))\n\t})\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserFilterer) FilterOwnershipRenounced(opts *bind.FilterOpts, previousOwner []common.Address) (*ProjectWalletAuthoriserOwnershipRenouncedIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\n\tlogs, sub, err := _ProjectWalletAuthoriser.contract.FilterLogs(opts, \"OwnershipRenounced\", previousOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ProjectWalletAuthoriserOwnershipRenouncedIterator{contract: _ProjectWalletAuthoriser.contract, event: \"OwnershipRenounced\", logs: logs, sub: sub}, nil\n}", "func (k *KRPC) notQueried(queriedNodes *boom.BloomFilter, contacts []bucket.ContactIdentifier) []bucket.ContactIdentifier {\n\tif contacts == nil {\n\t\treturn []bucket.ContactIdentifier{}\n\t}\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\tret := []bucket.ContactIdentifier{}\n\tfor _, c := range contacts {\n\t\tif !queriedNodes.TestAndAdd([]byte(c.GetAddr().String())) {\n\t\t\tret = append(ret, c)\n\t\t}\n\t}\n\treturn ret\n}", "func filterOutCondition(conditions []farosv1alpha1.GitTrackObjectCondition, condType farosv1alpha1.GitTrackObjectConditionType) []farosv1alpha1.GitTrackObjectCondition {\n\tvar newConditions []farosv1alpha1.GitTrackObjectCondition\n\tfor _, c := range conditions {\n\t\tif c.Type == condType {\n\t\t\tcontinue\n\t\t}\n\t\tnewConditions = append(newConditions, c)\n\t}\n\treturn newConditions\n}", "func (_TokensNetwork *TokensNetworkFilterer) FilterChannelUnlocked(opts *bind.FilterOpts, channel_identifier [][32]byte) (*TokensNetworkChannelUnlockedIterator, error) {\n\n\tvar channel_identifierRule []interface{}\n\tfor _, channel_identifierItem := range channel_identifier {\n\t\tchannel_identifierRule = append(channel_identifierRule, channel_identifierItem)\n\t}\n\n\tlogs, sub, err := _TokensNetwork.contract.FilterLogs(opts, \"ChannelUnlocked\", channel_identifierRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokensNetworkChannelUnlockedIterator{contract: _TokensNetwork.contract, event: \"ChannelUnlocked\", logs: logs, sub: sub}, nil\n}", "func (cluster *HttpCluster) NonActive() []string {\n\tcluster.RLock()\n\tdefer cluster.RUnlock()\n\tmember := cluster.active\n\tlist := make([]string, 0)\n\tfor i := 0; i < cluster.size; i++ {\n\t\tif member.status == MEMBER_UNAVAILABLE {\n\t\t\tlist = append(list, member.hostname)\n\t\t}\n\t}\n\treturn list\n}", "func NotInvoicedNotIn(vs ...float32) predicate.Order {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldNotInvoiced), v...))\n\t})\n}", "func NumNotIn(vs ...int) predicate.Repairinvoice {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Repairinvoice(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldNum), v...))\n\t})\n}", "func DetachIndexConditions(conditions []expression.Expression, cols []*expression.Column,\n\tlengths []int) (accessConds []expression.Expression, filterConds []expression.Expression) {\n\taccessConds = make([]expression.Expression, len(cols))\n\tvar equalOrInCount int\n\tfor _, cond := range conditions {\n\t\toffset := getEqOrInColOffset(cond, cols)\n\t\tif offset != -1 {\n\t\t\taccessConds[offset] = cond\n\t\t}\n\t}\n\tfor i, cond := range accessConds {\n\t\tif cond == nil {\n\t\t\taccessConds = accessConds[:i]\n\t\t\tequalOrInCount = i\n\t\t\tbreak\n\t\t}\n\t\tif lengths[i] != types.UnspecifiedLength {\n\t\t\tfilterConds = append(filterConds, cond)\n\t\t}\n\t\tif i == len(accessConds)-1 {\n\t\t\tequalOrInCount = len(accessConds)\n\t\t}\n\t}\n\t// We should remove all accessConds, so that they will not be added to filter conditions.\n\tconditions = removeAccessConditions(conditions, accessConds)\n\tif equalOrInCount == len(cols) {\n\t\t// If curIndex equals to len of index columns, it means the rest conditions haven't been appended to filter conditions.\n\t\tfilterConds = append(filterConds, conditions...)\n\t\treturn accessConds, filterConds\n\t}\n\treturn extractAccessAndFilterConds(conditions, accessConds, filterConds, cols[equalOrInCount], lengths[equalOrInCount])\n}", "func MaskNotIn(vs ...int) predicate.IP {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.IP(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldMask), v...))\n\t})\n}", "func TeamNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldTeam), v...))\n\t})\n}", "func (_Cakevault *CakevaultFilterer) FilterUnpaused(opts *bind.FilterOpts) (*CakevaultUnpausedIterator, error) {\n\n\tlogs, sub, err := _Cakevault.contract.FilterLogs(opts, \"Unpaused\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CakevaultUnpausedIterator{contract: _Cakevault.contract, event: \"Unpaused\", logs: logs, sub: sub}, nil\n}", "func (cil ClusterInstanceList) Except(i ClusterInstance) ClusterInstanceList {\n\tresult := ClusterInstanceList{}\n\tfor _, x := range cil {\n\t\tif !x.Equals(i) {\n\t\t\tresult = append(result, x)\n\t\t}\n\t}\n\treturn result\n}", "func (fn FilterNone) Filter(incidnetsChan <-chan Incident, filteredIncidnetsChan chan<- Incident) {\n\tfn.l.WithFields(log.Fields{\n\t\t\"source\": \"FilterNone\",\n\t\t\"stage\": \"filter\",\n\t}).Info(\"starting FilterNone\")\n\n\tfor v := range incidnetsChan {\n\t\tfn.l.WithFields(log.Fields{\n\t\t\t\"source\": \"FilterNone\",\n\t\t\t\"stage\": \"filter\",\n\t\t\t\"content\": fmt.Sprintf(\"%#v\", v),\n\t\t}).Trace(\"passing through value\")\n\t\tfn.l.WithFields(log.Fields{\n\t\t\t\"source\": \"FilterNone\",\n\t\t\t\"stage\": \"filter\",\n\t\t\t\"Incidnet\": v.Summary,\n\t\t}).Debug(\"Filter Incident\")\n\t\tfilteredIncidnetsChan <- v\n\t}\n}", "func OutcomeOverviewParticipantsNEQ(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldOutcomeOverviewParticipants), v))\n\t})\n}", "func (f *fragment) unprotectedRows(start uint64, filters ...rowFilter) []uint64 {\n\tstartKey := rowToKey(start)\n\ti, _ := f.storage.Containers.Iterator(startKey)\n\trows := make([]uint64, 0)\n\tvar lastRow uint64 = math.MaxUint64\n\n\t// Loop over the existing containers.\n\tfor i.Next() {\n\t\tkey, c := i.Value()\n\n\t\t// virtual row for the current container\n\t\tvRow := key >> shardVsContainerExponent\n\n\t\t// skip dups\n\t\tif vRow == lastRow {\n\t\t\tcontinue\n\t\t}\n\n\t\t// apply filters\n\t\taddRow, done := true, false\n\t\tfor _, filter := range filters {\n\t\t\tvar d bool\n\t\t\taddRow, d = filter(vRow, key, c)\n\t\t\tdone = done || d\n\t\t\tif !addRow {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif addRow {\n\t\t\tlastRow = vRow\n\t\t\trows = append(rows, vRow)\n\t\t}\n\t\tif done {\n\t\t\treturn rows\n\t\t}\n\t}\n\treturn rows\n}", "func Filter(vs []int, f func(int) bool) []int {\n\tvsf := make([]int, 0)\n\tfor _, v := range vs {\n\t\tif f(v) {\n\t\t\tvsf = append(vsf, v)\n\t\t}\n\t}\n\treturn vsf\n}", "func FilterCommits(dbName string, commits []github.RepositoryCommit) []github.RepositoryCommit {\n\tvar filtered []github.RepositoryCommit\n\n\tfor _, commit := range commits {\n\t\tif IsValidCommit(*commit.Commit.Message) &&\n\t\t\tGetSHA(dbName, *commit.SHA) == false {\n\n\t\t\tfiltered = append(filtered, commit)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func SendIDNotIn(vs ...string) predicate.Block {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Block(func(s *sql.Selector) {\n\t\ts.Where(sql.NotIn(s.C(FieldSendID), v...))\n\t})\n}", "func (c *Collector) FilterInvalidObjects(objs object.UnstructuredSet) object.UnstructuredSet {\n\tvar diff object.UnstructuredSet\n\tfor _, obj := range objs {\n\t\tif !c.InvalidIds.Contains(object.UnstructuredToObjMetadata(obj)) {\n\t\t\tdiff = append(diff, obj)\n\t\t}\n\t}\n\treturn diff\n}", "func (ls *LocalStorage) filterAllowedNodes(clients map[string]provisioner.API, deploymentName, role string) ([]provisioner.API, error) {\n\t// Find all PVs for given deployment & role\n\tlist, err := ls.deps.KubeCli.CoreV1().PersistentVolumes().List(metav1.ListOptions{\n\t\tLabelSelector: fmt.Sprintf(\"%s=%s,%s=%s\", k8sutil.LabelKeyArangoDeployment, deploymentName, k8sutil.LabelKeyRole, role),\n\t})\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\texcludedNodes := make(map[string]struct{})\n\tfor _, pv := range list.Items {\n\t\tnodeName := pv.GetAnnotations()[nodeNameAnnotation]\n\t\texcludedNodes[nodeName] = struct{}{}\n\t}\n\tresult := make([]provisioner.API, 0, len(clients))\n\tfor nodeName, c := range clients {\n\t\tif _, found := excludedNodes[nodeName]; !found {\n\t\t\tresult = append(result, c)\n\t\t}\n\t}\n\treturn result, nil\n}", "func (g *Group) InactiveMemberIDs() []MemberIndex {\n\treturn g.inactiveMemberIDs\n}", "func CoveredPersonNumberNotIn(vs ...string) predicate.CoveredPerson {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldCoveredPersonNumber), v...))\n\t})\n}", "func DisabledAtNotIn(vs ...time.Time) predicate.GameServer {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldDisabledAt), v...))\n\t})\n}", "func InvoicedNotIn(vs ...float32) predicate.Order {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldInvoiced), v...))\n\t})\n}", "func (m Map) Without(filter Coord) Map {\n\tfiltered := make(Map, 0)\n\n\tfor _, c := range m {\n\t\tif c != filter {\n\t\t\tfiltered = append(filtered, c)\n\t\t}\n\t}\n\n\treturn filtered\n}", "func FilterOut(t transport.Transport, filePath string, toBan []string) (filtered int, duplicates int, nbMatch int) {\n\tfor i := 0; i < len(toBan); i++ {\n\t\tlogger.Debugf(\"Should ban: %s\", toBan[i])\n\t}\n\n\ttmpfile, err := ioutil.TempFile(\"\", t.GetID())\n\tlogger.Debugf(\"Write filtered file: %s\", tmpfile.Name())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tfiltered = 0\n\tduplicates = 0\n\tnbMatch = 0\n\tscanner := bufio.NewScanner(file)\n\tprevMatch := \"\"\n\tfor scanner.Scan() {\n\t\tmatch := [][]logol.Match{}\n\t\tjsonMatch := scanner.Text()\n\t\tif jsonMatch == prevMatch {\n\t\t\tduplicates++\n\t\t\tcontinue\n\t\t}\n\t\tprevMatch = jsonMatch\n\t\t// fmt.Println(jsonMatch)\n\t\terr := json.Unmarshal([]byte(jsonMatch), &match)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to load a match, skipping it: %s\", jsonMatch)\n\t\t\tcontinue\n\t\t}\n\t\tmustBeRemoved := false\n\t\tfor i := 0; i < len(match); i++ {\n\t\t\tsmatch := match[i]\n\t\t\tfor j := 0; j < len(smatch); j++ {\n\t\t\t\tssmatch := smatch[j]\n\t\t\t\tfor t := 0; t < len(toBan); t++ {\n\t\t\t\t\tmToBan := toBan[t]\n\t\t\t\t\t_, found := ssmatch.GetByUid(mToBan)\n\t\t\t\t\tif found {\n\t\t\t\t\t\tmustBeRemoved = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif mustBeRemoved {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif mustBeRemoved {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !mustBeRemoved {\n\t\t\tfmt.Fprintln(tmpfile, \"\", jsonMatch)\n\t\t\tnbMatch++\n\t\t} else {\n\t\t\tfiltered++\n\t\t}\n\t}\n\tos.Rename(tmpfile.Name(), filePath)\n\treturn filtered, duplicates, nbMatch\n}", "func (x *Xroads) TrimNonIntersections() {\n\tx.Mutex.Lock()\n\tfor nodeID, wayIDs := range x.NodeMap {\n\t\tif len(wayIDs) < 2 {\n\t\t\tdelete(x.NodeMap, nodeID)\n\t\t} else {\n\t\t\t// insert all intersection way IDs in mask\n\t\t\tfor _, wayID := range wayIDs {\n\t\t\t\tx.IntersectionWaysMask.Insert(wayID)\n\t\t\t}\n\t\t}\n\t}\n\tx.Mutex.Unlock()\n}", "func NonMaxSuppression(scope *Scope, boxes tf.Output, scores tf.Output, max_output_size tf.Output, optional ...NonMaxSuppressionAttr) (selected_indices tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"NonMaxSuppression\",\n\t\tInput: []tf.Input{\n\t\t\tboxes, scores, max_output_size,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func NotReceivedNotIn(vs ...float32) predicate.Order {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldNotReceived), v...))\n\t})\n}", "func Not(p predicate.Project) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func Not(p predicate.Project) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\tp(s.Not())\n\t})\n}", "func removeBooleanListener(list []BooleanListener, index int) []BooleanListener {\n\tcopy(list[index:], list[index+1:])\n\treturn list[:len(list)-1]\n}", "func (candidate *Candidate) getFilteredUpdates() []*stake {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\tvar updates []*stake\n\tfor _, update := range candidate.updates {\n\t\t// skip updates with 0 stakes\n\t\tupdate.lock.RLock()\n\t\tif update.Value.Cmp(big.NewInt(0)) != 1 {\n\t\t\tupdate.lock.RUnlock()\n\t\t\tcontinue\n\t\t}\n\n\t\t// merge updates\n\t\tmerged := false\n\t\tfor _, u := range updates {\n\n\t\t\tu.lock.Lock()\n\t\t\tif u.Coin == update.Coin && u.Owner == update.Owner {\n\t\t\t\tu.Value = big.NewInt(0).Add(u.Value, update.Value)\n\t\t\t\tu.lock.Unlock()\n\n\t\t\t\tmerged = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tu.lock.Unlock()\n\t\t}\n\n\t\tupdate.lock.RUnlock()\n\n\t\tif !merged {\n\t\t\tupdates = append(updates, update)\n\t\t}\n\t}\n\n\treturn updates\n}", "func filterNot(args []sexp) (Filter, error) {\n\tif len(args) != 1 {\n\t\treturn nil, fmt.Errorf(\"not [%v]: %w\", args, ErrWrongArgCount)\n\t}\n\tf, err := compileSexp(args[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"compiling not filter: %w\", err)\n\t}\n\treturn func(msg *layers.SIP) bool {\n\t\treturn !f(msg)\n\t}, nil\n}", "func NonParticipant() parameter.Parameter {\n\treturn Other(\"NON-PARTICIPANT\")\n}", "func (sm *SharedManager) unprocessedIndexBlobsUnlocked(ctx context.Context, contents []IndexBlobInfo) (resultCh <-chan blob.ID, totalSize int64, err error) {\n\tch := make(chan blob.ID, len(contents))\n\tdefer close(ch)\n\n\tfor _, c := range contents {\n\t\thas, err := sm.committedContents.cache.hasIndexBlobID(ctx, c.BlobID)\n\t\tif err != nil {\n\t\t\treturn nil, 0, errors.Wrapf(err, \"error determining whether index blob %v has been downloaded\", c.BlobID)\n\t\t}\n\n\t\tif has {\n\t\t\tformatLog(ctx).Debugf(\"index-already-cached %v\", c.BlobID)\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- c.BlobID\n\t\ttotalSize += c.Length\n\t}\n\n\treturn ch, totalSize, nil\n}", "func (_ERC20Pausable *ERC20PausableFilterer) FilterUnpaused(opts *bind.FilterOpts) (*ERC20PausableUnpausedIterator, error) {\n\n\tlogs, sub, err := _ERC20Pausable.contract.FilterLogs(opts, \"Unpaused\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ERC20PausableUnpausedIterator{contract: _ERC20Pausable.contract, event: \"Unpaused\", logs: logs, sub: sub}, nil\n}", "func (in Ints) Discard(f func(int) bool) (out Ints) {\n\tfor _, val := range in {\n\t\tif !f(val) {\n\t\t\tout = append(out, val)\n\t\t}\n\t}\n\treturn out\n}", "func UseridNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUserid), v...))\n\t})\n}", "func (i Ints) Discard(f func(int) bool) Ints {\n\tvar toReturn Ints\n\tfor _, v := range i {\n\t\tif !f(v) {\n\t\t\ttoReturn = append(toReturn, v)\n\t\t}\n\t}\n\treturn toReturn\n}", "func filterExclusive(excludeRegex *regexp.Regexp, products []*Product) []*Product {\n\tvar filtered []*Product\n\tif excludeRegex != nil {\n\t\tfor _, product := range products {\n\t\t\tif excludeRegex.MatchString(product.Name) {\n\t\t\t\tlog.Debugf(\"product %s excluded because it matches the exclude regex\", product.Name)\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"product %s included because it does not match the exclude regex\", product.Name)\n\t\t\t\tfiltered = append(filtered, product)\n\t\t\t}\n\t\t}\n\t\treturn filtered\n\t}\n\treturn products\n}", "func filterOutPodByOwnerReferenceKind(podList []v1.Pod, kind string) (output []v1.Pod) {\n\tfor _, pod := range podList {\n\t\tfor _, ownerReference := range pod.ObjectMeta.OwnerReferences {\n\t\t\tif ownerReference.Kind != kind {\n\t\t\t\toutput = append(output, pod)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func ExcludeFromSlice(sl []string, exclude map[string]string) []string {\n\tres := make([]string, len(sl))\n\ti := 0\n\tfor k, v := range sl {\n\t\t_, isExcluded := exclude[v]\n\t\tif isExcluded {\n\t\t\tcontinue\n\t\t}\n\t\tres[k] = v\n\t\ti++\n\t}\n\treturn res[:i]\n}", "func ClientIDNotIn(vs ...string) predicate.Order {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldClientID), v...))\n\t})\n}", "func (s *Subscribe) GetIgnored() []*Subscriber {\n\tvar subs []*Subscriber\n\n\tfor _, sub := range s.Subscribers {\n\t\tif sub.Ignored {\n\t\t\tsubs = append(subs, sub)\n\t\t}\n\t}\n\n\treturn subs\n}", "func hiddenIndices(Disclosure []byte) []int {\n\tHiddenIndices := make([]int, 0)\n\tfor index, disclose := range Disclosure {\n\t\tif disclose == 0 {\n\t\t\tHiddenIndices = append(HiddenIndices, index)\n\t\t}\n\t}\n\treturn HiddenIndices\n}", "func hiddenIndices(Disclosure []byte) []int {\n\tHiddenIndices := make([]int, 0)\n\tfor index, disclose := range Disclosure {\n\t\tif disclose == 0 {\n\t\t\tHiddenIndices = append(HiddenIndices, index)\n\t\t}\n\t}\n\treturn HiddenIndices\n}", "func TagsNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldTags), v...))\n\t})\n}", "func (ints Ints) Discard(satisfies func(int) bool) Ints {\n\tvar keeps Ints\n\tfor _, val := range ints {\n\t\tif !satisfies(val) {\n\t\t\tkeeps = append(keeps, val)\n\t\t}\n\t}\n\n\treturn keeps\n}", "func FilterInts(x []int, filter func(int) bool) []int {\n\ty := x[:0]\n\tfor _, v := range x {\n\t\tif filter(v) {\n\t\t\ty = append(y, v)\n\t\t}\n\t}\n\treturn y\n}", "func excludeByIsolation(container *container.Snapshot, ctx *listContext) iterationAction {\n\treturn includeContainer\n}", "func filter(runes []rune, f func(rune) bool) []rune {\n\toutput := make([]rune, 0)\n\tfor _, r := range runes {\n\t\tif !f(r) {\n\t\t\toutput = append(output, r)\n\t\t}\n\t}\n\treturn output\n}", "func NotInvoicedIn(vs ...float32) predicate.Order {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldNotInvoiced), v...))\n\t})\n}", "func (_Contract *ContractFilterer) FilterVoteCanceled(opts *bind.FilterOpts) (*ContractVoteCanceledIterator, error) {\n\n\tlogs, sub, err := _Contract.contract.FilterLogs(opts, \"VoteCanceled\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractVoteCanceledIterator{contract: _Contract.contract, event: \"VoteCanceled\", logs: logs, sub: sub}, nil\n}", "func onlyPublic(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPublicAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t}\n\t}\n\treturn routable\n}", "func (_WyvernExchange *WyvernExchangeFilterer) FilterOwnershipRenounced(opts *bind.FilterOpts, previousOwner []common.Address) (*WyvernExchangeOwnershipRenouncedIterator, error) {\n\n\tvar previousOwnerRule []interface{}\n\tfor _, previousOwnerItem := range previousOwner {\n\t\tpreviousOwnerRule = append(previousOwnerRule, previousOwnerItem)\n\t}\n\n\tlogs, sub, err := _WyvernExchange.contract.FilterLogs(opts, \"OwnershipRenounced\", previousOwnerRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &WyvernExchangeOwnershipRenouncedIterator{contract: _WyvernExchange.contract, event: \"OwnershipRenounced\", logs: logs, sub: sub}, nil\n}", "func RepaircostNotIn(vs ...int) predicate.CarRepairrecord {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.CarRepairrecord(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldRepaircost), v...))\n\t})\n}", "func filterReleases(releases []*release.Release, ignoredReleaseNames []string) []*release.Release {\n\t// if ignoredReleaseNames is nil, just return releases\n\tif ignoredReleaseNames == nil {\n\t\treturn releases\n\t}\n\n\tvar filteredReleases []*release.Release\n\tfor _, rel := range releases {\n\t\tfound := false\n\t\tfor _, ignoredName := range ignoredReleaseNames {\n\t\t\tif rel.Name == ignoredName {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tfilteredReleases = append(filteredReleases, rel)\n\t\t}\n\t}\n\n\treturn filteredReleases\n}" ]
[ "0.6421765", "0.55129176", "0.55083704", "0.5222244", "0.511495", "0.5057186", "0.49680507", "0.49319294", "0.49185967", "0.47754484", "0.4771741", "0.4742586", "0.46975172", "0.46934822", "0.46650293", "0.46164444", "0.46133345", "0.46104798", "0.45709845", "0.45638588", "0.45441955", "0.45380232", "0.45283163", "0.45212865", "0.45198756", "0.45185432", "0.45158005", "0.4515542", "0.44955018", "0.44952148", "0.44948405", "0.44928056", "0.447691", "0.44729123", "0.44689667", "0.44647822", "0.44613218", "0.44521597", "0.4448457", "0.4438161", "0.44358906", "0.44298175", "0.4429535", "0.44285098", "0.44236895", "0.44189435", "0.44131717", "0.4410211", "0.44035605", "0.44014257", "0.4397387", "0.4391616", "0.4382447", "0.4380425", "0.4377465", "0.43676943", "0.4366932", "0.43632317", "0.43594104", "0.43562686", "0.4353957", "0.43539008", "0.43517482", "0.43445203", "0.43358895", "0.43284273", "0.43281507", "0.43248436", "0.4316109", "0.43061206", "0.43038866", "0.42946282", "0.42946282", "0.42945117", "0.42902917", "0.4289884", "0.42875776", "0.42827088", "0.42822576", "0.42807657", "0.42792848", "0.42704645", "0.42648983", "0.4263096", "0.4254366", "0.42465582", "0.42445073", "0.4243609", "0.4243609", "0.42431194", "0.42425725", "0.4236854", "0.4233544", "0.42260495", "0.42237404", "0.422242", "0.42210075", "0.42199263", "0.4212368", "0.4211999" ]
0.7585397
0
Send sends message using chat.postMessage from Slack's API
func (s slackService) Send(msg string, notifier entities.Notifier) error { request := newSlackRequest(msg, notifier) _, err := http.DefaultClient.Do(request) if err != nil { return errors.New("error requesting slack notifier " + notifier.Name) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SendMessageToSlack(message string) {\n\tfmt.Println(\"Sending message to slack...\")\n\n\thttp.Post(url, \"\")\n\n\treturn nil\n}", "func (s *SlackSvc) SendMessage(report ReportPayload) error {\n\tattachments := make([]map[string]interface{}, 1)\n\tattachments[0] = map[string]interface{}{\"text\": fmt.Sprintf(\"Howdy! Here's a list of *%d* PRs waiting to be reviewed and merged:\", len(report.PRs))}\n\tfor _, v := range report.PRs {\n\t\tattachments = append(attachments, map[string]interface{}{\"text\": v.ToString()})\n\t}\n\n\tif len(report.Reminders) > 0 {\n\t\tfor _, v := range report.Reminders {\n\t\t\tattachments = append(attachments, map[string]interface{}{\"text\": v.Text})\n\t\t}\n\t}\n\n\tmessage := map[string]interface{}{\n\t\t\"channel\": s.channelID,\n\t\t\"username\": s.user,\n\t\t\"icon_emoji\": \":robot_face:\",\n\t\t\"attachments\": attachments,\n\t}\n\n\tpayload, err := json.Marshal(message)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Failed to serialize Slack payload\")\n\t\treturn err\n\t}\n\n\tresp, err := s.client.Post(s.webhook, \"application/json\", bytes.NewReader(payload))\n\tif err != nil {\n\t\tlog.Error().Err(err).Msgf(\"Failed to serialize Slack payload: %v\", err)\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tlog.Info().Msgf(\"Message successfully sent to channel %s\", s.channelID)\n\treturn nil\n}", "func sendMessage(recipient string, reviewUrl string) {\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(SlackMessage{Channel: recipient, Text: reviewUrl})\n\tresp, _ := http.Post(os.Getenv(\"SLACKURL\"), \"application/json; charset=utf-8\", b)\n\n\tdefer resp.Body.Close()\n\tioutil.ReadAll(resp.Body)\n}", "func sendSlackMessage(message slack.Message) {\n\tuserData := SlackAPI.GetUserInfo(message.User)\n\ttimestampSplit := strings.Split(message.Ts, \".\")\n\ttimestampInt, err := strconv.ParseInt(timestampSplit[0], 10, 64)\n\ttimestamp := time.Unix(timestampInt, 0)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\terr = SlackAPI.PostMessage(conf.ChannelToMessage, conf.SlackMessageText)\n\tif err != nil {\n\t\tspew.Dump(err)\n\t}\n\n\terr = SlackAPI.PostMessage(conf.ChannelToMessage, \"> <@\"+userData.User.ID+\"> - \"+timestamp.Format(\"03:04:05 PM\")+\": \\n> \"+message.Text)\n\tif err != nil {\n\t\tspew.Dump(err)\n\t}\n}", "func (bot *SlackBot) sendMessage(msg Message) error {\n\tmsg.ID = atomic.AddUint64(&counter, 1)\n\terr := websocket.JSON.Send(bot.ws, msg)\n\treturn err\n}", "func (c *SlackConnection) SendMessage(message gateway.Message, channel *gateway.Channel) (*gateway.Message, error) {\n\tif strings.HasPrefix(message.Text, \"/\") {\n\t\t// Slash commands require some preprocessing.\n\t\treturn sendSlashCommand(c, message, channel)\n\t} else {\n\t\tlog.Printf(\"Sending message to team %s on channel %s\", c.Team().Name, channel.Name)\n\n\t\t// Otherwise just a plain message\n\t\t_, err := http.Get(\"https://slack.com/api/chat.postMessage?token=\" + c.token + \"&channel=\" + channel.Id + \"&text=\" + url.QueryEscape(message.Text) + \"&link_names=true&parse=full&unfurl_links=true&as_user=true\")\n\t\treturn nil, err\n\t}\n}", "func (s *Slack) SendMessage(msg string) error {\n\tlog.Logger.Info(fmt.Sprintf(\">> Sending to slack: %+v\", msg))\n\n\tapi := slack.New(s.Token)\n\tparams := slack.PostMessageParameters{\n\t\tAsUser: true,\n\t}\n\n\tchannelID, timestamp, err := api.PostMessage(s.Channel, msg, params)\n\tif err != nil {\n\t\tlog.Logger.Errorf(\"Error in sending slack message %s\", err.Error())\n\t\treturn err\n\t}\n\n\tlog.Logger.Infof(\"Message successfully sent to channel %s at %s\", channelID, timestamp)\n\treturn nil\n}", "func (m *Slack) Send(mes *message.Message) error {\n\topts := createSlackMessageOptions(mes.Text, mes.Image, mes.Fields, mes.Level)\n\n\t_channel, _timestamp, _text, err := m.api.SendMessage(m.channel, opts...)\n\n\tm.logger.Debug(\"send slack message\",\n\t\tzap.String(\"channel\", _channel),\n\t\tzap.String(\"timestamp\", _timestamp),\n\t\tzap.String(\"text\", _text),\n\t\tzap.Error(err),\n\t)\n\n\treturn err\n}", "func SlackSendMsg(slackAPI *slack.Client, MsgText string) error {\n\tif _, _, err := slackAPI.PostMessage(viper.GetString(\"slack_channel_id\"), slack.MsgOptionText(MsgText, false)); err != nil {\n\t\tlog.Errorf(\"[ERROR] %s\\n\", err)\n\t\treturn err\n\t}\n\tlog.Infof(\"[Slack] Send %s\", MsgText)\n\treturn nil\n}", "func (s *Slack) Send(color, msg string, v ...interface{}) error {\n\tb, err := json.Marshal(&payload{\n\t\tChannel: s.channel,\n\t\tUsername: s.username,\n\t\tIconURL: s.iconURL,\n\t\tAttachments: []attachment{\n\t\t\t{\n\t\t\t\tColor: color,\n\t\t\t\tText: fmt.Sprintf(msg, v...),\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.infof(\"payload: %s\", b)\n\tr, err := http.Post(s.webhookURL, \"application/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.infof(\"response: %s\", r.Status)\n\n\tif r.StatusCode >= 400 {\n\t\treturn &ResponseError{r}\n\t}\n\treturn nil\n}", "func send(api *slack.Client, message models.Message, bot *models.Bot) {\n\tusers, err := getSlackUsers(api, message)\n\tif err != nil {\n\t\tbot.Log.Errorf(\"Problem sending message: %s\", err.Error())\n\t}\n\tif message.DirectMessageOnly {\n\t\terr := handleDirectMessage(api, message, bot)\n\t\tif err != nil {\n\t\t\tbot.Log.Errorf(\"Problem sending message: %s\", err.Error())\n\t\t}\n\t} else {\n\t\terr := handleNonDirectMessage(api, users, message, bot)\n\t\tif err != nil {\n\t\t\tbot.Log.Errorf(\"Problem sending message: %s\", err.Error())\n\t\t}\n\t}\n}", "func sendMessage(api *slack.Client, ephemeral bool, channel, userID, text, threadTimeStamp, wsToken string, attachments []slack.Attachment) error {\n\t// send ephemeral message is indicated\n\tif ephemeral {\n\t\tvar opt slack.MsgOption\n\t\tif len(attachments) > 0 {\n\t\t\topt = slack.MsgOptionAttachments(attachments[0]) // only handling attachments messages with single attachments\n\t\t\t_, err := api.PostEphemeral(channel, userID, opt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\t// send standard message\n\tpmp := slack.PostMessageParameters{\n\t\tAsUser: true,\n\t\tThreadTimestamp: threadTimeStamp,\n\t}\n\t// check if message was a link to set link attachment\n\tif text != \"\" && strings.Contains(text, \"http\") {\n\t\tif isValidURL(text) {\n\t\t\tif len(attachments) > 0 {\n\t\t\t\tattachments[0].ImageURL = text\n\t\t\t} else {\n\t\t\t\tattachments = []slack.Attachment{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageURL: text,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tattachments[0].ImageURL = text\n\t\t\t}\n\t\t}\n\t}\n\t// include attachments if any\n\tif len(attachments) > 0 {\n\t\tpmp.Attachments = attachments\n\t}\n\t_, _, err := api.PostMessage(channel, text, pmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *SlackService) SendMessage(channel string, message string) {\n\t// https://godoc.org/github.com/nlopes/slack#PostMessageParameters\n\tpostParams := slack.PostMessageParameters{\n\t\tAsUser: true,\n\t}\n\n\t// https://godoc.org/github.com/nlopes/slack#Client.PostMessage\n\ts.Client.PostMessage(channel, message, postParams)\n}", "func MsgSlack(ctx *Context, msg string) error {\n\tcfg := ctx.Config\n\twebhookURL := \"https://hooks.slack.com/services/\" + cfg.Slacks[*ctx.ArgProfileName].Key\n\n\tlog.Printf(\"webhook: %s\", webhookURL)\n\n\tslackBody, _ := json.Marshal(slackRequestBody{Text: msg})\n\treq, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tif buf.String() != \"ok\" {\n\t\treturn errors.New(\"Non-ok response returned from Slack\")\n\t}\n\treturn nil\n}", "func (s *Slack) Post(msg Message) (err error) {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := bytes.NewBuffer(b)\n\n\treq, err := http.NewRequest(\"POST\", s.URL, buf)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Can't make new request\")\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\n\tif s.Verbose {\n\t\tif curl, err := http2curl.GetCurlCommand(req); err == nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"[CURL]: %v\", curl)\n\t\t}\n\t}\n\n\tclient := http.Client{Timeout: s.Timeout}\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Can't post request\")\n\t}\n\n\tdefer func() {\n\t\tif err := res.Body.Close(); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"[WARN]: %v\", errors.Wrap(err, \"Can't close response body\"))\n\t\t}\n\t}()\n\n\tif res.StatusCode != 200 {\n\t\treturn errors.New(\"Slack response status is not 2xx\")\n\t}\n\n\treturn nil\n}", "func (s *Slack) SendMessage(message string) error {\n\t_, _, err := s.client.PostMessage(s.channelID, slack.MsgOptionText(message, false))\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"client.PostMessage(): failed to post message\")\n\t}\n\n\treturn nil\n}", "func (s *SlackNotify) Send(v ...interface{}) error {\n\tif s.URL == \"\" {\n\t\treturn nil\n\t}\n\tpayload, err := json.Marshal(slackMsg{Text: fmt.Sprint(s.prefix, v)})\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, _ := http.NewRequest(\"POST\", s.URL, bytes.NewBuffer(payload))\n\treq.Header.Add(\"content-type\", \"application/json\")\n\tres, err := s.c.Do(req)\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Error posting to slack\")\n\t}\n\treturn nil\n}", "func (s *Client) SendMessage(text, channel string) error {\n\t_, _, respText, err := s.client.SendMessage(channel, slack.MsgOptionText(text, false))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"Slack Respsonse text: \", respText)\n\n\treturn nil\n}", "func (s *slackMessenger) Send(args ...interface{}) error {\n\tif 1 > len(args) {\n\t\treturn fault.InsufficientSlackSendParameter\n\t}\n\n\tmessage := args[0].(string)\n\ts.rtm.SendMessage(s.rtm.NewOutgoingMessage(message, s.channelID))\n\treturn nil\n}", "func (s *Slack) Send(pending []reviewit.MergeRequest) error {\n\ts.pending = pending\n\ts.build()\n\tbuf, err := json.Marshal(&s.msg)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failure to Marshal\")\n\t}\n\treq, _ := http.NewRequest(\"POST\", s.WebhookURL, bytes.NewReader(buf))\n\tif _, err := http.DefaultClient.Do(req); err != nil {\n\t\treturn errors.WithMessage(err, \"slack post message failed\")\n\t}\n\treturn nil\n}", "func (d *DingTalkClient) SendMessage(msg DingTalkMessage) error {\n\n\tvar message string\n\tswitch msg.Type {\n\tcase \"text\":\n\t\tmessage = fmt.Sprintf(`{\"msgtype\": \"text\",\"text\": {\"content\": \"监控报警: %s\"}}`, msg.Message)\n\tcase \"markdown\":\n\t\tmessage = fmt.Sprintf(`{\"msgtype\": \"markdown\",\"markdown\":{\"title\": 监控报警: \"%s\", \"text\": \"%s\"}}`, msg.Title, msg.Message)\n\tdefault:\n\t\tmessage = fmt.Sprintf(`{\"msgtype\": \"text\",\"text\": {\"content\": \"监控报警: %s\"}}`, msg.Message)\n\t}\n\n\tclient := &http.Client{}\n\trequest, _ := http.NewRequest(\"POST\", d.RobotURL, bytes.NewBuffer([]byte(message)))\n\trequest.Header.Set(\"Content-type\", \"application/json\")\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"访问钉钉URL(%s) 出错了: %s\", d.RobotURL, err)\n\t}\n\tif response.StatusCode != 200 {\n\t\tbody, _ := ioutil.ReadAll(response.Body)\n\t\treturn fmt.Errorf(\"访问钉钉URL(%s) 出错了: %s\", d.RobotURL, string(body))\n\t}\n\treturn nil\n}", "func SendSlack(temp string, data interface{}) error {\n\tmessageLock.Lock()\n\tbuf := new(bytes.Buffer)\n\tslackTemp, _ := template.New(\"slack\").Parse(temp)\n\tslackTemp.Execute(buf, data)\n\tslackMessages = append(slackMessages, buf.String())\n\tmessageLock.Unlock()\n\treturn nil\n}", "func sendEchoMessage(slackClient *slack.RTM, message, slackChannel string) {\n\tsplitMessage := strings.Fields(strings.ToLower(message))\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(strings.Join(splitMessage[1:], \" \"), slackChannel))\n}", "func send(username string, text string, ws *websocket.Conn) {\n\tm := Message{\n\t\tUsername: username,\n\t\tText: text,\n\t}\n\terr := websocket.JSON.Send(ws, m)\n\tif err != nil {\n\t\tfmt.Println(\"Could not send message: \", err.Error())\n\t}\n}", "func SendSlackWebhook(message string) {\n\twebhookURL := getWebhookURLFromEnvironmentVariable()\n\tif webhookURL == \"none\" {\n\t\treturn\n\t}\n\tslackBody, _ := json.Marshal(slackRequestBody{Text: message})\n\n\treq, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tif buf.String() != \"ok\" {\n\t\tfmt.Println(errors.New(\"Non-ok response returned from Slack\"))\n\t}\n}", "func (b *Bot) post(message map[string]interface{}, reply *domain.WorkReply, data *domain.Context, sub *subscription) error {\n\tmessage[\"text\"] = mainMessageFormatted()\n\tmessage[\"as_user\"] = true\n\tvar err error\n\t_, err = sub.s.Do(\"POST\", \"chat.postMessage\", message)\n\treturn err\n}", "func sendNotificationToSlack(payloadJSONEncoded []byte, response chan<- *http.Response) {\n\tfmt.Println(\"Sending notification to Slack...\")\n\n\t// Récupération des paramètres\n\t// ---------------------------\n\thookURL = config.SlackHookURL\n\thookPayload = config.SlackHookPayload\n\n\t// Envoi de la requête\n\t// -------------------\n\tresponse <- sendNotificationToApplication(hookURL, hookPayload, payloadJSONEncoded)\n}", "func (c *Client) Send(message *Message) error {\n\tif message == nil {\n\t\treturn xerrors.New(\"message is nil\")\n\t}\n\tvar b bytes.Buffer\n\tif err := json.NewEncoder(&b).Encode(message); err != nil {\n\t\treturn xerrors.Errorf(\"could not encode the message to JSON: %w\", err)\n\t}\n\thc := c.HTTPClient\n\tif hc == nil {\n\t\thc = http.DefaultClient\n\t}\n\tresp, err := hc.Post(c.WebhookURL, \"application/json\", &b)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"could not send the request: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode >= 300 {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn xerrors.Errorf(\"error from Slack API: %w\", &slackError{\n\t\t\tstatusCode: resp.StatusCode,\n\t\t\tbody: string(b),\n\t\t})\n\t}\n\treturn nil\n}", "func SendMessage(w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"unsupport body type\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif hub == nil {\n\t\thttp.Error(w, \"unknown error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thub.sendMessage(string(b))\n}", "func Send(config config.Config, text string) {\n\tapi := slack.New(config.Slack.Token)\n\tparams := slack.PostMessageParameters{}\n\tparams.IconEmoji = config.Slack.IconEmoji\n\tparams.Username = config.Slack.Username\n\tchannelID, timestamp, err := api.PostMessage(config.Slack.Channel, text, params)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\", err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Message successfully sent to channel %s at %s\", channelID, timestamp)\n}", "func (s *SlcLogger) sendNotification(logLevel logLevel, color string, message interface{}, titleParam []string) error {\n\n\tvar text string\n\tif t, ok := message.(error); ok {\n\t\ttext = t.Error()\n\t} else if t, ok := message.(string); ok {\n\t\ttext = t\n\t} else {\n\t\treturn &SlcErr{errors.New(\"the type of message parameter should be string or error\"), 0}\n\t}\n\n\tif logLevel < s.LogLevel {\n\t\treturn nil\n\t}\n\tslackChannel := s.getTargetChannel(logLevel)\n\n\tpayload, err := s.buildPayload(slackChannel, color, text, titleParam)\n\tif err != nil {\n\t\treturn &SlcErr{err, 0}\n\t}\n\n\treq, err := http.NewRequest(\"POST\", s.WebHookURL, bytes.NewBuffer(payload))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif err != nil {\n\t\treturn &SlcErr{err, 0}\n\t}\n\tctx := context.Background()\n\treq.WithContext(ctx)\n\n\tresp, err := http.DefaultClient.Do(req)\n\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\t_, _ = io.Copy(ioutil.Discard, resp.Body)\n\t\t\t_ = resp.Body.Close()\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\treturn &SlcErr{err, 0}\n\t}\n\n\tif resp.StatusCode >= 400 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn &SlcErr{errors.New(string(body)), resp.StatusCode}\n\t}\n\n\treturn nil\n}", "func sendVideoMessage(slackClient *slack.RTM, slackChannel string) {\n\tpostMessageParameters:= slack.PostMessageParameters{UnfurlMedia: true, UnfurlLinks: true}\n\tslackClient.PostMessage(slackChannel, slack.MsgOptionText(\"https://www.youtube.com/watch?v=Rh64GkNRDNU&ab_channel=MarySpender\", true), slack.MsgOptionPostMessageParameters(postMessageParameters))\n}", "func (b *Bot) SendMessage(message string) {\n\n\t// marshal request body\n\tbody, err := json.Marshal(types.NewMessage(b.ToChannel, message))\n\n\tif err != nil {\n\t\tlog.Printf(\"[%s] create send request body is failed: %s\", common.TimeNow(), err)\n\t\treturn\n\t}\n\n\t// new request\n\treq, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tb.PostMessageURL,\n\t\tbytes.NewBuffer(body),\n\t)\n\n\t// set request headers\n\treq.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", b.AuthorizationToken))\n\n\tlog.Printf(\"[%s] send request header: %s\\n\", common.TimeNow(), req.Header)\n\tlog.Printf(\"[%s] send request body: \\n%s\\n\", common.TimeNow(), common.FormatStringJoin(string(body)))\n\n\t// send message\n\tres, err := client.Do(req)\n\n\tif err != nil {\n\t\tlog.Printf(\"[%s] send request is failed [%s]\\n\", common.TimeNow(), err)\n\t\treturn\n\t}\n\n\tdefer res.Body.Close()\n\n\t// output request body\n\tbody, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] bad response body: %s\\n\", common.TimeNow(), err)\n\t\treturn\n\t}\n\n\tlog.Printf(\"[%s] response body: \\n%s\\n\", common.TimeNow(), common.FormatStringJoin(string(body)))\n\n}", "func (t *Telegram) SendMessage(text string) error {\n\tlog.Printf(\"Send to telegram chat %d: %s\", t.chatID, text)\n\tmessage := &Message{\n\t\tChatID: t.chatID,\n\t\tText: text,\n\t}\n\tdata, err := json.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// build request to telegram API\n\treq, err := t.buildRequest(data, SendMessageMethod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tlog.Fatal(string(body))\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func sendToVK(token string, message string, ID int64) {\n\t//VK Part\n\n\t//client, err := vkapi.NewClientFromLogin(\"<username>\", \"<password>\", vkapi.ScopeMessages)\n\tclient, err := vkapi.NewClientFromToken(token)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tclient.Log(true)\n\n\tif err := client.InitLongPoll(0, 2); err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t//Send one consoleMSG to chatID!\n\tclient.SendMessage(vkapi.NewMessage(vkapi.NewDstFromChatID(ID), message))\n}", "func sendMessage(w http.ResponseWriter, r *http.Request) {\n\t// Store the message\n\tvar message Message\n\t_ = json.NewDecoder(r.Body).Decode(&message)\n\tmessage.Username = getRandUsername()\n\tstoreMessage(message)\n\n\t// Broadcast the message\n\tbroadcast <- message\n\n\tvar msgs []Message\n\tmsgs = append(msgs, message)\n\tgetMessageResponse(w, msgs, nil)\n}", "func (messenger *Messenger) CallSendAPI(messageData interface{}) (*http.Response, error) {\n\turl := \"https://graph.facebook.com/v3.3/me/messages?access_token=\" + messenger.AccessToken\n\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tbody := new(bytes.Buffer)\n\tjson.NewEncoder(body).Encode(messageData)\n\n\treq, _ := http.NewRequest(\"POST\", url, body)\n\n\tfmt.Println(\"REQUEST [POST]: \" + url + \" params : \" + body.String())\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error request : \" + err.Error())\n\t\treturn resp, err\n\t}\n\n\tjson.NewEncoder(body).Encode(resp.Body)\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tfmt.Printf(\"Error http resp -> %v\\n\", resp)\n\t\tfmt.Println(\"Error http \" + strconv.Itoa(resp.StatusCode) + \" -> \" + body.String())\n\t}\n\n\treturn resp, err\n}", "func (b *Bslack) sendWebhook(msg config.Message) error {\n\t// Skip events.\n\tif msg.Event != \"\" {\n\t\treturn nil\n\t}\n\n\tif b.GetBool(useNickPrefixConfig) {\n\t\tmsg.Text = msg.Username + msg.Text\n\t}\n\n\tif msg.Extra != nil {\n\t\t// This sends a message only if we received a config.EVENT_FILE_FAILURE_SIZE.\n\t\tfor _, rmsg := range helper.HandleExtra(&msg, b.General) {\n\t\t\trmsg := rmsg // scopelint\n\t\t\ticonURL := config.GetIconURL(&rmsg, b.GetString(iconURLConfig))\n\t\t\tmatterMessage := matterhook.OMessage{\n\t\t\t\tIconURL: iconURL,\n\t\t\t\tChannel: msg.Channel,\n\t\t\t\tUserName: rmsg.Username,\n\t\t\t\tText: rmsg.Text,\n\t\t\t}\n\t\t\tif err := b.mh.Send(matterMessage); err != nil {\n\t\t\t\tb.Log.Errorf(\"Failed to send message: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\t// Webhook doesn't support file uploads, so we add the URL manually.\n\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\tfi, ok := f.(config.FileInfo)\n\t\t\tif !ok {\n\t\t\t\tb.Log.Errorf(\"Received a file with unexpected content: %#v\", f)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif fi.URL != \"\" {\n\t\t\t\tmsg.Text += \" \" + fi.URL\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have native slack_attachments add them.\n\tvar attachs []slack.Attachment\n\tfor _, attach := range msg.Extra[sSlackAttachment] {\n\t\tattachs = append(attachs, attach.([]slack.Attachment)...)\n\t}\n\n\ticonURL := config.GetIconURL(&msg, b.GetString(iconURLConfig))\n\tmatterMessage := matterhook.OMessage{\n\t\tIconURL: iconURL,\n\t\tAttachments: attachs,\n\t\tChannel: msg.Channel,\n\t\tUserName: msg.Username,\n\t\tText: msg.Text,\n\t}\n\tif msg.Avatar != \"\" {\n\t\tmatterMessage.IconURL = msg.Avatar\n\t}\n\tif err := b.mh.Send(matterMessage); err != nil {\n\t\tb.Log.Errorf(\"Failed to send message via webhook: %#v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Topic) Send(m *lobby.Message) error {\n\tcol := t.session.DB(\"\").C(colMessages)\n\n\tvar raw interface{}\n\n\tvalid, err := ValidateBytes(m.Value)\n\tif err == nil {\n\t\terr := json.Unmarshal(valid, &raw)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to unmarshal json\")\n\t\t}\n\t} else {\n\t\traw = m.Value\n\t}\n\n\terr = col.Insert(&message{Group: m.Group, Topic: t.name, Value: raw})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to insert of update\")\n\t}\n\n\treturn nil\n}", "func (s *instance) postMessage(jsondata []byte) {\r\n\tif s.client != nil {\r\n\t\tchannelID, timestamp, err := s.client.PostMessage(s.config.Channel, slack.MsgOptionText(string(jsondata), false), slack.MsgOptionUsername(\"g0-h0m3\"), slack.MsgOptionAsUser(true))\r\n\t\tif err == nil {\r\n\t\t\ts.service.Logger.LogInfo(s.name, fmt.Sprintf(\"message '%s' send (%s, %s)\", string(jsondata), channelID, timestamp))\r\n\t\t} else {\r\n\t\t\ts.service.Logger.LogError(s.name, fmt.Sprintf(\"message '%s' not send (%s, %s)\", string(jsondata), s.config.Channel, timestamp))\r\n\t\t\ts.service.Logger.LogError(s.name, err.Error())\r\n\t\t}\r\n\t} else {\r\n\t\ts.service.Logger.LogError(s.name, \"service not connected\")\r\n\t}\r\n}", "func SlackPost(username string, icon string, text string, hookurl string) (err error) {\n\tapiURL, err := url.ParseRequestURI(hookurl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tquery := url.Values{}\n\tapiURL.RawQuery = query.Encode()\n\tdata, _ := json.Marshal(map[string]string{\n\t\t\"text\": text,\n\t\t\"icon_emoji\": icon,\n\t\t\"username\": username,\n\t})\n\tclient := &http.Client{}\n\tr, err := http.NewRequest(\"POST\", hookurl, strings.NewReader(string(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\t_, err = client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func message(w http.ResponseWriter, r *http.Request) {\n\tvar rBody request\n\n\tif err := json.NewDecoder(r.Body).Decode(&rBody); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to decode message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := models.GetConnectionWithRecipients(rBody.ConnectionID)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to get connection\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdbMsg := &models.Message{\n\t\tConnectionID: rBody.ConnectionID,\n\t\tMessage: rBody.Text,\n\t\tSourceUser: *c.SourceUser,\n\t\tSourceUserID: c.SourceUserID,\n\t\tDestinationUserID: c.DestinationUserID,\n\t\tChannel: rBody.Channel,\n\t}\n\n\tif err := dbMsg.Save(); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to save message. \", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcMsg := models.ChannelMessage{\n\t\tID: int(dbMsg.ID),\n\t\tCreatedAt: dbMsg.CreatedAt,\n\t\tMessage: dbMsg.Message,\n\t\tReadBy: dbMsg.ReadBy,\n\t\tUser: rBody.User,\n\t}\n\n\tpayload := pubMessage{\n\t\t// populate embedded struct (promoted fields)\n\t\tdefaultProperties: defaultProperties{\n\t\t\tChannel: rBody.Channel,\n\t\t\tType: rBody.Type,\n\t\t\tSubType: rBody.SubType,\n\t\t},\n\t\tChannelMessage: cMsg,\n\t}\n\n\t// prep for ws\n\tbytes, err := json.Marshal(payload)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to marshal chat message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpubMessage := hub.PublishMessage{\n\t\tTopic: rBody.Channel,\n\t\tPayload: bytes,\n\t}\n\n\tbroker.Hub.Publish(pubMessage)\n\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func SendSlackNotification(webhookURL string, msg data.SlackRequestBody) error {\n\n\tslackBody, _ := json.Marshal(msg)\n\n\tlog.Printf(\"Sending message to Slack:\\n %v\\n\", string(slackBody))\n\n\treq, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tif buf.String() != \"ok\" {\n\t\treturn errors.New(\"Non-ok response returned from Slack\")\n\t}\n\treturn nil\n}", "func (bot *Bot) SendMessage(chatID int64, message string) {\n\tlog.Printf(\"Send '%s' to %d chat id\\n\", message, chatID)\n\tmsg := tgbotapi.NewMessage(chatID, message)\n\tmsg.ParseMode = bot.MessageParseMode\n\t_, err := bot.API.Send(msg)\n\tif err != nil {\n\t\tlog.Panicf(\"Send Messsage Error: %v\\n\", err)\n\t}\n}", "func (t *Telegram) SendMessage(message string) error {\n\tu := t.formatURL(\"%s/bot%s/sendMessage\")\n\tcontentType := \"application/x-www-form-urlencoded\"\n\tvalues := url.Values{}\n\tvalues.Add(\"chat_id\", t.chatID)\n\tvalues.Add(\"text\", message)\n\treader := strings.NewReader(values.Encode())\n\t_, err := http.Post(u, contentType, reader)\n\treturn err\n}", "func (t *Tracker) send(color, message string) error {\n\tenv := os.Getenv(\"ENV\")\n\t// If no ENV is specified, assume we are in development mode, so we don't want to flood Slack uselessly.\n\tif env == \"\" {\n\t\treturn nil\n\t}\n\n\t_, perr := poster.Post(\n\t\tt.WebHook,\n\t\tmap[string]interface{}{\n\t\t\t\"text\" : fmt.Sprintf(\"%s - %s\", t.Application, env),\n\t\t\t\"attachments\": []map[string]interface{}{\n\t\t\t\t{\n\t\t\t\t\t\"color\": color,\n\t\t\t\t\t\"text\": fmt.Sprintf(\n\t\t\t\t\t\t\"*Message*\\n%s\\n\\n*Stack*\\n```%s```\\n\\n*Time*\\n%s\",\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tstring(debug.Stack()),\n\t\t\t\t\t\ttime.Now().Format(\"2006-01-02 03:04:05\"),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\n\t// An unexpected error happened when sending our message to Slack.\n\treturn perr\n}", "func (c *Client) send(ctx context.Context, session string, content Content) error {\n\t_dt := c.Now\n\tif _dt == nil {\n\t\t_dt = dt.Now\n\t}\n\t_m := newMsg(session, content, _dt)\n\tm := newJSONMsg(_m)\n\tb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody := bytes.NewReader(b)\n\tu := c.url(\"/rex/v0/messages\")\n\tresp, err := c.http().Post(u, \"application/json\", body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn fmt.Errorf(\"%v %s %s: %s\", resp.Status, \"POST\", u, b)\n\t}\n\treturn nil\n}", "func (w *Webhook) SendMessage(Content []byte) error {\n\treq, resp := BuildRequest(\"POST\", w.webhookURL, Content)\n\treq.Header.SetContentType(\"application/json\")\n\tif err := fasthttp.Do(req, resp); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) postMessage(ctx context.Context, username, iconurl, channel, text string) error {\n\tif iconurl != \"\" {\n\t\ticonurl = \"icon_url=\" + iconurl\n\t}\n\tvar resp ResponseHeader\n\treturn rpc(ctx, c, &resp, \"chat.postMessage\",\n\t\t\"username=\"+username,\n\t\ticonurl,\n\t\t\"as_user=false\",\n\t\t\"channel=\"+channel,\n\t\t\"text=\"+text)\n}", "func (c *ChanPost) slckSend(rtm *slack.RTM) {\n\tlog.Println(\"Message from bot received\")\n\tmessage := \"Infra Announce: \" + c.text + \" \" +\n\t\ttime.Unix(int64(c.date), 0).Format(\"Mon Jan _2 15:04\") +\n\t\t\"(from telegram channel)\"\n\trtm.SendMessage(rtm.NewOutgoingMessage(message, config.sChat))\n}", "func (mm mattermostMessage) sendMessage() {\n\tpost := &model.Post{}\n\tpost.ChannelId = mm.Event.Broadcast.ChannelId\n\t// Create file if message is too large\n\tif len(mm.Response) >= 3990 {\n\t\tres, resp := client.UploadFileAsRequestBody([]byte(mm.Response), mm.Event.Broadcast.ChannelId, mm.Request)\n\t\tif resp.Error != nil {\n\t\t\tlogging.Logger.Error(\"Error occured while uploading file. Error: \", resp.Error)\n\t\t}\n\t\tpost.FileIds = []string{string(res.FileInfos[0].Id)}\n\t} else if len(mm.Response) == 0 {\n\t\tlogging.Logger.Info(\"Invalid request. Dumping the response\")\n\t\treturn\n\t} else {\n\t\tpost.Message = \"```\\n\" + mm.Response + \"\\n```\"\n\t}\n\n\t// Create a post in the Channel\n\tif _, resp := client.CreatePost(post); resp.Error != nil {\n\t\tlogging.Logger.Error(\"Failed to send message. Error: \", resp.Error)\n\t}\n}", "func sendHelp(slackClient *slack.RTM, slackChannel string) {\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(helpMessage, slackChannel))\n}", "func sendHelp(slackClient *slack.RTM, slackChannel string) {\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(helpMessage, slackChannel))\n}", "func (client *Client) SendMessage(channel, text string) error {\n\tmsg := struct {\n\t\tID int `json:\"id\"`\n\t\tType string `json:\"type\"`\n\t\tChannel string `json:\"channel\"`\n\t\tText string `json:\"text\"`\n\t}{client.messageID, \"message\", channel, text}\n\n\tif err := client.conn.WriteJSON(msg); err != nil {\n\t\treturn err\n\t}\n\n\tclient.messageID++\n\n\treturn nil\n}", "func (s WeworkSender) SendRobotMsg(key, tp, content string) error {\n\tvar msg = &RobotMsg{\n\t\tMsgType: tp,\n\t}\n\tswitch tp {\n\tcase \"text\":\n\t\tmsg.Text = &MsgText{Content: content}\n\tcase \"markdown\":\n\t\tmsg.MarkDown = &MsgMarkdown{Content: content}\n\t}\n\t_, err := grequests.Post(s.BaseURL+key, &grequests.RequestOptions{\n\t\tJSON: msg,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"wechat work send robot message api error: %w\", err)\n\t}\n\treturn nil\n}", "func SendMessage(version, build string) error {\n\texpanded, err := homedir.Expand(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := os.Stat(expanded); os.IsNotExist(err) {\n\t\treturn errgo.Mask(ErrNotConfigured, errgo.Any)\n\t}\n\n\tslackConfiguration := SlackConfiguration{\n\t\tNotificationUsername: \"KochoBot\",\n\t\tEmojiIcon: \":robot_face:\",\n\t}\n\n\tconfigFile, err := os.Open(expanded)\n\tif err != nil {\n\t\treturn errgo.WithCausef(err, ErrInvalidConfiguration, \"couldn't open Slack configuration file\")\n\t}\n\tdefer configFile.Close()\n\n\tif err := json.NewDecoder(configFile).Decode(&slackConfiguration); err != nil {\n\t\treturn errgo.WithCausef(err, ErrInvalidConfiguration, \"couldn't decode Slack configuration\")\n\t}\n\n\tclient := slack.New(slackConfiguration.Token)\n\n\tparams := slack.PostMessageParameters{}\n\tparams.Attachments = []slack.Attachment{\n\t\tslack.Attachment{\n\t\t\tColor: \"#2484BE\",\n\t\t\tText: fmt.Sprintf(\"*Kocho*: %s ran `%s`\", slackConfiguration.Username, strings.Join(os.Args, \" \")),\n\t\t\tFields: []slack.AttachmentField{\n\t\t\t\tslack.AttachmentField{\n\t\t\t\t\tTitle: \"Kocho Version\",\n\t\t\t\t\tValue: version,\n\t\t\t\t\tShort: true,\n\t\t\t\t},\n\t\t\t\tslack.AttachmentField{\n\t\t\t\t\tTitle: \"Kocho Build\",\n\t\t\t\t\tValue: build,\n\t\t\t\t\tShort: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\tMarkdownIn: []string{\"text\"},\n\t\t},\n\t}\n\tparams.Username = slackConfiguration.NotificationUsername\n\tparams.IconEmoji = slackConfiguration.EmojiIcon\n\n\tif _, _, err := client.PostMessage(slackConfiguration.NotificationChannel, \"\", params); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func sendMessage(message string) {\n\ts, _ := session.GetSession()\n\tif s != nil {\n\t\tconn := s.OpenConnection(chatServiceId)\n\t\tio.WriteString(conn, message)\n\t\tconn.Close()\n\t} else {\n\t\tfmt.Println(\"No chat sessions available\")\n\t}\n}", "func (t *Typetalk) ChatPostMessage(ctx context.Context, message string) (*typetalk.PostedMessageResult, *typetalkShared.Response, error) {\n\treturn t.Client.Messages.PostMessage(ctx, t.TopicID, message, nil)\n}", "func (s SlackReporter) Post(ctx context.Context, msg string) (string, error) {\n\t_, ts, err := s.api.PostMessageContext(ctx, s.channel, slack.MsgOptionText(msg, false))\n\treturn ts, err\n}", "func send(g *gocui.Gui, v *gocui.View) error {\n\tmsg := chatmessage.Chatmessage{\n\t\tText: v.Buffer(),\n\t\tFrom: nickname,\n\t}\n\n\t// Get the top window view and write the buffer of the bottom window view to it\n\tif m, err := g.View(\"messages\"); err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tif len(msg.Text) != 0 {\n\t\t\tm.Write([]byte(\" \" + msg.From + \": \" + msg.Text))\n\t\t}\n\t}\n\n\t// Clear the bottom window and reset the cursor\n\tv.Clear()\n\tif err := v.SetCursor(0, 0); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Send message to other clients\n\n\treturn nil\n}", "func SendSlackNotification(title string, cobraCmd *cobra.Command, output string, mgr credential.Manager) error {\n\tuserID, err := mgr.GetUserIDByParseToken()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while parsinng oauth2 token\")\n\t}\n\n\tslackhookUrl := GlobalOpts.SlackAPIURL()\n\ttext_msg := \"New \" + title + \" is triggerred on \" + getClusterType() + \" by \" + userID\n\ttriggeredCmd := revertUpgradeOpts(title, cobraCmd)\n\tattachment := Attachment{\n\t\tColor: SLACK_COLOR,\n\t\tText: triggeredCmd + \"\\n\" + output,\n\t}\n\n\tslackBody, _ := json.Marshal(SlackRequestBody{Text: text_msg, Icon_emoji: ICON_EMOJI, Username: SLACK_USER_NAME,\n\t\tAttachments: []Attachment{attachment}})\n\treq, err := http.NewRequest(http.MethodPost, slackhookUrl, bytes.NewBuffer(slackBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Drain response body and close, return error to context if there isn't any.\n\tdefer func() {\n\t\tderr := drainResponseBody(resp.Body)\n\t\tif err == nil {\n\t\t\terr = derr\n\t\t}\n\t\tcerr := resp.Body.Close()\n\t\tif err == nil {\n\t\t\terr = cerr\n\t\t}\n\t}()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"calling %s returned %s status\", slackhookUrl, resp.Status)\n\t}\n\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while decoding slack response body\")\n\t}\n\tbodyString := string(bodyBytes)\n\tif bodyString != \"ok\" {\n\t\treturn fmt.Errorf(\"non-ok response returned from Slack\")\n\t}\n\treturn nil\n}", "func (t *FakeSlackChat) postMessage(msg Message) error {\n\treturn nil\n}", "func (c *ClientType) sendToLoggly(msg messageType) error {\n\n\t// Marshal message object to JSON\n\tmsgBytes, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn errors.New(\"Could not create JSON payload\")\n\t}\n\n\t// Construct the HTTP request with timeout\n\thttpClient := &http.Client{\n\t\tTimeout: 7 * time.Second}\n\trequest, err := http.NewRequest(http.MethodPost, c.URL, bytes.NewBuffer(msgBytes))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the header attributes\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\n\t_, err = httpClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) SendMessage(msg Message) error {\n\t// convert Message to JSON bytes\n\tmsgJSON, err := makeJSONMassage(msg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fail to make json bytes\")\n\t}\n\n\t// create new Request with given params\n\treq, err := http.NewRequest(\"POST\", c.WebhookURL.String(), bytes.NewBuffer(msgJSON))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fail to create new request\")\n\t}\n\n\t// add necessary headers\n\tfor k, v := range c.Header {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tlog.Printf(\"send request\")\n\t// send http request\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"error after send request\")\n\t\treturn errors.Wrap(err, \"fail to send request\")\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Printf(\"check status code\")\n\t// check status code\n\tif res.StatusCode != 200 {\n\t\tt, _ := ioutil.ReadAll(res.Body)\n\t\treturn fmt.Errorf(\"http request failed: status: %s: url=%s, body=%s\", res.Status, c.WebhookURL.String(), string(t))\n\t}\n\treturn nil\n}", "func (s *Slack) Message(msg string, v ...interface{}) error {\n\treturn s.Send(\"\", msg, v...)\n}", "func (dc *channel) Send(message notification.Message) error {\n\tclient := resty.New()\n\t_, err := client.R().\n\t\tSetHeader(\"Content-Type\", \"application/json\").\n\t\tSetBody(map[string]string{\"content\": message.Body}).\n\t\tPost(dc.Webhook)\n\treturn err\n}", "func (b *Bot) SendMessage(chatID int64, text string) (Message, error) {\n\n\turl := fmt.Sprintf(\"https://api.telegram.org/bot%s/sendMessage?chat_id=%d&text=%s\", b.Token, chatID, text)\n\n\tresp, err := getContent(url)\n\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\n\tvar m Message\n\terr = json.Unmarshal(resp, &m)\n\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\n\treturn m, nil\n\n}", "func (bot *BotAPI) SendMessage(chatID int64, chatType string, message interface{}) (Message, error) {\n\treturn bot.Send(NewMessage(chatID, chatType, message))\n}", "func SendMessage(message string) {\n\tif message == \"\" {\n\t\tfmt.Println(\"Message cannot be empty\")\n\t\tos.Exit(1)\n\t}\n\n\ttype Status struct {\n\t\tSuccess bool\n\t\tMessage interface{}\n\t}\n\n\ttype Result struct {\n\t\tNewMessageID string `json:\"new_message_id\"`\n\t}\n\ttype Response struct {\n\t\tStatus Status `json:\"status\"`\n\t\tResult interface{}\n\t}\n\n\tbaseURL, err := url.Parse(apiURL)\n\n\tif err != nil {\n\t\tfmt.Println(\"Malformed URL: \", err.Error())\n\t\treturn\n\t}\n\n\troomID := viper.GetString(\"roomID\")\n\tparams := url.Values{}\n\tparams.Add(\"room_id\", roomID)\n\n\tbaseURL.RawQuery = params.Encode()\n\n\tvar replacedString = strings.ReplaceAll(message, \"\\\\n\", \"\\n\")\n\t// re := regexp.MustCompile(`\\r?\\n`)\n\t// replacedString := re.ReplaceAllString(message, `\\n`)\n\t// fmt.Printf(\"fd;fhkhfkhf %v\", replacedString)\n\tjsonValues, err := json.Marshal(map[string]string{\n\t\t\"text\": replacedString,\n\t\t\"_t\": viper.GetString(\"token\"),\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tformData := url.Values{\n\t\t\"pdata\": {string(jsonValues)},\n\t}\n\n\treq, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tbaseURL.String(),\n\t\tstrings.NewReader(formData.Encode()),\n\t)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8\")\n\treq.Header.Add(\"cookie\", fmt.Sprintf(\"%v=%v\", cookieName, viper.GetString(\"cookie\")))\n\n\tresponse, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error making send-message request, %v\\n\", err)\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error parsing response %v\\n\", err)\n\t\treturn\n\t}\n\n\tvar parsedBody Response\n\terr = json.Unmarshal(body, &parsedBody)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error parsing response\", err)\n\t}\n\n\tif parsedBody.Status.Success != true {\n\t\tvar errMsg string\n\t\tswitch v := parsedBody.Status.Message.(type) {\n\t\tcase string:\n\t\t\terrMsg = v\n\t\tcase []interface{}:\n\t\t\t// for _, val := range v {\n\t\t\t// \tfmt.Println(val)\n\t\t\t// }\n\t\t\terrMsg = v[0].(string)\n\t\t}\n\t\tfmt.Printf(\"❌ Send report failed: %v\\n\", errMsg)\n\n\t} else {\n\t\tfmt.Println(\"✅ Send report successfully\")\n\t}\n\t// fmt.Printf(\"%s\\n\", string(body))\n\n}", "func (d *Dao) SendWechatToGroup(c context.Context, chatid, msg string) (err error) {\n\tvar (\n\t\tnum int\n\t\treq *http.Request\n\t\tb = &bytes.Buffer{}\n\t\turl = _sagaWechatURL + \"/appchat/send\"\n\t\tbody = &ut.WechatGroupMsg{\n\t\t\tChatID: chatid,\n\t\t\tMsgType: \"text\",\n\t\t\tSafe: 0,\n\t\t}\n\t)\n\tmsgBlock := strings.Split(msg, \"\\n\")\n\tif len(msgBlock)%40 == 0 {\n\t\tnum = len(msgBlock)/40 - 1\n\t} else {\n\t\tnum = len(msgBlock) / 40\n\t}\n\tfor i := 0; i <= num; i++ {\n\t\tvar (\n\t\t\tres struct {\n\t\t\t\tCode int `json:\"code\"`\n\t\t\t\tMessage string `json:\"message\"`\n\t\t\t}\n\t\t)\n\t\tstart, end := 40*i, 40*(i+1)\n\t\tif end > len(msgBlock) {\n\t\t\tend = len(msgBlock)\n\t\t}\n\t\tbody.Text = &ut.TextContent{\n\t\t\tContent: strings.Join(msgBlock[start:end], \"\\n\") + fmt.Sprintf(\"\\n(%d/%d)\", i+1, num+1),\n\t\t}\n\t\tif err = json.NewEncoder(b).Encode(body); err != nil {\n\t\t\tlog.Error(\"apmSvc.SendWechatToGroup Error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tif req, err = http.NewRequest(http.MethodPost, url, b); err != nil {\n\t\t\tlog.Error(\"apmSvc.SendWechatToGroup Error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tif err = d.client.Do(c, req, &res); err != nil {\n\t\t\tlog.Error(\"apmSvc.SendWechatToGroup Error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t\tif res.Code != 0 {\n\t\t\terr = fmt.Errorf(\"Http response Code(%v)!=0\", res.Code)\n\t\t\tlog.Error(\"apmSvc.SendWechatToGroup Error(%v)\", err)\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func PostMessage(channel, username, text string) (res *http.Response, err error) {\n\tm := Message{\n\t\tChannel: channel,\n\t\tUsername: username,\n\t\tText: text,\n\t}\n\tb, _ := json.Marshal(m)\n\n\treq, err := http.NewRequest(\"POST\", apiURL, bytes.NewBuffer(b))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\tres, err = client.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\treturn\n}", "func (chat ChatMsg) SendChatMsg(data string) {\n\n\tif strings.HasPrefix(data, \"L \") {\n\t\ttmp1 := strings.TrimLeft(data, \"L \")\n\n\t\tchatting.Msg += \"Me: \" + tmp1 + \"\\n\"\n\t\tqml.Changed(chatting, &chatting.Msg)\n\n\t} else if strings.HasPrefix(data, \"G \") {\n\t\ttmp2 := strings.TrimLeft(data, \"G \")\n\n\t\tglobalchatting.Msg += \"Me: \" + tmp2 + \"\\n\"\n\t\tqml.Changed(globalchatting, &globalchatting.Msg)\n\t}\n\n\tmessenger.Msnger.Send_message(data, mylib.CHAT_MESSAGE)\n}", "func (api *API) SendTextMessage(mes *TextMessage) error {\n\tfields := map[string]string{\n\t\t\"chat_id\": strconv.Itoa(int(mes.ChatID)),\n\t\t\"text\": mes.Text,\n\t\t\"parse_mode\": \"MarkdownV2\",\n\t}\n\n\treturn api.sendMessage(fields, methodSendMessage)\n}", "func (c *Connection) SendMessage(r *dto.Response) {\n\n\tbody, err := json.Marshal(r)\n\tif err != nil {\n\n\t}\n\n\tc.Inner.WriteMessage(websocket.TextMessage, body)\n}", "func SendMessage(writer http.ResponseWriter, req *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(req.Body, 1048576))\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := req.Body.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Decode the passed body into the struct.\n\tvar message MessageStruct\n\tif err := json.Unmarshal(body, &message); err != nil {\n\t\tsendUnprocessableEntity(writer, err)\n\t\treturn\n\t}\n\n\tprotocol := strings.ToLower(message.Protocol)\n\n\tif protocol == \"http\" {\n\t\t// Send HTTP message\n\t\tvar httpMsg gcm.HttpMessage\n\t\tif err := json.Unmarshal(message.Message, &httpMsg); err != nil {\n\t\t\tlog.Println(\"Message Unmarshal error: %+v\", err)\n\t\t\tsendUnprocessableEntity(writer, err)\n\t\t\treturn\n\t\t}\n\n\t\tres, sendErr := gcm.SendHttp(apiKey, httpMsg)\n\t\tif sendErr != nil {\n\t\t\tSendMessageSendError(writer, sendErr)\n\t\t} else {\n\t\t\tSendOkResponse(writer, res)\n\t\t}\n\t} else if protocol == \"xmpp\" {\n\t\t// Send XMPP message\n\t\tvar xmppMsg gcm.XmppMessage\n\t\tif err := json.Unmarshal(message.Message, &xmppMsg); err != nil {\n\t\t\tlog.Println(\"Message Unmarshal error: %+v\", err)\n\t\t\tsendUnprocessableEntity(writer, err)\n\t\t\treturn\n\t\t}\n\n\t\tres, _, sendErr := gcm.SendXmpp(senderId, apiKey, xmppMsg)\n\t\tif sendErr != nil {\n\t\t\tSendMessageSendError(writer, sendErr)\n\t\t} else {\n\t\t\tSendOkResponse(writer, res)\n\t\t}\n\t} else {\n\t\t// Error\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\tsendJSON(writer, &HttpError{\"protocol should be HTTP or XMPP only.\"})\n\t}\n}", "func (c *DingTalk) Send(message nuntius.Message) error {\n\tpayload := &DingTalkPayload{}\n\tpayload.Msgtype = c.MsgType\n\tpayload.Text.Content = message.Text\n\tpayload.Markdown.Title = c.Title\n\tpayload.Markdown.Text = message.Text\n\tpayload.At.AtMobiles = c.AtMobiles\n\tpayload.At.IsAtAll = c.IsAtAll\n\n\tdata, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest, err := http.NewRequest(\"POST\", c.URL+\"?access_token=\"+c.Token, bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\trequest.Header.Set(\"User-Agent\", \"Nuntius\")\n\n\tresponse, err := dingtalkHTTPClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\tvar body []byte\n\tresponse.Body.Read(body)\n\tif response.StatusCode == http.StatusOK && err == nil {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Failed sending message. statusCode: %d\", response.StatusCode)\n}", "func SendMessage(botToken string, chatId string, text string) (*Message, error) {\n\tbody := &SendMessageRequestBody{\n\t\tChatID: chatId,\n\t\tText: text,\n\t}\n\tb, err := json.Marshal(&body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse, err := http.Post(\"https://api.telegram.org/\"+botToken+\"/sendMessage\", \"application/json\", bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif response.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(\"sendMessage request returned: \" + response.Status)\n\t}\n\tvar result *ResponseBody\n\tif err := json.NewDecoder(response.Body).Decode(&result); err != nil {\n\t\treturn nil, errors.New(\"could not convert response to *ResponseBody\")\n\t}\n\treturn result.Result, nil\n}", "func (p *Payload) SendMessage() error {\n\n\twebHookURL := p.NewClientURL()\n\tmessage, err := p.NewMessage()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//TODO: Add option for cert bundle\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tres, err := client.Post(webHookURL, \"application/json\", message)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\t_, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *Hipchat) send(client HipchatClient, color, format, message string, notify bool) error {\n\treq := hipchat.MessageRequest{\n\t\tRoomId: h.Room,\n\t\tFrom: \"Drone\",\n\t\tMessage: message,\n\t\tColor: color,\n\t\tMessageFormat: format,\n\t\tNotify: notify,\n\t}\n\n\treturn client.PostMessage(req)\n}", "func sendText(msg string, s *discordgo.Session, m *discordgo.MessageCreate) {\n\t_, _ = s.ChannelMessageSend(m.ChannelID, msg)\n\tfmt.Printf(\"Sending %q\\n\", msg)\n}", "func (_m *SlackRTMInterface) SendMessage(msg *slack.OutgoingMessage) {\n\t_m.Called(msg)\n}", "func sendChannelMessage(api *slack.Client, channel string, message models.Message) error {\n\treturn sendMessage(api, message.IsEphemeral, channel, message.Vars[\"_user.id\"], message.Output, message.ThreadTimestamp, message.Attributes[\"ws_token\"], message.Remotes.Slack.Attachments)\n}", "func sendShareChatMessage(openID, tenantKey, appID, shareChatID string) error {\n\tuser := &protocol.UserInfo{\n\t\tID: openID,\n\t\tType: protocol.UserTypeOpenID,\n\t}\n\n\tctx := context.TODO()\n\n\t//send group shared card(last param means group chat id, and this message will be sent to this user by openid)\n\t_, err := message.SendShareChatMessage(ctx, tenantKey, appID, user, \"\", shareChatID)\n\tif err != nil {\n\t\tcommon.Logger(ctx).Errorf(\"send group card failed[%v]\", err)\n\t\treturn fmt.Errorf(\"send group card failed[%v]\", err)\n\t}\n\treturn nil\n}", "func sendTextToTelegramChat(chatId int, text string) (string, error) {\n\n\tlog.Printf(\"Sending %s to chat_id: %d\", text, chatId)\n\tresponse, err := http.PostForm(\n\t\ttelegramApi,\n\t\turl.Values{\n\t\t\t\"chat_id\": {strconv.Itoa(chatId)},\n\t\t\t\"text\": {text},\n\t\t})\n\n\tif err != nil {\n\t\tlog.Printf(\"error when posting text to the chat: %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\n\tvar bodyBytes, errRead = ioutil.ReadAll(response.Body)\n\tif errRead != nil {\n\t\tlog.Printf(\"error in parsing telegram answer %s\", errRead.Error())\n\t\treturn \"\", err\n\t}\n\tbodyString := string(bodyBytes)\n\tlog.Printf(\"Body of Telegram Response: %s\", bodyString)\n\n\treturn bodyString, nil\n}", "func echoMessage(slackClient *slack.RTM, message, slackChannel string) {\n\tsplitMessage := strings.Fields(strings.ToLower(message))\n\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(strings.Join(splitMessage[1:], \" \"), slackChannel))\n}", "func (s *Service) SendMessage(TargetChannelID, messageToSend string) error {\n\t_, err := s.discordapi.ChannelMessageSend(TargetChannelID, messageToSend)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error sending message to channel %v\", err)\n\t}\n\treturn nil\n}", "func SendMessage(to tb.Recipient, b *tb.Bot, d interface{}) (*tb.Message, error) {\n\tmessage, err := b.Send(to, d, tb.Silent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogrus.Infof(\"Send message %v\", message.ID, message.Text)\n\treturn message, nil\n}", "func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}", "func (b *Bot) SendMessage(v interface{}) error {\n\tmsg := toString(v)\n\turl := fmt.Sprintf(sendMsgURL, b.token, b.chatID, msg)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode == http.StatusBadRequest {\n\t\tbodyStr := string(body)\n\t\terrData := &BotError{}\n\n\t\terr = json.Unmarshal([]byte(bodyStr), &errData)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors.New(errData.Description)\n\t}\n\treturn nil\n}", "func (sn *SlackMessage) Notify(slackURL string) error {\n\tbp, err := json.Marshal(sn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = http.Post(slackURL, \"application/json\", bytes.NewBuffer(bp))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SendXrayMessage(w http.ResponseWriter, r *http.Request) {\n\t// params := mux.Vars(r)\n\tvar xrayMessage XrayMessage\n\terr := json.NewDecoder(r.Body).Decode(&xrayMessage)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif len(xrayMessage.PolicyName) == 0 {\n\t\tlog.Error(\"Could not parse post body\")\n\t}\n\n\tkeys, ok := r.URL.Query()[\"key\"]\n\n\tif !ok || len(keys[0]) < 1 {\n\t\tlog.Error(\"Url Param 'key' is missing\")\n\t\treturn\n\t}\n\n\tif len(xrayMessage.Issues) < 1 {\n\t\tlog.Debug(\"There are no Issues so not sending a message\")\n\t\treturn\n\t}\n\n\twebHookUrl := fmt.Sprintf(\"https://outlook.office.com/webhook/%s\", keys[0])\n\tteamsMessage := TransformXrayMessage(&xrayMessage)\n\n\trequestByte, _ := json.Marshal(teamsMessage)\n\trequestReader := bytes.NewReader(requestByte)\n\tlog.Printf(\"Sending Post to %s\\n\", webHookUrl)\n\tres, err := http.Post(webHookUrl, \"application/json\", requestReader)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trb, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tlog.Infof(\"Microsoft Teams response text: %s\", string(rb))\n\tif res.StatusCode != http.StatusOK {\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed reading Teams http response: %v\", err)\n\t\t\t// fmt.Errorf(\"Failed reading Teams http response: %v\", err)\n\t\t}\n\t\t// fmt.Errorf(\"Failed sending to the Teams Channel. Teams http response: %s\",\n\t\tlog.Errorf(\"Failed sending to the Teams Channel. Teams http response: %s\",\n\t\t\tres.Status)\n\t}\n\tif err := res.Body.Close(); err != nil {\n\t\tlog.Error(err)\n\t}\n\tfmt.Fprintf(w, string(rb))\n\tres.Body.Close()\n}", "func (user *User) sendMessage(m Message) {\n\tmsg, _ := json.Marshal(m)\n\n\tif err := user.conn.WriteMessage(1, msg); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (d *Discord) SendMessage(channel, message string) error {\n\tif channel == \"\" {\n\t\tlog.Println(\"Empty channel could not send message\", message)\n\t\treturn nil\n\t}\n\n\tif _, err := d.Session.ChannelMessageSend(channel, message); err != nil {\n\t\tlog.Println(\"Error sending discord message: \", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}", "func SendMsg(message string) {\n\tbotMutex.Lock()\n\tdefer botMutex.Unlock()\n\tif !messageReceived {\n\t\tlog.Println(\n\t\t\t\"Write a message to the bot for specifying notifiable chat ID\",\n\t\t)\n\t\treturn\n\t}\n\tmsg := tgbotapi.NewMessage(notifiableChatID, message)\n\t_, err := bot.Send(msg)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (adapter *Adapter) SendMessage(ctx context.Context, output sarah.Output) {\n\tvar message *webapi.PostMessage\n\tswitch content := output.Content().(type) {\n\tcase *webapi.PostMessage:\n\t\tmessage = content\n\n\tcase string:\n\t\tchannel, ok := output.Destination().(event.ChannelID)\n\t\tif !ok {\n\t\t\tlogger.Errorf(\"Destination is not instance of Channel. %#v.\", output.Destination())\n\t\t\treturn\n\t\t}\n\t\tmessage = webapi.NewPostMessage(channel, content)\n\n\tcase *sarah.CommandHelps:\n\t\tchannelID, ok := output.Destination().(event.ChannelID)\n\t\tif !ok {\n\t\t\tlogger.Errorf(\"Destination is not instance of Channel. %#v.\", output.Destination())\n\t\t\treturn\n\t\t}\n\n\t\tvar fields []*webapi.AttachmentField\n\t\tfor _, commandHelp := range *output.Content().(*sarah.CommandHelps) {\n\t\t\tfields = append(fields, &webapi.AttachmentField{\n\t\t\t\tTitle: commandHelp.Identifier,\n\t\t\t\tValue: commandHelp.Instruction,\n\t\t\t\tShort: false,\n\t\t\t})\n\t\t}\n\t\tattachments := []*webapi.MessageAttachment{\n\t\t\t{\n\t\t\t\tFallback: \"Here are some input instructions.\",\n\t\t\t\tPretext: \"Help:\",\n\t\t\t\tTitle: \"\",\n\t\t\t\tFields: fields,\n\t\t\t},\n\t\t}\n\t\tmessage = webapi.NewPostMessage(channelID, \"\").WithAttachments(attachments)\n\n\tdefault:\n\t\tlogger.Warnf(\"Unexpected output %#v\", output)\n\t\treturn\n\t}\n\n\tresp, err := adapter.client.PostMessage(ctx, message)\n\tif err != nil {\n\t\tlogger.Errorf(\"Something went wrong with Web API posting: %+v. %+v\", err, message)\n\t\treturn\n\t}\n\n\tif !resp.OK {\n\t\tlogger.Errorf(\"Failed to post message %#v: %s\", message, resp.Error)\n\t}\n}", "func (w *WebHook) SendTextMsg(content string, isAtAll bool, mobiles ...string) error {\n\t// send request\n\treturn w.sendPayload(&PayLoad{\n\t\tMsgType: \"text\",\n\t\tText: struct {\n\t\t\tContent string `json:\"content\"`\n\t\t}{\n\t\t\tContent: content,\n\t\t},\n\t\tAt: struct {\n\t\t\tAtMobiles []string `json:\"atMobiles\"`\n\t\t\tIsAtAll bool `json:\"isAtAll\"`\n\t\t}{\n\t\t\tAtMobiles: mobiles,\n\t\t\tIsAtAll: isAtAll,\n\t\t},\n\t})\n}", "func (d *handler) SendMessage(msg *pb.Event) error {\n\terr := d.ChatStream.Send(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error Sending message through ChatStream: %s\", err)\n\t}\n\treturn nil\n}", "func (c *Channel) Send(message string, recursive bool) {\n\ttextMessage := TextMessage{\n\t\tMessage: message,\n\t}\n\tif recursive {\n\t\ttextMessage.Trees = []*Channel{c}\n\t} else {\n\t\ttextMessage.Channels = []*Channel{c}\n\t}\n\tc.client.Send(&textMessage)\n}", "func Chat(chub *connections.ConnectionHub) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tgo chub.WriteMessage()\n\t\tlog.Println(\"wrote message\")\n\t})\n}" ]
[ "0.7732439", "0.74268425", "0.7389534", "0.7340354", "0.72862184", "0.707481", "0.7074682", "0.6926702", "0.6915882", "0.69094616", "0.69049686", "0.68718964", "0.6864219", "0.6815867", "0.67980945", "0.6793824", "0.671282", "0.6694843", "0.6692216", "0.6663749", "0.66623217", "0.66123766", "0.6592559", "0.6571184", "0.6467464", "0.64654845", "0.6457172", "0.6455419", "0.64484066", "0.64380014", "0.63889897", "0.63775384", "0.63677776", "0.63640815", "0.6359428", "0.63575", "0.6350762", "0.6349996", "0.6337787", "0.63323534", "0.63306034", "0.63197017", "0.631329", "0.6305032", "0.6293887", "0.6266078", "0.6258343", "0.625497", "0.6245188", "0.6234272", "0.6231851", "0.6225409", "0.6225409", "0.62020814", "0.6200485", "0.6192136", "0.61879796", "0.6182515", "0.617649", "0.61664337", "0.61531687", "0.6135592", "0.61317766", "0.612972", "0.6118227", "0.6103712", "0.6103406", "0.6082817", "0.6082628", "0.60822695", "0.6072666", "0.60526353", "0.60490054", "0.6037551", "0.60302335", "0.602684", "0.6022569", "0.60041994", "0.600043", "0.59982777", "0.5992907", "0.599268", "0.5989149", "0.5985228", "0.59825045", "0.5978092", "0.5977391", "0.59737957", "0.59565485", "0.5954523", "0.5953567", "0.5948937", "0.59326667", "0.59296334", "0.59279823", "0.5924729", "0.5921439", "0.59017545", "0.58896714", "0.58878237" ]
0.61143094
65
NewActivity creates a new AppActivity
func NewActivity(metadata *activity.Metadata) activity.Activity { return &SleepActivity{metadata: metadata} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewActivity(metadata *activity.Metadata) activity.Activity {\n return &MyActivity{metadata: metadata}\n}", "func newManifestApp() *types.App {\n\treturn &types.App{\n\t\tUser: \"0\",\n\t\tGroup: \"0\",\n\t}\n}", "func newManifestApp() *types.App {\n\treturn &types.App{\n\t\tUser: \"0\",\n\t\tGroup: \"0\",\n\t}\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n\tctx.Logger().Info(\"In New activity\")\n\n\tact := &Activity{}\n\treturn act, nil\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n\tctx.Logger().Info(\"In New activity\")\n\n\tact := &Activity{}\n\treturn act, nil\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n\tctx.Logger().Info(\"In New activity\")\n\n\tact := &Activity{}\n\treturn act, nil\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\r\n\treturn &MyActivity{metadata: metadata}\r\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\treturn &Activity{}, nil\n}", "func newApp(name string) (app *App, err error) {\n\tapp = &App{\n\t\tName: name,\n\t\tID: uuid.NewV5(namespace, \"org.homealone.\"+name).String(),\n\t\thandler: make(map[queue.Topic]message.Handler),\n\t\tdebug: *debug,\n\t\tfilterMessages: true,\n\t}\n\tapp.Log = log.NewLogger().With(log.Fields{\"app\": name, \"id\": app.ID})\n\treturn app, errors.Wrap(err, \"newApp failed\")\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MyActivity{metadata: metadata}\n}", "func NewApp(f interface{}, args Arguments, info *debug.Info) App {\n\treturn App{f, args, info}\n}", "func (api API) CreateActivity(config ActivityConfig) (activity Activity, err error) {\n\n\tbearer, err := api.Authenticator.GetToken(\"code:all\")\n\tif err != nil {\n\t\treturn\n\t}\n\tpath := api.Authenticator.GetHostPath() + api.DesignAutomationPath\n\tactivity, err = createActivity(path, config, bearer.AccessToken)\n\n\tactivity.authenticator = api.Authenticator\n\tactivity.path = path\n\tactivity.name = config.ID\n\n\t//WARNING: when an Activity is created, it is assigned an '$LATEST' alias\n\t// but this alias is not usable and if no other alias is created for this\n\t// appBundle, then the alias listing will fail.\n\t// Thus I decided to autoasign a \"default\" alias upon app creation\n\tgo activity.CreateAlias(\"default\", 1)\n\n\treturn\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n\tact := &Activity{} //add aSetting to instance\n\treturn act, nil\n}", "func (t tApp) New(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\tc := &contr.App{}\n\tc.Controllers = Controllers.New(w, r, ctr, act)\n\treturn c\n}", "func NewActivity(a *ARC, pkgName, activityName string) (*Activity, error) {\n\tdisp, err := NewDisplay(a, DefaultDisplayID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create a new Display\")\n\t}\n\treturn &Activity{\n\t\ta: a,\n\t\tpkgName: pkgName,\n\t\tactivityName: activityName,\n\t\tdisp: disp,\n\t}, nil\n}", "func NewApp() App {\n\treturn App{}\n}", "func NewApp() App {\n\treturn App{}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &AddActivity{metadata: metadata}\n}", "func NewActivity(activity, showDate, date, annotation string, isImportant, isNotify int) *Activity {\n\tnow := helper.FormattedDateTimeNow()\n\treturn &Activity{\n\t\tActivity: activity,\n\t\tShowDate: showDate,\n\t\tDate: date,\n\t\tAnnotation: annotation,\n\t\tIsImportant: isImportant,\n\t\tIsNotify: isNotify,\n\t\tCreatedAt: now,\n\t\tUpdatedAt: now,\n\t}\n}", "func NewActivity() *Activity {\n\treturn &Activity{}\n}", "func New() App {\n\treturn App{}\n}", "func (c *Controller) renderNew(ctx context.Context, w http.ResponseWriter, app *database.MobileApp) {\n\tm := templateMap(ctx)\n\tm.Title(\"New mobile app\")\n\tm[\"app\"] = app\n\tc.h.RenderHTML(w, \"mobileapps/new\", m)\n}", "func NewApp(name string) *App {\n\treturn &App{Name: name, Labels: make(map[string]string)}\n}", "func New(descr string) App {\n\treturn &app{descr: descr}\n}", "func newApp(desc string) *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = name\n\tapp.HelpName = filepath.Base(os.Args[0])\n\tapp.Author = author\n\tapp.Version = version\n\tapp.Description = desc\n\tapp.Writer = os.Stdout\n\treturn app\n}", "func NewCmdNewApplication(f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAppOptions(streams)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"new-app (IMAGE | IMAGESTREAM | TEMPLATE | PATH | URL ...)\",\n\t\tShort: \"Create a new application\",\n\t\tLong: newAppLong,\n\t\tExample: newAppExample,\n\t\tSuggestFor: []string{\"app\", \"application\"},\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tkcmdutil.CheckErr(o.Complete(f, c, args))\n\t\t\tkcmdutil.CheckErr(o.RunNewApp())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().BoolVar(&o.Config.AsTestDeployment, \"as-test\", o.Config.AsTestDeployment, \"If true create this application as a test deployment, which validates that the deployment succeeds and then scales down.\")\n\tcmd.Flags().BoolVar(&o.Config.DeploymentConfig, \"as-deployment-config\", o.Config.DeploymentConfig, \"If true create this application as a deployment config, which allows for hooks and custom strategies.\")\n\tcmd.Flags().StringSliceVar(&o.Config.SourceRepositories, \"code\", o.Config.SourceRepositories, \"Source code to use to build this application.\")\n\tcmd.Flags().StringVar(&o.Config.ContextDir, \"context-dir\", o.Config.ContextDir, \"Context directory to be used for the build.\")\n\tcmd.Flags().StringSliceVarP(&o.Config.ImageStreams, \"image-stream\", \"i\", o.Config.ImageStreams, \"Name of an existing image stream to use to deploy an app.\")\n\tcmd.Flags().StringSliceVar(&o.Config.DockerImages, \"image\", o.Config.DockerImages, \"Name of a container image to include in the app. Note: not specifying a registry or repository means defaults in place for client image pulls are employed.\")\n\tcmd.Flags().StringSliceVar(&o.Config.DockerImages, \"docker-image\", o.Config.DockerImages, \"\")\n\tcmd.Flags().MarkDeprecated(\"docker-image\", \"Deprecated flag use --image\")\n\tcmd.Flags().StringSliceVar(&o.Config.Templates, \"template\", o.Config.Templates, \"Name of a stored template to use in the app.\")\n\tcmd.Flags().StringSliceVarP(&o.Config.TemplateFiles, \"file\", \"f\", o.Config.TemplateFiles, \"Path to a template file to use for the app.\")\n\tcmd.MarkFlagFilename(\"file\", \"yaml\", \"yml\", \"json\")\n\tcmd.Flags().StringArrayVarP(&o.Config.TemplateParameters, \"param\", \"p\", o.Config.TemplateParameters, \"Specify a key-value pair (e.g., -p FOO=BAR) to set/override a parameter value in the template.\")\n\tcmd.Flags().StringArrayVar(&o.Config.TemplateParameterFiles, \"param-file\", o.Config.TemplateParameterFiles, \"File containing parameter values to set/override in the template.\")\n\tcmd.MarkFlagFilename(\"param-file\")\n\tcmd.Flags().StringSliceVar(&o.Config.Groups, \"group\", o.Config.Groups, \"Indicate components that should be grouped together as <comp1>+<comp2>.\")\n\tcmd.Flags().StringArrayVarP(&o.Config.Environment, \"env\", \"e\", o.Config.Environment, \"Specify a key-value pair for an environment variable to set into each container.\")\n\tcmd.Flags().StringArrayVar(&o.Config.EnvironmentFiles, \"env-file\", o.Config.EnvironmentFiles, \"File containing key-value pairs of environment variables to set into each container.\")\n\tcmd.MarkFlagFilename(\"env-file\")\n\tcmd.Flags().StringArrayVar(&o.Config.BuildEnvironment, \"build-env\", o.Config.BuildEnvironment, \"Specify a key-value pair for an environment variable to set into each build image.\")\n\tcmd.Flags().StringArrayVar(&o.Config.BuildEnvironmentFiles, \"build-env-file\", o.Config.BuildEnvironmentFiles, \"File containing key-value pairs of environment variables to set into each build image.\")\n\tcmd.MarkFlagFilename(\"build-env-file\")\n\tcmd.Flags().StringVar(&o.Config.Name, \"name\", o.Config.Name, \"Set name to use for generated application artifacts\")\n\tcmd.Flags().Var(&o.Config.Strategy, \"strategy\", \"Specify the build strategy to use if you don't want to detect (docker|pipeline|source). NOTICE: the pipeline strategy is deprecated; consider using Jenkinsfiles directly on Jenkins or OpenShift Pipelines.\")\n\tcmd.Flags().StringP(\"labels\", \"l\", \"\", \"Label to set in all resources for this application.\")\n\tcmd.Flags().BoolVar(&o.Config.IgnoreUnknownParameters, \"ignore-unknown-parameters\", o.Config.IgnoreUnknownParameters, \"If true, will not stop processing if a provided parameter does not exist in the template.\")\n\tcmd.Flags().BoolVar(&o.Config.InsecureRegistry, \"insecure-registry\", o.Config.InsecureRegistry, \"If true, indicates that the referenced container images are on insecure registries and should bypass certificate checking\")\n\tcmd.Flags().BoolVarP(&o.Config.AsList, \"list\", \"L\", o.Config.AsList, \"List all local templates and image streams that can be used to create.\")\n\tcmd.Flags().BoolVarP(&o.Config.AsSearch, \"search\", \"S\", o.Config.AsSearch, \"Search all templates, image streams, and container images that match the arguments provided. Note: the container images search is run on the OpenShift cluster via the ImageStreamImport API.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowMissingImages, \"allow-missing-images\", o.Config.AllowMissingImages, \"If true, indicates that referenced container images that cannot be found locally or in a registry should still be used.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowMissingImageStreamTags, \"allow-missing-imagestream-tags\", o.Config.AllowMissingImageStreamTags, \"If true, indicates that image stream tags that don't exist should still be used.\")\n\tcmd.Flags().BoolVar(&o.Config.AllowSecretUse, \"grant-install-rights\", o.Config.AllowSecretUse, \"If true, a component that requires access to your account may use your token to install software into your project. Only grant images you trust the right to run with your token.\")\n\tcmd.Flags().StringVar(&o.Config.SourceSecret, \"source-secret\", o.Config.SourceSecret, \"The name of an existing secret that should be used for cloning a private git repository.\")\n\tcmd.Flags().BoolVar(&o.Config.SkipGeneration, \"no-install\", o.Config.SkipGeneration, \"Do not attempt to run images that describe themselves as being installable\")\n\tcmd.Flags().BoolVar(&o.Config.BinaryBuild, \"binary\", o.Config.BinaryBuild, \"Instead of expecting a source URL, set the build to expect binary contents. Will disable triggers.\")\n\tcmd.Flags().StringVar(&o.Config.ImportMode, \"import-mode\", o.Config.ImportMode, \"Imports the full manifest list of a tag when set to 'PreserveOriginal'. Defaults to 'Legacy'.\")\n\n\to.Action.BindForOutput(cmd.Flags(), \"output\", \"template\")\n\tcmd.Flags().String(\"output-version\", \"\", \"The preferred API versions of the output objects\")\n\n\treturn cmd\n}", "func NewApp() *App {\n\tpages := ui.NewPageHandler()\n\n\tapp := tview.NewApplication().\n\t\tSetInputCapture(pages.InputCapture()).\n\t\tSetRoot(pages, true)\n\n\treturn &App{\n\t\tPageHandler: pages,\n\t\tapp: app,\n\t}\n}", "func NewApp(name string, basename string, opts ...Option) *App {\n\ta := &App{\n\t\tname: name,\n\t\tbasename: basename,\n\t}\n\n\tfor _, o := range opts {\n\t\to(a)\n\t}\n\n\treturn a\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &MakeDirectoryActivity{metadata: metadata}\n}", "func NewActivity(name ActivityName) Activity {\n\tcreated := time.Now()\n\treturn Activity{\n\t\tName: string(name),\n\t\tPublicID: uuid.NewV4().String(),\n\t\tCreated: created,\n\t\tUpdated: created,\n\t}\n}", "func NewApp(s *Services, c *Clients, a alert.Alert) *App {\n\treturn &App{\n\t\tServices: s,\n\t\tClients: c,\n\t\tAlert: a,\n\t}\n}", "func NewApp(entry *Entry) (app *App) {\n\tapp = new(App)\n\tapp.ID = entry.TrackID\n\tapp.Name = entry.TrackName\n\tapp.URL = entry.TrackViewURL\n\n\tapp.Icon = entry.ArtworkURL512\n\tapp.Kind = entry.Kind\n\tapp.Version = entry.Version\n\tapp.BundleID = entry.BundleID\n\n\tapp.AuthorID = entry.ArtistID\n\tapp.AuthorName = entry.ArtistName\n\tapp.AuthorURL = entry.ArtistViewURL\n\tapp.VendorName = entry.SellerName\n\tapp.VendorURL = entry.SellerURL\n\n\tapp.GenreID = entry.PrimaryGenreID\n\tapp.GenreIDList = stringSliceToInt(entry.GenreIDs)\n\tapp.Genre = entry.PrimaryGenreName\n\tapp.GenreList = entry.Genres\n\n\tapp.Icon60 = entry.ArtworkURL60\n\tapp.Icon100 = entry.ArtworkURL100\n\tapp.Price = int64(math.Ceil(entry.Price))\n\tapp.Currency = entry.Currency\n\n\tapp.System = entry.MinimumOsVersion\n\tapp.Features = entry.Features\n\tapp.Devices = entry.SupportedDevices\n\tapp.Languages = entry.LanguageCodesISO2A\n\n\tapp.Rating = entry.TrackContentRating\n\tif app.Rating == \"\" {\n\t\tapp.Rating = entry.ContentAdvisoryRating\n\t}\n\tapp.Reasons = entry.Advisories\n\n\tapp.Size, _ = strconv.ParseInt(entry.FileSizeBytes, 10, 64)\n\tapp.CntRating = entry.UserRatingCount\n\tapp.AvgRating = entry.AverageUserRating\n\tapp.CntRatingCurrent = entry.UserRatingCountForCurrentVersion\n\tapp.AvgRatingCurrent = entry.AverageUserRatingForCurrentVersion\n\tapp.VppDevice = entry.IsVppDeviceBasedLicensingEnabled\n\tapp.GameCenter = entry.IsGameCenterEnabled\n\n\tapp.Screenshots = merge(entry.ScreenshotURLs, entry.AppletvScreenshotURLs, entry.IpadScreenshotURLs)\n\n\t// Reserved fields: these fields should be fetched from iTunes page\n\t// app.Copyright\n\t// app.Platforms\n\t// app.InAppPurchase\n\t// app.SiblingApps\n\t// app.RelatedApps\n\t// app.SupportSites\n\t// app.Reviews\n\n\tapp.Description = entry.Description\n\tapp.ReleaseNotes = entry.ReleaseNotes\n\tapp.ReleaseTime, _ = time.Parse(time.RFC3339, entry.CurrentVersionReleaseDate)\n\tapp.PublishTime, _ = time.Parse(time.RFC3339, entry.ReleaseDate)\n\tapp.CrawledTime = time.Now()\n\tsort.Strings(app.Devices)\n\tsort.Strings(app.Languages)\n\n\treturn app\n}", "func New(ctx activity.InitContext) (activity.Activity, error) {\n\n//\ts := &Settings{}\n//\terr := metadata.MapToStruct(ctx.Settings(), s, true)\n//\tif err != nil {\n//\t\treturn nil, err\n//\t}\n\n//\tctx.Logger().Debugf(\"Setting: %s\", s.ASetting)\n\n\tact := &Activity{} //add aSetting to instance//nothing to add now\n\n\treturn act, nil\n}", "func NewActivity(userID, name string) activity.Activity {\n\treturn activity.Activity{\n\t\tUserID: userID,\n\t\tName: name,\n\t\tMetadata: make(activity.ActivityMetadata),\n\t\tOccuredAt: time.Now(),\n\t}\n}", "func New() *App {\n\treturn &App{}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func NewApp() *App {\n\treturn &App{}\n}", "func NewExternalActivity()(*ExternalActivity) {\n m := &ExternalActivity{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}", "func newAppContext(ctx Context, m *Module) Context {\n\treturn &appContext{\n\t\tContext: ctx,\n\t\tchain: *m,\n\t\tindex: -1,\n\t}\n}", "func (b BotAppNotModified) construct() BotAppClass { return &b }", "func New() *App {\n\treturn NewApp(newDefaultApp())\n}", "func (t tApp) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.App{}\n\n\t// Allocate its parents. Make sure controller of every type\n\t// is allocated just once, then reused.\n\tc.Controllers = &contr.Controllers{}\n\tc.Controllers.Templates = c.Controllers.Errors.Templates\n\tc.Controllers.Errors = &c5.Errors{}\n\tc.Controllers.Static = &c3.Static{}\n\tc.Controllers.Sessions = &c2.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Requests = &c1.Requests{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Global = &c0.Global{\n\n\t\tCurrentAction: act,\n\n\t\tCurrentController: ctr,\n\t}\n\tc.Controllers.Errors.Templates = &c4.Templates{}\n\tc.Controllers.Errors.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Errors.Templates.Global = c.Controllers.Global\n\tc.Controllers.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Templates.Global = c.Controllers.Global\n\n\treturn c\n}", "func NewApp(name string) (*App, error) {\n\treturn newApp(\"app.\" + name)\n}", "func NewApp() *App {\n\treturn &App{\n\t\tName: filepath.Base(os.Args[0]),\n\t\tUsage: \"A new cli application\",\n\t\tVersion: \"0.0.0\",\n\t\tShowHelp: showHelp,\n\t\tShowVersion: showVersion,\n\t}\n}", "func makeApp(def pchannel.App, data pchannel.Data) perun.App {\n\treturn perun.App{\n\t\tDef: def,\n\t\tData: data,\n\t}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &ListActivity{metadata: metadata}\n}", "func NewApp() App {\n\treturn new(app)\n}", "func NewApp(ctx *pulumi.Context,\n\tname string, args *AppArgs, opts ...pulumi.ResourceOption) (*App, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AppType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AppType'\")\n\t}\n\tif args.DomainId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DomainId'\")\n\t}\n\tif args.UserProfileName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserProfileName'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource App\n\terr := ctx.RegisterResource(\"aws-native:sagemaker:App\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewAppItem(name string, protocol string, address string) *AppItem {\n instance := new(AppItem)\n instance.name = name\n instance.protocol = protocol\n instance.address = address\n return instance\n}", "func CreateApplication() *Alpha {\n app := &Alpha{}\n app.Request = &Request{}\n app.Response = &Response{}\n app.init()\n return app\n}", "func newApp() (*app, error) {\n\tapp := &app{}\n\n\tgd, err := newGDrive(\"\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable initializate Google Drive configuration: %v\", err)\n\t}\n\tapp.gDrive = gd\n\n\tsrv, err := app.gDrive.getService()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to retrieve Drive client: %v\", err)\n\t}\n\tapp.srv = srv\n\n\treturn app, nil\n}", "func New(c Config) *App {\n\treturn &App{\n\t\tName: c.Name,\n\t}\n}", "func New(c *deis.Client, appID string) (api.App, error) {\n\tbody := []byte{}\n\n\tif appID != \"\" {\n\t\treq := api.AppCreateRequest{ID: appID}\n\t\tb, err := json.Marshal(req)\n\n\t\tif err != nil {\n\t\t\treturn api.App{}, err\n\t\t}\n\t\tbody = b\n\t}\n\n\tres, reqErr := c.Request(\"POST\", \"/v2/apps/\", body)\n\tif reqErr != nil && !deis.IsErrAPIMismatch(reqErr) {\n\t\treturn api.App{}, reqErr\n\t}\n\tdefer res.Body.Close()\n\n\tapp := api.App{}\n\tif err := json.NewDecoder(res.Body).Decode(&app); err != nil {\n\t\treturn api.App{}, err\n\t}\n\n\treturn app, reqErr\n}", "func NewApp(config gettConfig.AppConfig, handler http.Handler, logger *logrus.Logger, pingers []healthcheck.Pinger) App {\n\tapp := App{\n\t\tconfig: config,\n\t\thandler: handler,\n\t\tlogger: logger,\n\t\tpingers: pingers,\n\t}\n\n\tgettOps.InitOps()\n\n\tlog.SetFlags(0)\n\tlog.Print(skeletonBanner)\n\tlog.SetFlags(log.LstdFlags)\n\n\treturn app\n}", "func NewApp() *App {\n\treturn &App{ver: \"v0\"}\n}", "func NewApp() *App {\n\tapp := App{}\n\treturn &app\n}", "func New(appName, version string) *App {\n\treturn createApp(appName, version)\n}", "func NewApp(out io.Writer, url string) App {\n\treturn App{Out: out, URL: url}\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &FabricRequestActivity{metadata: metadata}\n}", "func NewApp(cfg *Config) *App {\n\treturn &App{\n\t\tl: log.With().Str(\"m\", \"app\").Logger(),\n\t\tcfg: cfg,\n\t\tgui: gui.NewGui(&cfg.Gui),\n\t}\n}", "func NewApplication()(*Application) {\n m := &Application{\n DirectoryObject: *NewDirectoryObject(),\n }\n odataTypeValue := \"#microsoft.graph.application\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func NewApp(cfg *config.Server, nodeContext *node.Context) (*App, error) {\n\tif cfg == nil || nodeContext == nil {\n\t\treturn nil, errors.New(\"got nil argument\")\n\t}\n\n\t// TODO: Determine the final logWriter in the configuration file\n\tw := os.Stdout\n\n\tapp := &App{\n\t\tname: \"OneLedger\",\n\t\tlogger: log.NewLoggerWithPrefix(w, \"app\").WithLevel(log.Level(cfg.Node.LogLevel)),\n\t}\n\tapp.nodeName = cfg.Node.NodeName\n\n\tctx, err := newContext(w, *cfg, nodeContext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create new app context\")\n\t}\n\n\tapp.Context = ctx\n\tapp.setNewABCI()\n\treturn app, nil\n}", "func AppCreate(ctx *Context, name string, typ DeviceType) (*Application, error) {\n\th := authHeader(ctx.Config.AuthToken)\n\turi := ctx.Config.APIEndpoint(\"application\")\n\tdata := make(map[string]interface{})\n\tdata[\"app_name\"] = name\n\tdata[\"device_type\"] = typ.String()\n\tbody, err := marhsalReader(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := doJSON(ctx, \"POST\", uri, h, nil, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trst := &Application{}\n\terr = json.Unmarshal(b, rst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rst, nil\n}", "func NewApp() *App_ {\n\treturn NewApp_WithOverrides(nil)\n}", "func NewApp(gitCommit, usage string) *cli.App {\r\n\tapp := cli.NewApp()\r\n\tapp.Name = filepath.Base(os.Args[0])\r\n\tapp.Author = \"\"\r\n\t//app.Authors = nil\r\n\tapp.Email = \"\"\r\n\tapp.Version = params.Version\r\n\tif len(gitCommit) >= 8 {\r\n\t\tapp.Version += \"-\" + gitCommit[:8]\r\n\t}\r\n\tapp.Usage = usage\r\n\treturn app\r\n}", "func NewApp(name string, scopes []string, redirectURI string) (g *Gondole, err error) {\n\t// Load configuration, will register if none is found\n\tcnf, err := LoadConfig(name)\n\tif err != nil {\n\t\t// Nothing exist yet\n\t\tcnf := Config{\n\t\t\tDefault: name,\n\t\t}\n\t\terr = cnf.Write()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error: can not write config for %s\", name)\n\t\t}\n\n\t\t// Now register this through OAuth\n\t\tif scopes == nil {\n\t\t\tscopes = ourScopes\n\t\t}\n\n\t\tg, err = registerApplication(name, scopes, redirectURI)\n\n\t} else {\n\t\tg = &Gondole{\n\t\t\tName: cnf.Name,\n\t\t\tID: cnf.ID,\n\t\t\tSecret: cnf.BearerToken,\n\t\t}\n\t}\n\n\treturn\n}", "func NewApp() *App {\n\treturn &App{\n\t\tConfig: &Config{},\n\t}\n}", "func NewApp(name string) (*App, error) {\n\tvar (\n\t\tconfig Config\n\t\tflagset = flag.NewFlagSet(name, flagErrorHandling)\n\t)\n\tif err := flagset.Parse(os.Args[1:]); err != nil {\n\t\tif err == flag.ErrHelp {\n\t\t\treturn &App{pass: true}, nil\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"parsing flags\")\n\t}\n\treturn NewAppFrom(name, config)\n}", "func NewAndroidManagedStoreApp()(*AndroidManagedStoreApp) {\n m := &AndroidManagedStoreApp{\n MobileApp: *NewMobileApp(),\n }\n odataTypeValue := \"#microsoft.graph.androidManagedStoreApp\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func New(opts ...Option) *App {\n\toptions := options{\n\t\tctx: context.Background(),\n\t\tsigns: []os.Signal{syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT},\n\t}\n\n\tif id, err := uuid.NewUUID(); err == nil {\n\t\toptions.id = id.String()\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tctx, cancel := context.WithCancel(options.ctx)\n\treturn &App{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\topts: options,\n\t}\n}", "func NewApp(database string) *Application {\n\tfolder := filepath.Dir(os.Args[0]) /* go 1.7.5 */\n\tconn, err := sql.Open(\"sqlite3\", folder+\"/\"+database)\n\n\tif err != nil {\n\t\tlog.Fatal(\"SQLite open; \", err)\n\t\treturn &Application{}\n\t}\n\n\tlog.Println(\"Database:\", folder+\"/\"+database)\n\n\tquery := `\n\tCREATE TABLE IF NOT EXISTS reviews (\n\t\tid INTEGER PRIMARY KEY,\n\t\tuid TEXT,\n\t\tname TEXT,\n\t\temail TEXT,\n\t\trating INTEGER,\n\t\tcomment TEXT,\n\t\tapproved INTEGER,\n\t\ttimestamp TIMESTAMP\n\t);\n\t`\n\n\tif _, err := conn.Exec(query); err != nil {\n\t\tlog.Fatal(\"Database setup; \", err)\n\t\treturn &Application{}\n\t}\n\n\treturn &Application{db: conn}\n}", "func newTestApp() *App {\n\treturn &App{\n\t\tstorage: storage.NewMemory(),\n\t}\n}", "func (c Client) createApp(body io.Reader) (*App, error) {\n\treq, err := http.NewRequest(\"POST\", c.getURL(\"/apps\"), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar marshalled map[string]*App\n\terr = c.executeRequestAndMarshal(req, &marshalled)\n\treturn marshalled[\"app\"], err\n}", "func NewApp(gitCommit, usage string) *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = filepath.Base(os.Args[0])\n\tapp.Author = \"\"\n\tapp.Email = \"\"\n\tapp.Version = Version\n\tapp.Usage = usage\n\treturn app\n}", "func MakeCreateActivity(activityID *url.URL) vocab.ActivityStreamsCreate {\n\tactivity := streams.NewActivityStreamsCreate()\n\tid := streams.NewJSONLDIdProperty()\n\tid.Set(activityID)\n\tactivity.SetJSONLDId(id)\n\n\treturn activity\n}", "func newApp(infile, outfile string) *App {\n\treturn &App{\n\t\tAddressFile: infile,\n\t\tGeoDecodeFile: outfile,\n\t\tClient: &http.Client{},\n\t}\n}", "func (controller *ActivityController) Create(res http.ResponseWriter, req *http.Request) {\n\tif !controller.auth.IsLogin(res, req) {\n\t\thttp.Redirect(res, req, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tcontroller.render(res, req, \"activity_create.gohtml\", nil, 2)\n}", "func NewActivity(metadata *activity.Metadata) activity.Activity {\n\treturn &RESTActivity{metadata: metadata}\n}" ]
[ "0.66808873", "0.6311383", "0.6311383", "0.6150149", "0.6150149", "0.6150149", "0.60460955", "0.5991709", "0.5933953", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5847072", "0.5741412", "0.5706258", "0.56748253", "0.5671901", "0.5658194", "0.5656957", "0.5656957", "0.5653454", "0.5649347", "0.5615923", "0.55797905", "0.5546446", "0.5543621", "0.55312127", "0.55136317", "0.54876703", "0.5475328", "0.5456699", "0.5436101", "0.5435847", "0.5420668", "0.5410701", "0.5402481", "0.53786963", "0.5360766", "0.5348944", "0.5348944", "0.5348944", "0.53444463", "0.53339845", "0.53123176", "0.530446", "0.5302279", "0.5301558", "0.5299886", "0.5283926", "0.52784485", "0.526567", "0.52489537", "0.5242453", "0.5234688", "0.523011", "0.522591", "0.5218659", "0.5178245", "0.5172914", "0.517238", "0.5154906", "0.51544774", "0.51500756", "0.5141461", "0.5141422", "0.51413995", "0.5139394", "0.51356536", "0.5133418", "0.5132073", "0.5125355", "0.5120497", "0.5108849", "0.51079696", "0.5098168", "0.50931054", "0.50919586", "0.5082018", "0.5066343", "0.506459", "0.5057917", "0.50553375" ]
0.53351647
60
Metadata returns the activity's metadata
func (a *SleepActivity) Metadata() *activity.Metadata { return a.metadata }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (*Activity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func (a *AddActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *RESTActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *JSONDataDecouplerActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *OPEMapMenuActivity) Metadata() *activity.Metadata {\n\treturn activityMd\n}", "func getActivityMetadata() *activity.Metadata {\n\tif activityMetadata == nil {\n\t\tjsonMetadataBytes, err := ioutil.ReadFile(\"../../../SmartContract/activity/collection/activity.json\")\n\t\tif err != nil {\n\t\t\tpanic(\"No Json Metadata found for activity.json path\")\n\t\t}\n\t\tactivityMetadata = activity.NewMetadata(string(jsonMetadataBytes))\n\t}\n\treturn activityMetadata\n}", "func (a *AggregateActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *ErrorActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *GPIOActivity) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (a *App) Metadata() map[string]string { return a.opts.metadata }", "func (a *Accumulator) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (m Manifest) Metadata() Metadata {\n\tif m[\"metadata\"] == nil {\n\t\tm[\"metadata\"] = make(map[string]interface{})\n\t}\n\treturn Metadata(m[\"metadata\"].(map[string]interface{}))\n}", "func (a *CSVFileWriter) Metadata() *activity.Metadata {\n\treturn a.metadata\n}", "func (e *EntryBase) Metadata(ctx context.Context) (JSONObject, error) {\n\t// Disable Metadata's caching in case the plugin author forgot to do this\n\te.DisableCachingFor(MetadataOp)\n\n\tattr := e.attributes()\n\treturn attr.Meta(), nil\n}", "func GetMetadata() (map[string]string, error) {\n\tcu, err := GetUtil()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]string{\n\t\t\"cri_name\": cu.GetRuntime(),\n\t\t\"cri_version\": cu.GetRuntimeVersion(),\n\t}, nil\n}", "func (tr *TestResult) MetaData() Metadata {\n\treturn tr.Metadata\n}", "func (r *Alarm_MetricDataQuery) Metadata() map[string]interface{} {\n\treturn r._metadata\n}", "func (_IRMAScheme *IRMASchemeCaller) Metadata(opts *bind.CallOpts) ([]byte, error) {\n\tvar (\n\t\tret0 = new([]byte)\n\t)\n\tout := ret0\n\terr := _IRMAScheme.contract.Call(opts, out, \"metadata\")\n\treturn *ret0, err\n}", "func GetAIMetadata() string {\n\treturn aiMetadata\n}", "func (c *Capture) Metadata() CaptureMetadata {\n\treturn CaptureMetadata{\n\t\tID: c.ID,\n\t\tPath: c.Req.URL.Path,\n\t\tMethod: c.Req.Method,\n\t\tStatus: c.Res.StatusCode,\n\t}\n}", "func (ft FanToken) GetMetaData() Metadata {\n\treturn ft.MetaData\n}", "func GetMetadata() (*Metadata, error) {\n\tif data == nil {\n\t\tdate, err := time.Parse(time.RFC1123Z, CompiledOn)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tdate = time.Now()\n\t\t}\n\t\tdata = &Metadata{RunningSince: time.Now(), BuildSHA: BuildCommitSHA, CompiledOn: date}\n\t\terr = json.Unmarshal([]byte(VersionInfo), data)\n\t\treturn data, err\n\t}\n\treturn data, nil\n}", "func (r *AWSAppStreamStack) Metadata() map[string]interface{} {\n\treturn r._metadata\n}", "func (i *item) Metadata() (map[string]interface{}, error) {\n\treturn i.wrapped.Metadata()\n}", "func GetMetadata(c *gin.Context) {\n\ttitle := utils.FormatString(c.Param(\"title\"))\n\tmetadataStore := datastore.GetStore()\n\n\tdata, err := metadataStore.GetApplication(title)\n\tif err != nil {\n\t\tc.YAML(http.StatusNotFound, gin.H{\"status\": http.StatusNotFound, \"message\": messages.MetadataNotFound, \"error\": err})\n\t} else {\n\t\tc.YAML(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": messages.MetadataFound, \"data\": data})\n\t}\n}", "func (o *Job) GetMetadata() map[string]string {\n\tif o == nil || o.Metadata == nil {\n\t\tvar ret map[string]string\n\t\treturn ret\n\t}\n\treturn *o.Metadata\n}", "func (i *item) Metadata() (map[string]interface{}, error) {\n\terr := i.ensureInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn i.metadata, nil\n}", "func (s *AppServerV3) GetMetadata() Metadata {\n\treturn s.Metadata\n}", "func (c *CoordinatorHelper) Metadata(\n\tctx context.Context,\n\tnetworkIdentifier *types.NetworkIdentifier,\n\tmetadataRequest map[string]interface{},\n) (map[string]interface{}, error) {\n\tres, fetchErr := c.offlineFetcher.ConstructionMetadata(\n\t\tctx,\n\t\tnetworkIdentifier,\n\t\tmetadataRequest,\n\t)\n\n\tif fetchErr != nil {\n\t\treturn nil, fetchErr.Err\n\t}\n\n\treturn res, nil\n}", "func (i *InstallationPermissions) GetMetadata() string {\n\tif i == nil || i.Metadata == nil {\n\t\treturn \"\"\n\t}\n\treturn *i.Metadata\n}", "func (op *RunPipelineOperation) Metadata() (*lifesciencespb.Metadata, error) {\n\tvar meta lifesciencespb.Metadata\n\tif err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn &meta, nil\n}", "func (o *Transfer) GetMetadata() map[string]string {\n\tif o == nil {\n\t\tvar ret map[string]string\n\t\treturn ret\n\t}\n\n\treturn o.Metadata\n}", "func (r *AWSCloudWatchAlarm_MetricDataQuery) Metadata() map[string]interface{} {\n\treturn r._metadata\n}", "func (m *Metadata) GetMetadata() Metadata {\n\treturn *m\n}", "func (w *S3Walker) Metadata() map[string]*string {\n\treturn w.metadata\n}", "func (t *SFTPUpload) Metadata() *gornir.TaskMetadata {\n\treturn t.Meta\n}", "func (trs *Transactions) GetMetaData() stored_files.File {\n\treturn trs.Met\n}", "func (v Version) Metadata() string {\n\treturn strings.Join(v.metadata, \".\")\n}", "func (f *Fetch) Metadata(a *Artifact) *MetadataXML {\n\tmetadata := &MetadataXML{Group: a.GroupID, Artifact: a.ArtifactID}\n\tmetadata.Unmarshal(f.mustFetch(a.MetadataPath()))\n\treturn metadata\n}", "func (n *wrapped) Metadata() a.Object {\n\treturn n.meta\n}", "func (_IRMAScheme *IRMASchemeCallerSession) Metadata() ([]byte, error) {\n\treturn _IRMAScheme.Contract.Metadata(&_IRMAScheme.CallOpts)\n}", "func (o *NewData) GetMetadata() map[string]interface{} {\n\tif o == nil || o.Metadata == nil {\n\t\tvar ret map[string]interface{}\n\t\treturn ret\n\t}\n\treturn *o.Metadata\n}", "func (d *Driver) GetMetadata(id string) (map[string]string, error) {\n\tlogrus.Debugf(\"GetMetadata\")\n\treturn nil, nil\n}", "func AgentMetadata() *agents.Metadata {\n\treturn &agents.Metadata{\n\t\tName: \"backplane\",\n\t\tDescription: \"Choria Management Backplane\",\n\t\tAuthor: \"R.I.Pienaar <[email protected]>\",\n\t\tVersion: Version,\n\t\tLicense: \"Apache-2.0\",\n\t\tURL: \"https://choria.io\",\n\t\tTimeout: 10,\n\t}\n}", "func (c *jsiiProxy_CfnApplication) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (c *jsiiProxy_CfnApplication) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (s *countAPI) Metadata(ctx context.Context, metric, limit string) (map[string][]v1.Metadata, error) {\n\ts.callCount[\"Metadata\"]++\n\treturn s.API.Metadata(ctx, metric, limit)\n}", "func (r *AnalyticsResult) Metadata() (*AnalyticsMetadata, error) {\n\tif !r.streamResult.Closed() {\n\t\treturn nil, clientError{message: \"result must be closed before accessing meta-data\"}\n\t}\n\n\treturn &r.metadata, nil\n}", "func (r *AWSMediaLiveChannel_InputAttachment) Metadata() map[string]interface{} {\n\treturn r._metadata\n}", "func (t *TOMLParser) Metadata() Metadata {\n\treturn t.metadata\n}", "func (bp *BasePayload) GetMetaData() *property.Configuration {\n\treturn bp.Metadata\n}", "func (c *jsiiProxy_CfnApp) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (p *Provider) GetMetadata(metric v1alpha1.Metric) map[string]string {\n\treturn nil\n}", "func (c *jsiiProxy_CfnStudio) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func ToMetadataInfo(metadata types.MetadataInfo) *api.Metadata {\n\treturn &api.Metadata{\n\t\tClock: metadata.Clock,\n\t\tData: metadata.Data,\n\t}\n}", "func (o GroupDiagnosticsLogAnalyticsOutput) Metadata() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v GroupDiagnosticsLogAnalytics) map[string]string { return v.Metadata }).(pulumi.StringMapOutput)\n}", "func (file *File) Metadata() (details *common.File) {\n\tfile.lock.Lock()\n\tdefer file.lock.Unlock()\n\n\treturn file.metadata\n}", "func (trs *Transaction) GetMetaData() stored_files.File {\n\treturn trs.MetaData\n}", "func (p *Parser) GetMetadata() Dataset {\n\treturn p.metadata\n}", "func (o ProjectMetadataOutput) Metadata() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *ProjectMetadata) pulumi.StringMapOutput { return v.Metadata }).(pulumi.StringMapOutput)\n}", "func (client *Client) GetActivityDetails(token string) (ActivityDetails, []string) {\n\t_, activity, errStrings := client.getActivityDetails(token)\n\treturn activity, errStrings\n}", "func NewMetadata() *Metadata {\n\treturn &Metadata{\n\t\tIsDownloadable: true,\n\t}\n}", "func (o DashboardLensOutput) Metadata() pulumi.MapOutput {\n\treturn o.ApplyT(func(v DashboardLens) map[string]interface{} { return v.Metadata }).(pulumi.MapOutput)\n}", "func (o InstanceOutput) Metadata() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.MapOutput { return v.Metadata }).(pulumi.MapOutput)\n}", "func (o InstanceOutput) Metadata() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringMapOutput { return v.Metadata }).(pulumi.StringMapOutput)\n}", "func (sd *SiaDir) Metadata() Metadata {\n\tsd.mu.Lock()\n\tdefer sd.mu.Unlock()\n\treturn sd.metadata\n}", "func (r boltResult) Metadata() map[string]interface{} {\n\treturn r.metadata\n}", "func (p *Policy) Metadata() *interop.ContractMD {\n\treturn &p.ContractMD\n}", "func (*YouTube) GetMetadata(url string) (*Metadata, error) {\n\tvideoInfo, err := ytdl.GetVideoInfo(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tformat := videoInfo.Formats.Extremes(ytdl.FormatAudioBitrateKey, true)[0]\n\n\tvideoURL, err := videoInfo.GetDownloadURL(format)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tytCall := youtube.NewVideosService(botData.BotClients.YouTube).\n\t\tList(\"snippet,contentDetails\").\n\t\tId(videoInfo.ID)\n\n\tytResponse, err := ytCall.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tduration, err := isoduration.FromString(ytResponse.Items[0].ContentDetails.Duration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetadata := &Metadata{\n\t\tTitle: videoInfo.Title,\n\t\tDisplayURL: url,\n\t\tStreamURL: videoURL.String(),\n\t\tDuration: duration.ToDuration().Seconds(),\n\t\tArtworkURL: videoInfo.GetThumbnailURL(\"maxresdefault\").String(),\n\t\tThumbnailURL: videoInfo.GetThumbnailURL(\"default\").String(),\n\t}\n\n\tvideoAuthor := &MetadataArtist{\n\t\tName: ytResponse.Items[0].Snippet.ChannelTitle,\n\t\tURL: \"https://youtube.com/channel/\" + ytResponse.Items[0].Snippet.ChannelId,\n\t}\n\tmetadata.Artists = append(metadata.Artists, *videoAuthor)\n\n\treturn metadata, nil\n}", "func (manager *Manager) GetMetadata() Metadata {\n\tmanager.metaWG.Wait()\n\treturn manager.metadata\n}", "func (t *TXNTrigger) Metadata() *trigger.Metadata {\n\treturn t.metadata\n}", "func (_IRMAScheme *IRMASchemeSession) Metadata() ([]byte, error) {\n\treturn _IRMAScheme.Contract.Metadata(&_IRMAScheme.CallOpts)\n}", "func (o ServiceResponseOutput) MetadataManagementActivity() MetadataManagementActivityResponseOutput {\n\treturn o.ApplyT(func(v ServiceResponse) MetadataManagementActivityResponse { return v.MetadataManagementActivity }).(MetadataManagementActivityResponseOutput)\n}", "func (o *IamServiceProviderAllOf) GetMetadata() string {\n\tif o == nil || o.Metadata == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Metadata\n}", "func (c *jsiiProxy_CfnWorkflow) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func Metadata(ctx context.Context) metadata.Metadata {\n\tif tr, ok := FromServerContext(ctx); ok {\n\t\treturn tr.Metadata()\n\t}\n\treturn metadata.Metadata{}\n}", "func (o DashboardPartsOutput) Metadata() pulumi.AnyOutput {\n\treturn o.ApplyT(func(v DashboardParts) interface{} { return v.Metadata }).(pulumi.AnyOutput)\n}", "func (op *RunJobOperation) Metadata() (*runpb.Execution, error) {\n\tvar meta runpb.Execution\n\tif err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn &meta, nil\n}", "func GetMetadata(url string) (ytdl.VideoInfo, error) {\n\tvideoInfo, err := ytdl.GetVideoInfo(url)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn ytdl.VideoInfo{}, err\n\t}\n\treturn *videoInfo, nil\n}", "func (t *Commit) GetMetadata() string {\n\tif t.Metadata == nil {\n\t\treturn \"\"\n\t}\n\treturn *t.Metadata\n}", "func (p *FrameLease) Metadata() []byte {\n\tif !p.header.Flag().Check(FlagMetadata) {\n\t\treturn nil\n\t}\n\treturn p.body.Bytes()[8:]\n}", "func (o DashboardLensResponseOutput) Metadata() pulumi.MapOutput {\n\treturn o.ApplyT(func(v DashboardLensResponse) map[string]interface{} { return v.Metadata }).(pulumi.MapOutput)\n}", "func GetActivationMetadata(key string, value *string) int {\n\tcKey := goToCString(key)\n\tvar cValue = getCArray()\n\tstatus := C.GetActivationMetadata(cKey, &cValue[0], maxCArrayLength)\n\t*value = ctoGoString(&cValue[0])\n\tfreeCString(cKey)\n\treturn int(status)\n}", "func (o PriorityClassOutput) Metadata() metav1.ObjectMetaOutput {\n\treturn o.ApplyT(func(v *PriorityClass) metav1.ObjectMetaOutput { return v.Metadata }).(metav1.ObjectMetaOutput)\n}", "func (c *jsiiProxy_CfnDeployment) GetMetadata(key *string) interface{} {\n\tvar returns interface{}\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getMetadata\",\n\t\t[]interface{}{key},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (p *FrameMetadataPush) Metadata() []byte {\n\treturn p.body.Bytes()\n}", "func (e *Edge) Metadata() Metadata {\n\treturn &e.metadata\n}", "func NewMetadata() Metadata {\n\treturn make(map[MetadataKey]interface{})\n}", "func (t *Table) Metadata(ctx context.Context) (*TableMetadata, error) {\n\treturn t.c.service.getTableMetadata(ctx, t.ProjectID, t.DatasetID, t.TableID)\n}", "func (r *presentationResolver) Metadata(ctx context.Context, obj *deprecated.Presentation) ([]models.StringEntry, error) {\n\tvar ret []models.StringEntry\n\tfor k, v := range obj.Metadata {\n\t\tret = append(ret, models.StringEntry{K: k, V: v})\n\t}\n\tsort.Slice(ret, func(i, j int) bool {\n\t\treturn ret[i].K < ret[j].K\n\t})\n\treturn ret, nil\n}" ]
[ "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.8149424", "0.81016266", "0.768566", "0.7655357", "0.7385168", "0.73647314", "0.7294074", "0.7238995", "0.70852596", "0.7020559", "0.68813634", "0.68264365", "0.6722788", "0.6642988", "0.65134573", "0.63594973", "0.63408536", "0.6282528", "0.62499654", "0.6225844", "0.62001514", "0.61444485", "0.61284184", "0.6110126", "0.6093706", "0.60887516", "0.608181", "0.60773486", "0.6061695", "0.60607916", "0.60508823", "0.60187304", "0.6013542", "0.59996766", "0.5960616", "0.5946408", "0.593866", "0.59347486", "0.59323984", "0.5929749", "0.5901588", "0.5900981", "0.58970654", "0.5893605", "0.58925205", "0.58875495", "0.58875495", "0.58770335", "0.5874548", "0.5866808", "0.5861632", "0.5859709", "0.5858415", "0.58523244", "0.58515096", "0.584975", "0.58496433", "0.58486587", "0.58419055", "0.5840124", "0.583672", "0.5829288", "0.58097", "0.5801712", "0.57927376", "0.57922727", "0.57906413", "0.5772687", "0.57716143", "0.5764569", "0.576194", "0.57422143", "0.57420194", "0.57382846", "0.5732025", "0.5727488", "0.57268846", "0.5724838", "0.5712641", "0.56999", "0.5692713", "0.5691058", "0.5672886", "0.56715584", "0.566751", "0.5666914", "0.5664676", "0.56625974", "0.5659581", "0.5649681", "0.563679" ]
0.76424104
13
time complexity: O((mn+1)n), where m is len(haystack), n is len(needle) space complexity: O(1)
func strStr(haystack string, needle string) int { if 0 == len(needle) { return 0 } for i, j := 0, 0; i <= len(haystack)-len(needle); i++ { for j = 0; j < len(needle); j++ { if haystack[i+j] != needle[j] { break } } if len(needle) == j { return i } } return -1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func search(ints []uint32, needle uint32) int {\n\t// Define f(-1) == false and f(n) == true.\n\t// Invariant: f(i-1) == false, f(j) == true.\n\ti, j := 0, len(ints)\n\tfor i < j {\n\t\th := int(uint(i+j) >> 1) // avoid overflow when computing h\n\t\t// i ≤ h < j\n\t\tif !(ints[h] >= needle) {\n\t\t\ti = h + 1 // preserves f(i-1) == false\n\t\t} else {\n\t\t\tj = h // preserves f(j) == true\n\t\t}\n\t}\n\t// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.\n\treturn i\n}", "func strStr(haystack string, needle string) int {\n if needle == \"\" {\n return 0\n }\n if haystack == \"\" {\n return -1\n }\n lh := len(haystack)\n ln := len(needle)\n check := needle[0]\n start := 0\n \n for start + ln <= lh {\n if string(haystack[start:start+ln]) == needle {\n return start\n }\n start++\n for start < lh && haystack[start] != check {\n start++\n }\n }\n return -1\n}", "func Find(needle string, haystack []string) ([]string, error) {\n\tresult := make([]string, len(haystack))\n\ttemp := make([]string, 0, len(result))\n\tcopy(result, haystack)\n\n\tfor i, l := 0, len(needle); i < l; i++ {\n\t\tfor j := 0; j < len(result); j++ {\n\t\t\tif i >= len(result[j]) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif needle[i] == result[j][i] {\n\t\t\t\ttemp = append(temp, result[j])\n\t\t\t}\n\t\t}\n\n\t\tif len(temp) == 0 {\n\t\t\tif i == 0 {\n\t\t\t\treturn make([]string, 0), nil\n\t\t\t}\n\n\t\t\treturn result, nil\n\t\t}\n\n\t\tresult, temp = temp, make([]string, 0, len(result))\n\t}\n\n\treturn result, nil\n}", "func binarySearch(needle int, haystack []int) bool {\n\t// len(hyastack) == 10\n\tlow := 0\n\t//hiigh == 9\n\thigh := len(haystack) - 1\n\tfmt.Printf(\"begin low %d \\n\", low)\n\tfmt.Printf(\"begin high %d \\n\", high)\n\n\t//low less than high\n\tfor low <= high {\n\t\t// find middle total/2 == 9/2 == 4; (then 7... 5... 6)\n\t\tmedian := ((low + high) / 2)\n\t\tfmt.Printf(\"top for loop median %d \\n\", median)\n\t\tfmt.Printf(\"top for loop low %d \\n\", low)\n\t\tfmt.Printf(\"top for loop high %d \\n\", high)\n\n\t\t//middle of list less than search term\n\t\t// split the list in half and serch halfsies\n\t\t// haystack value less than search term...\n\t\tif haystack[median] < needle {\n\t\t\t//move into end of list\n\t\t\t// low == 0\n\t\t\tlow = median + 1\n\t\t\t// low == 5; (then 6)\n\t\t\tfmt.Printf(\"< needle low %d \\n\", low)\n\t\t} else {\n\t\t\t//move into start of list\n\t\t\t// high == 9\n\t\t\thigh = median - 1\n\t\t\t// high == 6; (then 5)\n\t\t\tfmt.Printf(\"> needle high %d \\n\", high)\n\t\t}\n\t}\n\tfmt.Printf(\"out of for loop low %d \\n\", low)\n\tfmt.Printf(\"out of for loop high %d \\n\", high)\n\tif low == len(haystack) || haystack[low] != needle {\n\t\treturn false\n\t}\n\tfmt.Printf(\"term== %d\\n\", haystack[low])\n\treturn true\n}", "func binarySearch(needle int, haystack []int) bool {\n\n\tlow := 0\n\thigh := len(haystack) - 1\n\n\tfor low <= high {\n\t\t// Establish the initial median of the list.\n\t\tmedian := (low + high) / 2\n\n\t\tif haystack[median] < needle {\n\t\t\t// Check if the needle is higher than the initial median.\n\t\t\t// If so, eliminate the everything before the median.\n\t\t\tlow = median + 1\n\t\t} else {\n\t\t\t// If not, eliminate everything after the median.\n\t\t\thigh = median - 1\n\t\t}\n\t}\n\t// If the low is the length of the haystack, then there are 0 items in the list and there is no need to search.\n\t// The way the search operates, low will = needle\n\t// if low == len(haystack), the end of the list was reached and the item being searched was not found.\n\tif low == len(haystack) || haystack[low] != needle {\n\t\treturn false\n\t}\n\tfmt.Println(len(haystack))\n\n\treturn true\n}", "func strStr(haystack string, needle string) int {\n\tif needle == \"\" {\n\t\treturn 0\n\t}\n\n\tif len(haystack) < len(needle) {\n\t\treturn -1\n\t}\n\n\tfor i := 0; i <= len(haystack)-len(needle); i++ {\n\t\tfor j := 0; j < len(needle) && needle[j] == haystack[j+i]; j++ {\n\t\t\tif j == len(needle)-1 {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn -1\n}", "func search(s []int, e int) int {\n\tstart := 0\n\tend := len(s)\n\tfor start < end {\n\t\ti := start + (end - start)/2\n\t\tif e > s[i] {\n\t\t\tstart = i+1\n\t\t} else if e < s[i] {\n\t\t\tend = i\n\t\t} else {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func search(nums []int, target int) int {\n\tl, r, mid := 0, len(nums)-1, len(nums)/2\n\tfor l <= r {\n\t\t//fmt.Println(l, r, mid, target, nums)\n\t\tif nums[mid] == target {\n\t\t\treturn mid\n\t\t}\n\t\tif nums[l] < nums[mid] && nums[mid] > target && nums[l] <= target { // 左边有序\n\t\t\tr = mid - 1\n\t\t} else if nums[l] > nums[mid] && (nums[l] <= target || nums[mid] > target) {\n\t\t\tr = mid - 1\n\t\t} else {\n\t\t\tl = mid + 1\n\t\t}\n\t\tmid = (r + l) / 2\n\t}\n\treturn -1\n}", "func search(nums []int, target int) int {\n\tif len(nums) == 0 {\n\t\treturn -1\n\t}\n\tfmt.Println(nums)\n\n\tlow := 0\n\thigh := len(nums) - 1\n\n\tfor low < high {\n\t\tmid := (low + high) / 2\n\t\t//case 1 mid == target\n\t\tif nums[mid] == target {\n\t\t\treturn mid\n\t\t}\n\n\t\tfmt.Println(\"low: \", low, \"hi\", high, \"nums[mid]: \", nums[mid], \"mid: \", mid, \"a[low]\", nums[low])\n\n\t\t// target < a[mid], which can be on either side.\n\t\t// so how to decide which side to go???\n\t\t//case 2, if a[mid] < a[high], then we know a[mid....high]\n\t\t// is sorted. so, just call BS on a\n\t\tif nums[mid] < nums[high] {\n\t\t\t// target in a[mid...high]\n\t\t\tif target >= nums[mid] && target <= nums[high] {\n\t\t\t\tlow = mid\n\t\t\t} else if target >= nums[low] {\n\t\t\t\t//target in a[low...mid-1]\n\t\t\t\thigh = mid - 1\n\t\t\t}\n\t\t\t//\tcontinue\n\t\t}\n\t\t//case 3, if a[mid] > a[low], then we know the a[low....mid] is sorted\n\t\tif nums[mid] > nums[low] {\n\t\t\tif target <= nums[mid] && target >= nums[low] {\n\t\t\t\thigh = mid - 1\n\t\t\t} else if target <= nums[high] {\n\t\t\t\tlow = mid + 1\n\t\t\t} else {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\tif high == low && nums[high] == target {\n\t\t\treturn high\n\t\t}\n\t}\n\treturn -1\n}", "func search(nums []int, target int) int {\n\tlow, high := 0, len(nums)-1\n\tvar mid int\n\tfor low <= high {\n\t\tmid = (low + high) / 2\n\t\tif nums[mid] < target {\n\t\t\tlow = mid + 1\n\t\t} else if nums[mid] > target {\n\t\t\thigh = mid - 1\n\t\t} else {\n\t\t\treturn mid\n\t\t}\n\t}\n\n\treturn -1\n}", "func strStr(haystack string, needle string) int {\n\tif needle == \"\" {\n\t\treturn 0\n\t}\n\n\tnlen := len(needle)\n\thlen := len(haystack)\n\tif nlen == hlen {\n\t\tif haystack == needle {\n\t\t\treturn 0\n\t\t}\n\t}\n\n\tfirstN := needle[0]\n\n\tfor i := 0; i <= hlen-nlen; i++ {\n\t\tif haystack[i] == firstN {\n\t\t\tif haystack[i:i+nlen] == needle {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1\n}", "func searchLeft(a []uint, x uint) int {\n\tlo := 0\n\thi := len(a)\n\tfor lo < hi {\n\t\tmid := (lo + hi) / 2\n\t\tif a[mid] < x {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\n\treturn lo\n}", "func Search(input string, pattern string) []int {\n\tvar (\n\t\tM = len(pattern)\n\t\tN = len(input)\n\t)\n\n\tif N == 0 || M == 0 {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tresult = make([]int, 0)\n\t\tl = 0\n\t\ti = 1\n\t\tj = 0\n\t\tlps = make([]int, M)\n\t)\n\n\tfor ; i < M; i++ {\n\t\tfor {\n\t\t\tif pattern[i] == pattern[l] {\n\t\t\t\tl++\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif l == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl = lps[l-1]\n\t\t}\n\t\tlps[i] = l\n\t}\n\n\ti = 0\n\tj = 0\n\n\tfor ; i < N; i++ {\n\t\tfor {\n\t\t\tif pattern[j] == input[i] {\n\t\t\t\tj++\n\n\t\t\t\tif j == M {\n\t\t\t\t\tresult = append(result, i-j+1)\n\t\t\t\t\tj = lps[j-1]\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif j > 0 {\n\t\t\t\tj = lps[j-1]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn result\n}", "func FindSubstring(s string, words []string) []int {\n\t// 排除特殊情况\n\tif len(words) == 0 {\n\t\treturn nil\n\t}\n\twordLen := len(words[0])\n\tcombLen := len(words) * wordLen\n\tif len(s) < combLen {\n\t\treturn nil\n\t}\n\n\tvar indices []int\n\tm := make(map[string]int)\n\tfor _, word := range words {\n\t\tm[word]++\n\t}\n\t// 分wordLen批次比较子串\n\tfor i := 0; i < wordLen; i++ {\n\t\tcounter := make(map[string]int)\n\t\tl, r := i, i\n\t\tnum := 0\n\t\tfor r+wordLen <= len(s) {\n\t\t\tword := s[r : r+wordLen]\n\t\t\tr += wordLen\n\t\t\t// 若word在words中不存在\n\t\t\tif m[word] == 0 {\n\t\t\t\tl = r\n\t\t\t\tnum = 0\n\t\t\t\tfor word := range counter {\n\t\t\t\t\tcounter[word] = 0\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcounter[word]++\n\t\t\tnum++\n\t\t\t// 若word重复了\n\t\t\tfor counter[word] > m[word] {\n\t\t\t\tcounter[s[l:l+wordLen]]--\n\t\t\t\tl += wordLen\n\t\t\t\tnum--\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// 若子串中的单词与words中的单词完全匹配\n\t\t\tif num == len(words) {\n\t\t\t\tindices = append(indices, l)\n\t\t\t\tcounter[s[l:l+wordLen]]--\n\t\t\t\tnum--\n\t\t\t\tl += wordLen\n\t\t\t}\n\t\t}\n\t}\n\n\treturn indices\n}", "func findSubstring(s string, words []string) []int {\n\tres := []int{}\n\tls, lw := len(s), len(words)\n\tif lw == 0 || ls == 0 {\n\t\treturn res\n\t}\n\n\tmp := make(map[string]int)\n\tfor _, v := range words {\n\t\tmp[v]++\n\t}\n\n\twLen := len(words[0])\n\twindow := wLen * lw\n\tfor i := 0; i < wLen; i++ {\n\t\tfor j := i; j+window <= ls; j = j + wLen {\n\t\t\ttmp := s[j : j+window]\n\t\t\ttp := make(map[string]int)\n\t\t\tfor k := lw - 1; k >= 0; k-- {\n\t\t\t\t// get the word from tmp\n\t\t\t\tword := tmp[k*wLen : (k+1)*wLen]\n\t\t\t\tcount := tp[word] + 1\n\t\t\t\tif count > mp[word] {\n\t\t\t\t\tj = j + k*wLen\n\t\t\t\t\tbreak\n\t\t\t\t} else if k == 0 {\n\t\t\t\t\tres = append(res, j)\n\t\t\t\t} else {\n\t\t\t\t\ttp[word] = count\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func FindSubstring(A string , B []string ) []int {\n\n\twm := map[string]int{}\n\tmA := make([]int, 26)\n\tmB := make([]int, 26)\n\n\t//Find the total number of characters in B\n\tbTotalLen := 0\n\tfor i := range B {\n\t\tfor j := range B[i] {\n\t\t\t//Map for characters in list B\n\t\t\tmB[B[i][j] - 'a'] = mB[B[i][j] - 'a'] + 1\n\t\t\tbTotalLen++\n\t\t}\n\t\t//Map of words in list B\n\t\twm[B[i]]++\n\t}\n\n\tvar result []int\n\tfor i := 0; i < len(A); i++ {\n\t\t//Add current character from the substring\n\t\tmA[A[i] - 'a'] = mA[A[i] - 'a'] + 1\n\n\t\t//Skip till first position where solution can be found\n\t\tif i < bTotalLen- 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t//if substring has same characters as list B\n\t\tif equals(mB, mA) {\n\t\t\t//Check if the substring has permutations of words from list B\n\t\t\tif hasAllWords(A[i -bTotalLen+ 1:i+1], copy(wm)) {\n\t\t\t\tresult = append(result, i -bTotalLen+ 1)\n\t\t\t}\n\t\t}\n\n\t\t//Remove first character from the substring\n\t\tp := A[i -bTotalLen+ 1]\n\t\tmA[p - 'a'] = mA[p - 'a'] - 1\n\t}\n\n\treturn result\n}", "func StrStr(haystack string, needle string) int {\n\tif len(needle) == 0 {\n\t\treturn 0\n\t}\n\n\thead, tail := 0, len(needle)-1\n\tfor tail < len(haystack) {\n\t\tif haystack[head:tail+1] == needle {\n\t\t\treturn head\n\t\t}\n\n\t\thead++\n\t\ttail++\n\t}\n\n\treturn -1\n}", "func binarySearch(target int, slice []int) int {\n\tleft := 0\n\tright := len(slice) - 1\n\tfor left <= right {\n\t\tmiddle := left + (right-left)/2\n\t\tif slice[middle] == target {\n\t\t\treturn middle\n\t\t} else if slice[middle] < target {\n\t\t\t// search right\n\t\t\tleft = middle + 1\n\t\t} else {\n\t\t\t//search left\n\t\t\tright = middle - 1\n\t\t}\n\t}\n\treturn -1\n}", "func BinarySearch(nums []int, target int) int {\n\n\tll := len(nums)\n\n\tif ll < 3 {\n\t\tfor i, k := range nums {\n\t\t\tif k == target {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\tstart, mid := 0, 0\n\n\tif ll%2 == 0 {\n\t\tmid = ll/2 - 1\n\t} else {\n\t\tmid = ll / 2\n\t}\n\n\tmax := int(math.Log2(float64(ll)))\n\ttimes := 0\n\n\tfor {\n\n\t\tres := nums[mid] - target\n\n\t\tif res > 0 {\n\t\t\tmid = (start + mid) / 2\n\t\t} else if res < 0 {\n\t\t\tmid = (mid + ll) / 2\n\t\t} else {\n\t\t\treturn mid\n\t\t}\n\n\t\tif times == max {\n\t\t\treturn -1\n\t\t}\n\t\ttimes++\n\t}\n}", "func (a *StringArray) search(v int64) int {\n\t// Define: f(x) → a.Timestamps[x] < v\n\t// Define: f(-1) == true, f(n) == false\n\t// Invariant: f(lo-1) == true, f(hi) == false\n\tlo := 0\n\thi := a.Len()\n\tfor lo < hi {\n\t\tmid := int(uint(lo+hi) >> 1)\n\t\tif a.Timestamps[mid] < v {\n\t\t\tlo = mid + 1 // preserves f(lo-1) == true\n\t\t} else {\n\t\t\thi = mid // preserves f(hi) == false\n\t\t}\n\t}\n\n\t// lo == hi\n\treturn lo\n}", "func binarySearchImpl(a []int, start, end, el int, recursionDepthLeft int) int {\n\tif recursionDepthLeft == 0 {\n\t\tpanic(\"recusion too deep\")\n\t}\n\t// fmt.Printf(\"\\t%v (%d %d) %d\\n\", a[start:end], start, end, el)\n\n\tswitch end - start {\n\tcase 0:\n\t\t// this should never happen\n\t\treturn -1\n\tcase 1:\n\t\tif a[start] == el {\n\t\t\treturn start\n\t\t} else {\n\t\t\treturn -1\n\t\t}\n\tdefault:\n\t\t// the core problem of binary search: how to split the array\n\t\t// so that it's always smaller than it was (no recursive loop)\n\t\t//\n\t\t// the idea about the solution is to split the thinking about the problem\n\t\t// into 2 separate sub-problems:\n\t\t// - how to split array into 2 smaller ones\n\t\t// - how to pick the proper array for later\n\t\t//\n\t\t// After the first problem is solved properly, second is simple \"if\" on indices.\n\t\t// The idea behind the split:\n\t\t// - 1st sub-array must be equal or larger by one than the 2nd:\n\t\t// [1 2 3 4] => [1 2] + [3 4]\n\t\t// [1 2 3] => [1 2] + [3]\n\t\t// [1 2] => [1] + [2]\n\t\tmid := (end + start + 1) / 2\n\t\tif el < a[mid] {\n\t\t\treturn binarySearchImpl(a, start, mid, el, recursionDepthLeft-1)\n\t\t} else {\n\t\t\treturn binarySearchImpl(a, mid, end, el, recursionDepthLeft-1)\n\t\t}\n\t}\n\n}", "func BiSearch(nums []int, target int) int {\n\tfor i := range nums {\n\t\tif target > nums[i] {\n\t\t\ti ++\n\t\t} else if target == nums[i] {\n\t\t\treturn i\n\t\t} else if target < nums [i]{\n\t\t\tif i > 0 {\n\t\t\t\ti--\n\t\t\t}\n\t\t\treturn -1\n\t\t}\n\t}\n\treturn -1\n}", "func RecursionBinSearch(data []int, target int) int {\n\tif len(data) == 0 {\n\t\treturn math.MinInt64\n\t}\n\tif len(data) == 1 && data[0] == target {\n\t\treturn 0\n\t} else if len(data) == 1 {\n\t\treturn math.MinInt64\n\t}\n\n\tleft := 0\n\tright := len(data)\n\tmid := left + (right-left)/2\n\tif data[mid] > target {\n\t\tright = mid\n\t} else if data[mid] == target {\n\t\treturn mid\n\t} else {\n\t\tleft = mid + 1\n\t}\n\n\treturn left + RecursionBinSearch(data[left:right], target)\n}", "func (p BigIntSlice) Search(x *big.Int) int { return SearchBigInts(p, x) }", "func BinarySearch(a []int, target int) int {\n\tlow := 0\n\thigh := len(a) - 1\n\tfor low <= high {\n\t\tlog.Println(\"high => \", high, \"low => \", low)\n\t\tmiddle := (high + low) / 2\n\t\tlog.Println(\"middle Element \", middle)\n\t\tif a[middle] > target {\n\t\t\thigh = middle - 1\n\t\t\tmiddle = (high + low) / 2\n\t\t} else if a[middle] < target {\n\t\t\tlow = middle + 1\n\t\t\tmiddle = (high + low) / 2\n\t\t} else {\n\t\t\treturn middle\n\t\t}\n\t}\n\treturn -1\n}", "func SearchInsert(nums []int, target int) int {\n\tnumsLen := len(nums)\n\tif numsLen == 0 {\n\t\treturn 0\n\t}\n\ti := 0\n\tj := numsLen\n\tmid := 0\n\tfor i <= j {\n\t\tmid = (i + j) / 2\n\t\tmidNumber := nums[mid]\n\t\tif midNumber == target {\n\t\t\treturn mid\n\t\t}\n\t\tif midNumber < target {\n\t\t\tif mid == numsLen-1 {\n\t\t\t\treturn numsLen\n\t\t\t}\n\t\t\tif target < nums[mid+1] {\n\t\t\t\treturn mid + 1\n\t\t\t}\n\t\t\ti = mid + 1\n\t\t} else {\n\t\t\tif mid == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tif nums[mid-1] < target {\n\t\t\t\treturn mid\n\t\t\t}\n\t\t\tj = mid - 1\n\t\t}\n\t}\n\treturn mid\n}", "func searchLinear(nums []uint, n uint) int {\n\tfor i := 0; i < len(nums); i++ {\n\t\tif nums[i] == n {\n\t\t\treturn int(n)\n\t\t}\n\t}\n\treturn -1\n}", "func findOdd(b []byte, m int, l int) result {\n\tif 0 == m {\n\t\treturn result{\n\t\t\tb: b[0:1],\n\t\t\tl: 1,\n\t\t}\n\t}\n\tif m == l {\n\t\tv := b[l-1 : l]\n\t\treturn result{\n\t\t\tb: v,\n\t\t\tl: len(v),\n\t\t}\n\t}\n\tmax := m + 1\n\tfor d := 1; d < max; d++ {\n\t\txi := m - d\n\t\tx := b[xi : xi+1]\n\t\tyi := m + d\n\t\ty := b[yi : yi+1]\n\t\tfmt.Println(\" m:\", m, string(b[m]))\n\t\tfmt.Println(\" x:\", xi, string(x[0]))\n\t\tfmt.Println(\" y:\", yi, string(y[0]))\n\t\tfmt.Println(\" range:\", string(b[xi:yi+1]))\n\t\tif x[0] != y[0] {\n\t\t\tv := b[m+1-d : m+d]\n\t\t\treturn result{\n\t\t\t\tb: v,\n\t\t\t\tl: len(v),\n\t\t\t}\n\t\t}\n\t}\n\tv := b[m-m : m+(m)+1]\n\treturn result{\n\t\tb: v,\n\t\tl: len(v),\n\t}\n}", "func binarySearch(a []Stake, odds float64) (index int) {\n\tmid := len(a) / 2\n\tswitch {\n\tcase len(a) == 0:\n\t\tindex = 0 // not found\n\tcase a[mid].Odds > odds:\n\t\tindex = binarySearch(a[:mid], odds)\n\tcase a[mid].Odds < odds:\n\t\tindex = binarySearch(a[mid+1:], odds)\n\t\tindex += mid + 1\n\tdefault: // a[mid] == search\n\t\tindex = mid // found\n\t}\n\treturn\n}", "func Tianyun_searchRange(nums []int, target int) []int {\n\n\t//O(n)\n//\tstartIndex:=-1\n//\tcount:=0\n//\n//\tfor i:=0;i<len(nums);i++{\n//\t\tif count==0&&nums[i]==target{\n//\t\t\tstartIndex = i\n//\t\t\tcount++\n//\n//\t\t}else if nums[i]==target{\n//\t\t\tcount++\n//\t\t}\n//}\n//\n// if count==0{\n// \treturn []int{-1,-1}\n// }else{\n// \treturn []int{startIndex,startIndex+count}\n// }\n\n\n\n//O(logn)\nif len(nums)==0{\n\treturn []int{-1,-1}\n}\n startIndex:=-1\n left:=0\n right:=len(nums)-1\n\n for left +1 <right{\n \tmid:=(left+right)/2\n \tif nums[mid]>=target{\n right = mid\n\t\t}else{\n\t\t\tleft =mid+1\n\t\t}\n\t }\n\t if nums[left]==target{\n\t \tstartIndex =left\n\t }else if nums[right]==target{\n\t \tstartIndex = right\n\t }else{\n\t \treturn []int{-1,-1}\n\t }\n\n\n\tleft=0\n\tright=len(nums)-1\n\n\tfor left +1 <right{\n\t\tmid:=(left+right)/2\n\t\tif nums[mid]<=target{\n\t\t\tleft = mid\n\t\t}else{\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tif nums[right]==target{\n\t\treturn []int{startIndex,right}\n\t}else if nums[left]==target{\n\t\treturn []int{startIndex,left}\n\t}else{\n\t\treturn []int{-1,-1}\n\t}\n}", "func KMPSearch(content string, pattern string) int {\n\tcr, pr := []rune(content), []rune(pattern)\n\tnext := GetNext(pr)\n\ti, j, sl, pl := 0, 0, len(cr), len(pr)\n\tfor i < sl && j < pl {\n\t\tif j == -1 || cr[i] == pr[j] {\n\t\t\ti, j = i+1, j+1\n\t\t} else {\n\t\t\tj = next[j]\n\t\t}\n\t}\n\tif j == pl {\n\t\treturn i - j\n\t}\n\treturn -1\n\n}", "func searchRange(nums []int, target int) []int {\n\tans := []int{-1, -1}\n\tif len(nums) == 0 {\n\t\treturn ans\n\t}\n\tfirstHit := -1\n\tlo, hi, mid := 0, len(nums)-1, 0\n\tfor lo <= hi {\n\t\tmid = (lo + hi) >> 1\n\t\tif nums[mid] == target {\n\t\t\tfirstHit = mid\n\t\t\tbreak\n\t\t} else if nums[mid] < target {\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid - 1\n\t\t}\n\t}\n\n\tif firstHit == -1 {\n\t\treturn ans\n\t}\n\n\tsearchBoundary := func(l, h, t int) int {\n\t\tmid := 0\n\t\tfor l < h {\n\t\t\tmid = (l + h) >> 1\n\t\t\tif nums[mid] < t {\n\t\t\t\tl = mid + 1\n\t\t\t} else {\n\t\t\t\th = mid\n\t\t\t}\n\t\t}\n\t\treturn l\n\t}\n\n\tans[0] = searchBoundary(lo, firstHit, target)\n\tans[1] = searchBoundary(firstHit, hi+1, target+1) - 1\n\treturn ans\n}", "func find(input, target string, start, end int) bool {\n\tlength := len(input)\n\tif length < end || start < 0 {\n\t\treturn false\n\t}\n\n\treturn input[start:end] == target\n}", "func findEven(b []byte, m int, l int) result {\n\tif 0 == m {\n\t\treturn result{\n\t\t\tb: b[0:1],\n\t\t\tl: 1,\n\t\t}\n\t}\n\tif m == l {\n\t\tv := b[l-1 : l]\n\t\treturn result{\n\t\t\tb: v,\n\t\t\tl: len(v),\n\t\t}\n\t}\n\tmax := m + 1\n\tfmt.Println(\"max?\", max, len(b))\n\tfor d := 1; d < max; d++ {\n\t\txi := m - d\n\t\tx := b[xi : xi+1]\n\t\tyi := m + d - 1\n\t\ty := b[yi : yi+1]\n\t\tfmt.Println(\" m:\", m, string(b[m]))\n\t\tfmt.Println(\" x:\", xi, string(x[0]))\n\t\tfmt.Println(\" y:\", yi, string(y[0]))\n\t\tfmt.Println(\" range:\", string(b[xi:yi+1]))\n\t\tif x[0] != y[0] {\n\t\t\tv := b[m+1-d : m+d-1]\n\t\t\treturn result{\n\t\t\t\tb: v,\n\t\t\t\tl: len(v),\n\t\t\t}\n\t\t}\n\t}\n\tv := b[m-m : m+(m)]\n\treturn result{\n\t\tb: v,\n\t\tl: len(v),\n\t}\n}", "func find(a []string, x string) int {\n\tfor i, n := range a {\n\t\tif x == n {\n\t\t\treturn i\n\t\t}\n\n\t}\n\treturn len(a)\n}", "func StrStr(haystack string, needle string) int {\n\tif len(needle) == 0 {\n\t\treturn 0\n\t}\n\n\tvar i, j int\n\t//outer loop is for iterating on haystack\n\tfor i = 0; i < len(haystack)-len(needle); i++ {\n\t\t//inner loop is for checking every haystack char with needle char\n\t\tfor j = 0; j < len(needle); j++ {\n\t\t\tif haystack[i+j] != needle[j] {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif j == len(needle) {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n\n}", "func (idx *deltaIndex) findMatch(src, tgt []byte, tgtOffset int) (srcOffset, l int) {\n\tif len(tgt) < tgtOffset+s {\n\t\treturn 0, len(tgt) - tgtOffset\n\t}\n\n\tif len(src) < blksz {\n\t\treturn 0, -1\n\t}\n\n\tif len(tgt) >= tgtOffset+s && len(src) >= blksz {\n\t\th := hashBlock(tgt, tgtOffset)\n\t\ttIdx := h & idx.mask\n\t\teIdx := idx.table[tIdx]\n\t\tif eIdx != 0 {\n\t\t\tsrcOffset = idx.entries[eIdx]\n\t\t} else {\n\t\t\treturn\n\t\t}\n\n\t\tl = matchLength(src, tgt, tgtOffset, srcOffset)\n\t}\n\n\treturn\n}", "func inSlice(needle string, haystack []string) bool {\n\tfor _, value := range haystack {\n\t\tif value == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func ld(s, t string, ignoreCase bool) int {\n\tif ignoreCase {\n\t\ts = strings.ToLower(s)\n\t\tt = strings.ToLower(t)\n\t}\n\td := make([][]int, len(s)+1)\n\tfor i := range d {\n\t\td[i] = make([]int, len(t)+1)\n\t}\n\tfor i := range d {\n\t\td[i][0] = i\n\t}\n\tfor j := range d[0] {\n\t\td[0][j] = j\n\t}\n\tfor j := 1; j <= len(t); j++ {\n\t\tfor i := 1; i <= len(s); i++ {\n\t\t\tif s[i-1] == t[j-1] {\n\t\t\t\td[i][j] = d[i-1][j-1]\n\t\t\t} else {\n\t\t\t\tmin := d[i-1][j]\n\t\t\t\tif d[i][j-1] < min {\n\t\t\t\t\tmin = d[i][j-1]\n\t\t\t\t}\n\t\t\t\tif d[i-1][j-1] < min {\n\t\t\t\t\tmin = d[i-1][j-1]\n\t\t\t\t}\n\t\t\t\td[i][j] = min + 1\n\t\t\t}\n\t\t}\n\n\t}\n\treturn d[len(s)][len(t)]\n}", "func stringBinarySearch(slice []string, elem string) int {\n\tidx := sort.SearchStrings(slice, elem)\n\n\tif idx != len(slice) && slice[idx] == elem {\n\t\treturn idx\n\t} else {\n\t\treturn -1\n\t}\n}", "func linearSearch(data []int, target int) int {\n\tfor index, v := range data {\n\t\tif v == target {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func binarySearch(nums []int, target int) bool {\n\t// Base case\n\tif len(nums) == 1 {\n\t\tif nums[0] == target {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Recursion step\n\tm := len(nums) / 2\n\n\tif nums[m] == target {\n\t\treturn true\n\t}\n\n\tif nums[m] < target {\n\t\treturn binarySearch(nums[m:], target)\n\t} else {\n\t\treturn binarySearch(nums[:m], target)\n\t}\n\n\treturn false\n}", "func d(i, j int, a, b string) int {\n\tmin_v := 100\n\n\tcost := 1\n\tif a[i] == b[j] {\n\t\tcost = 0\n\t}\n\n\tif i == j && j == 0 {\n\t\tmin_v = 0\n\t}\n\tif i > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j, a, b) + 1)\n\t}\n\tif j > 0 {\n\t\tmin_v = min(min_v, d(i, j - 1, a, b) + 1)\n\t}\n\tif i > 0 && j > 0 {\n\t\tmin_v = min(min_v, d(i - 1, j - 1, a, b) + cost)\n\t}\n\tif i > 1 && j > 1 && a[i] == b[j - 1] && a[i - 1] == b[j] {\n\t\tmin_v = min(min_v, d(i - 2, j - 2, a, b) + 1)\n\t}\n\n\treturn min_v\n\n}", "func searchRange(nums []int, target int) []int {\n\trst := make([]int, 2)\n\trst[0] = -1\n\trst[1] = -1\n\n\tif len(nums) == 0 {\n\t\treturn rst\n\t}\n\n\t// search for left bound\n\tl, r := 0, len(nums)-1\n\tmid := 0\n\tfor l < r {\n\t\tmid = l + (r-l)/2\n\t\tif nums[mid] < target {\n\t\t\tl = mid + 1\n\t\t} else {\n\t\t\t// target <= nums[mid]\n\t\t\tr = mid\n\t\t}\n\t}\n\tif nums[l] != target {\n\t\treturn rst\n\t} else {\n\t\trst[0] = l\n\t}\n\n\t// search for right bound\n\tl, r = 0, len(nums)-1\n\tfor l < r {\n\t\tmid = l + (r-l)/2 + 1 // trick to make mid bias to right bound\n\t\tif target < nums[mid] {\n\t\t\tr = mid - 1\n\t\t} else {\n\t\t\t// nums[mid] <= target\n\t\t\tl = mid\n\t\t}\n\t}\n\trst[1] = l\n\n\treturn rst\n}", "func SearchInts(s []int, k int) int {\n\tfor i, j := 0, len(s)-1; i <= j; {\n\t\th := (i + j) / 2\n\t\tswitch {\n\t\tcase s[h] < k:\n\t\t\ti = h + 1\n\t\tcase s[h] > k:\n\t\t\tj = h - 1\n\t\tdefault:\n\t\t\treturn h\n\t\t}\n\t}\n\treturn -1\n}", "func search(s string, m map[string]bool, sub string) {\n\tif s == \"\" {\n\t\tans = append(ans, sub)\n\t\treturn \n\t}\n\tfor j := 1; j < len(s)+1; j++ {\n\t\tif m[s[:j]] {\n\t\t\tif sub == \"\" {\n\t\t\t\tsearch(s[j:], m, s[:j])\n\t\t\t} else {\n\t\t\t\tsearch(s[j:], m, sub + \" \" + s[:j])\n\t\t\t}\n\t\t}\n\t}\n}", "func BinarySearch(target_map []int, value int) int {\n\n\tstart_index := 0\n\tend_index := len(target_map) - 1\n\n\tfor start_index <= end_index {\n\t\tmedian := (start_index + end_index) / 2\n\n\t\tif target_map[median] < value {\n\t\t\tstart_index = median + 1\n\t\t} else {\n\t\t\tend_index = median - 1\n\t\t}\n\t}\n\n\tif start_index == len(target_map) || target_map[start_index] != value {\n\t\treturn -1\n\t} else {\n\t\treturn start_index\n\t}\n}", "func (h *hashLongestMatchQuickly) FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult) {\n\tvar best_len_in uint = out.len\n\tvar cur_ix_masked uint = cur_ix & ring_buffer_mask\n\tvar key uint32 = h.HashBytes(data[cur_ix_masked:])\n\tvar compare_char int = int(data[cur_ix_masked+best_len_in])\n\tvar min_score uint = out.score\n\tvar best_score uint = out.score\n\tvar best_len uint = best_len_in\n\tvar cached_backward uint = uint(distance_cache[0])\n\tvar prev_ix uint = cur_ix - cached_backward\n\tvar bucket []uint32\n\tout.len_code_delta = 0\n\tif prev_ix < cur_ix {\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char == int(data[prev_ix+best_len]) {\n\t\t\tvar len uint = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScoreUsingLastDistance(uint(len))\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = uint(len)\n\t\t\t\t\tout.distance = cached_backward\n\t\t\t\t\tout.score = best_score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t\tif h.bucketSweep == 1 {\n\t\t\t\t\t\th.buckets[key] = uint32(cur_ix)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.bucketSweep == 1 {\n\t\tvar backward uint\n\t\tvar len uint\n\n\t\t/* Only one to look for, don't bother to prepare for a loop. */\n\t\tprev_ix = uint(h.buckets[key])\n\n\t\th.buckets[key] = uint32(cur_ix)\n\t\tbackward = cur_ix - prev_ix\n\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\tif compare_char != int(data[prev_ix+best_len_in]) {\n\t\t\treturn\n\t\t}\n\n\t\tif backward == 0 || backward > max_backward {\n\t\t\treturn\n\t\t}\n\n\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\tif len >= 4 {\n\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\tif best_score < score {\n\t\t\t\tout.len = uint(len)\n\t\t\t\tout.distance = backward\n\t\t\t\tout.score = score\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbucket = h.buckets[key:]\n\t\tvar i int\n\t\tprev_ix = uint(bucket[0])\n\t\tbucket = bucket[1:]\n\t\tfor i = 0; i < h.bucketSweep; (func() { i++; tmp3 := bucket; bucket = bucket[1:]; prev_ix = uint(tmp3[0]) })() {\n\t\t\tvar backward uint = cur_ix - prev_ix\n\t\t\tvar len uint\n\t\t\tprev_ix &= uint(uint32(ring_buffer_mask))\n\t\t\tif compare_char != int(data[prev_ix+best_len]) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backward == 0 || backward > max_backward {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlen = findMatchLengthWithLimit(data[prev_ix:], data[cur_ix_masked:], max_length)\n\t\t\tif len >= 4 {\n\t\t\t\tvar score uint = backwardReferenceScore(uint(len), backward)\n\t\t\t\tif best_score < score {\n\t\t\t\t\tbest_score = score\n\t\t\t\t\tbest_len = uint(len)\n\t\t\t\t\tout.len = best_len\n\t\t\t\t\tout.distance = backward\n\t\t\t\t\tout.score = score\n\t\t\t\t\tcompare_char = int(data[cur_ix_masked+best_len])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif h.useDictionary && min_score == out.score {\n\t\tsearchInStaticDictionary(dictionary, h, data[cur_ix_masked:], max_length, max_backward+gap, max_distance, out, true)\n\t}\n\n\th.buckets[key+uint32((cur_ix>>3)%uint(h.bucketSweep))] = uint32(cur_ix)\n}", "func longestCommonSubsequenceLentgh(s1 string, s2 string) int {\n\n\t/*\n\t * s2 will be on the rows, s1 will be on the columns.\n\t *\n\t * +1 to leave room at the left for the \"\".\n\t */\n\n\tcache := make([][]int, len(s1)+1)\n\n\tfor indx := range cache {\n\n\t\tcache[indx] = make([]int, len(s2)+1)\n\t}\n\n\t/*\n\t * cache[s2.length()][s1.length()] is our original subproblem.\n\n\t *\tEach entry in the\n\t * table is taking a substring operation against whatever string is on the rows\n\t *\n\t *\n\t * It goes from index 0 to index s2Row/s1Col (exclusive)\n\t *\n\t * So if my s1 = \"azb\" and s1Col = 2...then my substring that I pass to the\n\t * lcs() function will be:\n\t *\n\t * 0 1 2 \"a z b\"\n\t *\n\t * \"az\" (index 2...our upper bound of the snippet...is excluded)\n\t */\n\n\tfor s2Row := 0; s2Row <= len(s2); s2Row++ {\n\t\tfor s1Col := 0; s1Col <= len(s1); s1Col++ {\n\t\t\tif s2Row == 0 || s1Col == 0 {\n\t\t\t\tcache[s2Row][s1Col] = 0\n\t\t\t} else if string(s2[s2Row-1]) == string(s1[s1Col-1]) {\n\t\t\t\tcache[s2Row][s1Col] = cache[s2Row-1][s1Col-1] + 1\n\t\t\t} else {\n\t\t\t\tif cache[s2Row-1][s1Col] > cache[s2Row][s1Col-1] {\n\t\t\t\t\tcache[s2Row][s1Col] = cache[s2Row-1][s1Col]\n\t\t\t\t} else {\n\t\t\t\t\tcache[s2Row-1][s1Col] = cache[s2Row][s1Col-1]\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t}\n\treturn cache[len(s2)][len(s1)]\n}", "func search81(nums []int, target int) bool {\n\tif len(nums) == 0 {\n\t\treturn false\n\t}\n\tleft, right := 0, len(nums)-1\nquiries:\n\tfor left < right {\n\t\tmid := left + (right-left)/2\n\t\tif nums[mid] > nums[right] {\n\t\t\tleft = mid + 1\n\t\t} else if nums[mid] < nums[right] {\n\t\t\tright = mid\n\t\t} else {\n\t\t\t// handle special case when the value of mid is equal to the right value\n\t\t\tfor _, v := range nums[mid : right+1] { // [3, 1, 1, 1, 1], [2, 2, 2, 0, 2, 2]\n\t\t\t\tif v != nums[mid] {\n\t\t\t\t\tleft = mid + 1\n\t\t\t\t\tcontinue quiries\n\t\t\t\t}\n\t\t\t}\n\t\t\tright = mid\n\t\t}\n\t}\n\n\tpivot := left\n\tleft, right = 0, len(nums)-1\n\tif target >= nums[pivot] && target <= nums[right] {\n\t\tleft = pivot\n\t} else {\n\t\tright = pivot - 1\n\t}\n\n\tfor left <= right {\n\t\tmid := left + (right-left)/2\n\t\tif target > nums[mid] {\n\t\t\tleft = mid + 1\n\t\t} else if target < nums[mid] {\n\t\t\tright = mid - 1\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func bgmlogsdist(a, b bgmcommon.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func binarySearch(cnt int) bool {\n lo := 0\n hi := len(luckyNumbers) - 1\n for lo <= hi {\n mid := (lo + hi) / 2\n if luckyNumbers[mid] == cnt {\n return true\n } else if luckyNumbers[mid] > cnt {\n hi = mid - 1\n } else {\n lo = mid + 1\n }\n }\n return false\n}", "func contains(needle int, haystack []int) bool {\n\tfor _, i := range haystack {\n\t\tif needle == i {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func inStrSlice(a []string, x string, caseSensitive bool) int {\n\tfor idx, n := range a {\n\t\tif !caseSensitive && strings.EqualFold(x, n) {\n\t\t\treturn idx\n\t\t}\n\t\tif x == n {\n\t\t\treturn idx\n\t\t}\n\t}\n\treturn -1\n}", "func TestBigSearch(t *testing.T) {\n\ttree := avl.TreeInit()\n\tfor i := 0; i < 100000; i++ {\n\t\ttree.Insert(myString{s: strconv.Itoa(i)})\n\t}\n\n\tfor i := 0; i < 100000; i++ {\n\t\tf := tree.Search(myString{s: strconv.Itoa(i)})\n\t\tif f == false {\n\t\t\tt.Errorf(\"Search error\\n\")\n\t\t\tt.Errorf(\"Could not find value: %v\\n\", myString{s: strconv.Itoa(i)})\n\t\t}\n\t}\n}", "func MagicIndexBinarySearch(A []int) int {\n\tif len(A) == 0 {\n\t\treturn -1\n\t}\n\n\tleft := 0\n\tright := len(A) - 1\n\n\tfor mid := left + (right-left)/2; left < right; mid = left + (right-left)/2 {\n\t\tif A[mid] == mid {\n\t\t\treturn mid\n\t\t} else if A[mid] > mid {\n\t\t\tright = mid - 1\n\t\t} else {\n\t\t\tleft = mid + 1\n\t\t}\n\t}\n\n\treturn -1\n}", "func BetterLinearSearch(A []int, x int) (int, bool) {\n\tfor i := range A {\n\t\tif A[i] == x {\n\t\t\treturn i, true\n\t\t}\n\t}\n\n\treturn 0, false\n}", "func levenshtein(a string, b string) int {\n\n\t// Handle empty string cases\n\tif len(a) == 0 {\n\t\treturn len(b)\n\t}\n\tif len(b) == 0 {\n\t\treturn len(a)\n\t}\n\n\t// DP matrix\n\tmat := make([][]int, len(a))\n\tfor i := range mat {\n\t\tmat[i] = make([]int, len(b))\n\t}\n\n\t// Initialize base cases\n\tfor i := 0; i < len(a); i++ {\n\t\tmat[i][0] = i\n\t}\n\tfor i := 0; i < len(b); i++ {\n\t\tmat[0][i] = i\n\t}\n\n\t// Fill out optimal edit distance matrix\n\tfor i := 1; i < len(a); i++ {\n\t\tfor j := 1; j < len(b); j++ {\n\t\t\tcost := 0\n\t\t\tif a[i] != b[j] {\n\t\t\t\tcost = 1\n\t\t\t}\n\n\t\t\t// Compute cheapest way of getting to this index\n\t\t\tabove := mat[i-1][j] + 1\n\t\t\tleft := mat[i][j-1] + 1\n\t\t\tdiag := mat[i-1][j-1] + cost\n\n\t\t\t// Sort and take idx 0 to get minimum\n\t\t\tarr := []int{above, left, diag}\n\t\t\tsort.Ints(arr)\n\t\t\tmin := arr[0]\n\t\t\tmat[i][j] = min\n\t\t}\n\t}\n\treturn mat[len(a)-1][len(b)-1]\n}", "func execmStringSliceSearch(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(sort.StringSlice).Search(args[1].(string))\n\tp.Ret(2, ret)\n}", "func Levenshtein(target, input string) int { // nolint: funlen\n\t// Example\n\t// ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python\n\t// ref optimized version in go: https://github.com/sajari/fuzzy/blob/master/fuzzy.go#L236\n\tlenTarget := len(target)\n\tlenInput := len(input)\n\tnumCols := lenTarget + 1\n\n\tdistance := make([]int, (lenTarget+1)*(lenInput+1))\n\n\t// log.Println(target, input)\n\n\tfor row := 0; row <= lenInput; row++ {\n\t\tfor col := 0; col <= lenTarget; col++ {\n\t\t\tif row == 0 {\n\t\t\t\tdistance[row*numCols+col] = col\n\t\t\t}\n\n\t\t\tif col == 0 {\n\t\t\t\tdistance[row*numCols+col] = row\n\t\t\t}\n\n\t\t\tif row > 0 && col > 0 {\n\t\t\t\tcost := 0\n\n\t\t\t\tif target[col-1] != input[row-1] {\n\t\t\t\t\tcost++\n\t\t\t\t}\n\n\t\t\t\t// Costs\n\t\t\t\t// - x is the current posizion\n\t\t\t\t//\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | substitution cost | insetion cost |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\t// | delete cost | x |\n\t\t\t\t// +-------------------+----------------+\n\t\t\t\tdelCost := distance[(row-1)*numCols+col] + 1 // Cost of deletions\n\t\t\t\tinsCost := distance[row*numCols+(col-1)] + 1 // Cost of insertions\n\t\t\t\tsubCost := distance[(row-1)*numCols+(col-1)] + cost // Cost of substitutions\n\n\t\t\t\tmin := delCost\n\n\t\t\t\tif insCost < min {\n\t\t\t\t\tmin = insCost\n\t\t\t\t}\n\n\t\t\t\tif subCost < min {\n\t\t\t\t\tmin = subCost\n\t\t\t\t}\n\n\t\t\t\tdistance[row*numCols+col] = min\n\t\t\t}\n\t\t}\n\t}\n\n\t// log.Printf(\"%+v\", distance)\n\n\t// for row := 0; row <= lenInput; row++ {\n\t// \tfor col := 0; col <= lenTarget; col++ {\n\t// \t\tfmt.Printf(\"%d \", distance[row*numCols+col])\n\t// \t}\n\t// \tfmt.Println()\n\t// }\n\n\treturn distance[len(distance)-1]\n}", "func LinearSearchStrings(arr []string, x string) int {\n\tarrLen := len(arr)\n\tif arrLen == 0 {\n\t\tpanic(\"cannot search in array of size 0\")\n\t}\n\treturn LinearSearch(arrLen, func(i int) bool { return arr[i] == x })\n}", "func findDuplicate(nums []int) int {\n N := len(nums)\n if N < 1 {\n return -1 \n }\n\n l := 1\n r := N - 1\n\n for l < r {\n // Divide number into: (l->m) & (m+1->r)\n mid := l + (r - l) / 2\n\n // Count numbers which is less or equal to m\n count := 0\n for _, num := range nums {\n if num <= mid {\n count++\n }\n }\n\n if count > mid {\n // Duplicate number must in left part, i.e. range: l->m\n r = mid\n } else {\n // Duplicate number must in right part, i.e. range: m+1->r\n l = mid + 1\n }\n }\n \n return l\n}", "func matchprefix(a, b string) string {\n\tres := \"\"\n\tsmallest := len(a)\n\tif smallest > len(b) {\n\t\tsmallest = len(b)\n\t}\n\tfor i := 0; i < smallest; i++ {\n\t\tif a[i] == b[i] {\n\t\t\tres += string(a[i])\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn res\n}", "func searchInsert(nums []int, target int) int {\n\tfor index, num := range nums {\n\t\tif target <= num {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn len(nums)\n}", "func IndexLookup(x *suffixarray.Index, s []byte, n int) []int", "func SearchInts(haystack []int, needle int) int {\n\tindex, _ := binarySearch(haystack, needle, 0)\n\treturn index\n}", "func LinearSearch(n int, equalityFunc func(int) bool) int {\n\tfor i := 0; i < n; i++ {\n\t\tif equalityFunc(i) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func binarySearch(array []int, left int, right int, v int) int {\n\n\tfor left <= right {\n\t\tmiddle := left + (right-left)/2\n\t\tif array[middle] == v {\n\t\t\treturn middle\n\t\t}\n\n\t\tif array[middle] < v {\n\t\t\tleft = middle + 1\n\t\t} else {\n\t\t\tright = middle - 1\n\t\t}\n\t}\n\n\treturn -1\n}", "func searchRange(nums []int, target int) []int {\n\tresult := []int{-1, -1}\n\tif len(nums) <= 0 {\n\t\treturn result\n\t}\n\n\tfor i := 0; i < len(nums); i++ {\n\t\tif nums[i] == target {\n\t\t\tresult[0] = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor j := len(nums) - 1; j >= 0; j-- {\n\t\tif nums[j] == target {\n\t\t\tresult[1] = j\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn result\n}", "func SearchInsert(nums []int, target int) int {\n\ti := 0\n\tfor j := 0; j < len(nums); j++ {\n\t\tif target <= nums[j] {\n\t\t\ti = j\n\t\t\treturn i\n\t\t}\n\t\ti = j + 1\n\t}\n\treturn i\n}", "func search(nums []int, target int) bool {\n\tl, r := 0, len(nums)-1\n\n\tfor l <= r {\n\t\tm := l + (r-l)/2\n\t\tif nums[m] == target {\n\t\t\treturn true\n\t\t} else if nums[m] < nums[l] && nums[m] < nums[r] {\n\t\t\t// pivot is between l and m\n\t\t\tif target > nums[m] && target <= nums[r] {\n\t\t\t\tl = m + 1\n\t\t\t} else {\n\t\t\t\tr = m - 1\n\t\t\t}\n\t\t} else if nums[m] > nums[l] && nums[m] > nums[r] {\n\t\t\t// pivot is between m and r\n\t\t\tif target < nums[m] && target >= nums[l] {\n\t\t\t\tr = m - 1\n\t\t\t} else {\n\t\t\t\tl = m + 1\n\t\t\t}\n\t\t} else if nums[m] > nums[l] && nums[m] < nums[r] {\n\t\t\t// no pivot\n\t\t\tif target < nums[m] {\n\t\t\t\tr = m - 1\n\t\t\t} else {\n\t\t\t\tl = m + 1\n\t\t\t}\n\t\t} else {\n\t\t\tif nums[l] == target {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tl++\n\t\t}\n\t}\n\n\treturn false\n}", "func searchMap(x map[int]string, y string) int {\n\n\tfor k, v := range x {\n\t\tif v == y {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func findShortestSubArray(nums []int) int {\n\tn := len(nums)\n\tif n < 2 {\n\t\treturn n\n\t}\n\tfirst := make(map[int]int, n) //第一次出现当前元素的位置\n\tcount := make(map[int]int, n) //记录当前元素出现的个数\n\tmaxCount := 1\n\tminLen := n\n\tfor i, v := range nums {\n\t\tcount[v]++\n\t\tif count[v] == 1 {\n\t\t\tfirst[v] = i\n\t\t} else {\n\t\t\tl := i - first[v] + 1 //度\n\t\t\tif maxCount < count[v] || (maxCount == count[v] && minLen > l) {\n\t\t\t\tmaxCount = count[v]\n\t\t\t\tminLen = l\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(count) == n {\n\t\treturn 1\n\t}\n\treturn minLen\n}", "func main() {\n\t//fmt.Println(search([]int{4, 5, 6, 7, 0, 1, 2}, 3))\n\tfmt.Println(search([]int{1, 2, 3, 4, 5, 6}, 4))\n}", "func search(n int, f func(int) bool) int {\n\tlo := 0\n\tfor hi := n; lo < hi; {\n\t\tif i := int(uint(lo+hi) >> 1); !f(i) {\n\t\t\tlo = i + 1\n\t\t} else {\n\t\t\thi = i\n\t\t}\n\t}\n\treturn lo\n}", "func search(nums []int, target int) int {\n\tfor i,v := range nums {\n\t\tif v == target {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func BinarySearch ( \n sortedArray []interface{}, \n toFind interface{}, \n comparator func ( interface{}, interface{}) (int, error) ,\n ) (int, error) {\n start, end := 0, len(sortedArray)\n for start <= end {\n mid := (end - start ) / 2 + start \n comparisionResult, typeError := comparator(toFind, sortedArray[mid])\n if typeError != nil {\n return -1, typeError\n }\n switch {\n case comparisionResult < 0 :\n end = mid-1\n case comparisionResult > 0 :\n start = mid+1\n default:\n return mid, nil \n }\n }\n return -1, nil \n}", "func BinarySearch(s []int, n int, low int, high int) (int, bool) {\n\tif len(s) == 0 {\n\t\treturn 0, false\n\t}\n\n\tif low > high {\n\t\treturn 0, false\n\t}\n\n\tmid := (high + low) / 2\n\tguess := s[mid]\n\n\tif guess == n {\n\t\treturn mid, true\n\t} else if guess > n {\n\t\treturn BinarySearch(s, n, low, mid-1)\n\t} else {\n\t\treturn BinarySearch(s, n, mid+1, high)\n\t}\n}", "func kmpAlgorithm(src, pat string) {\n\tlps := createLongestPrefixSuffix([]rune(pat))\n\n\ti := 0\n\tj := 0\n\tfor i < len(src) {\n\t\tif src[i] == pat[j] {\n\t\t\ti++\n\t\t\tj++\n\t\t}\n\n\t\tif j == len(pat) {\n\t\t\tfmt.Println(\"Pattern Found at index:\", i-j)\n\t\t\tj = lps[j-1]\n\t\t} else if src[i] != pat[j] {\n\t\t\tif j != 0 {\n\t\t\t\tj = lps[j-1]\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t}\n}", "func (self *kmp) FindAllStringIndex(s string) []int {\n\t// precompute\n\tlen_s := len(s)\n\tif len_s < self.size {\n\t\treturn []int{}\n\t}\n\n\tmatch := make([]int, 0, startSize)\n\tm, i := 0, 0\n\tfor m+i < len_s {\n\t\tif self.pattern[i] == s[m+i] {\n\t\t\tif i == self.size-1 {\n\t\t\t\t// the word was matched\n\t\t\t\tmatch = append(match, m)\n\t\t\t\t// simulate miss, and keep running\n\t\t\t\tm += i - self.next[i]\n\t\t\t\tif self.next[i] > -1 {\n\t\t\t\t\ti = self.next[i]\n\t\t\t\t} else {\n\t\t\t\t\ti = 0\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else {\n\t\t\tm += i - self.next[i]\n\t\t\tif self.next[i] > -1 {\n\t\t\t\ti = self.next[i]\n\t\t\t} else {\n\t\t\t\ti = 0\n\t\t\t}\n\t\t}\n\t}\n\treturn match\n}", "func KMPImprovedSearch(content string, pattern string) int {\n\tcr, pr := []rune(content), []rune(pattern)\n\tnext := GetImprovedNext(pr)\n\ti, j, sl, pl := 0, 0, len(cr), len(pr)\n\tfor i < sl && j < pl {\n\t\tif j == -1 || cr[i] == pr[j] {\n\t\t\ti, j = i+1, j+1\n\t\t} else {\n\t\t\tj = next[j]\n\t\t}\n\t}\n\tif j == pl {\n\t\treturn i - j\n\t}\n\treturn -1\n\n}", "func BinarySearch(arr []int, n int) int{\n f,l := 0,len(arr)\n for f<l{\n mid := f + (l-f)/2\n if arr[mid] <= n{\n f = mid+1\n }else{\n l = mid\n }\n }\n return f\n}", "func search() {\n\tvar lowerMatchedList = list.New() // the list which stores the lower-matched index\n\tfor i := 0; i < indexSize; i++ { // scan each index item (lower)\n\t\tvar isMatched bool = false\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.lower.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.lower.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // lowerMatchedList will store all the indexes' positions which match the lower-bound\n\t\t\tlowerMatchedList.PushBack(i)\n\t\t}\n\t}\n\n\tfor e := lowerMatchedList.Front(); e != nil; e = e.Next() { // find which one matches the upper bound from the list whose item matches the lower bound\n\t\tvar (\n\t\t\ti = e.Value.(int)\n\t\t\tisMatched bool = false\n\t\t)\n\t\tfor j := 0; j < 32/blockSize; j++ { // scan each block\n\t\t\tfor k := 0; k < int(subIndexSize); k++ { // scan all the blocks which their tags are the same as the query's\n\t\t\t\tif index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] == 100 { // if all the items with the same sub-index in one block have been checked\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttargetItem := index[i].blockCipher[j].subIndex[queryCipher.upper.blockCipher[j].subIndex][k] // get the item's index\n\n\t\t\t\t// perform the hash operation to check if this item is matched by the query lower-bound block\n\t\t\t\tk1Byte := F(new(big.Int).SetBytes(queryCipher.upper.blockCipher[j].cipher), index[i].gamma)\n\t\t\t\tk2Byte := index[i].blockCipher[j].ciphers[targetItem]\n\n\t\t\t\tif bytes.Equal(k1Byte, k2Byte) {\n\t\t\t\t\tisMatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMatched == true { // if one item in a block matches, the whole index item matches\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isMatched == true { // insert the matched index into the result list\n\t\t\tres.PushBack(index[i].note)\n\t\t}\n\t}\n}", "func BinarySearch(src []int, key int) bool {\n\tstart := 0\n\tend := len(src) - 1\n\tfor start <= end {\n\t\tmid := (start + end) / 2\n\t\ttmp := src[mid]\n\t\tif tmp == key {\n\t\t\treturn true\n\t\t} else if key < tmp {\n\t\t\tend = mid - 1\n\t\t} else {\n\t\t\tstart = mid + 1\n\t\t}\n\t}\n\treturn false\n}", "func BinarySearch(arr []int64, e int64) (bool, int) {\n\tvar middle, start, end int\n\tstart = 0\n\tend = len(arr) - 1\n\n\tfor start <= end {\n\t\tmiddle = (start + end) / 2\n\t\tif arr[middle] == e {\n\t\t\treturn true, middle\n\t\t} else if arr[middle] > e {\n\t\t\tend = middle - 1\n\t\t} else {\n\t\t\tstart = middle + 1\n\t\t}\n\t}\n\treturn false, -1\n}", "func Find(needle *types.Entry, haystack []*types.Entry) (*types.Entry, bool) {\n\tvar found bool\n\tvar target *types.Entry\n\tfor _, e := range haystack {\n\t\tif types.EntriesAreEqual(e, needle) {\n\t\t\tfound = true\n\t\t\ttarget = e\n\t\t\tbreak\n\t\t}\n\t}\n\treturn target, found\n}", "func Find(ss []string, s string) (indices []int) {\n\tfor i, s1 := range ss {\n\t\tif s1 == s {\n\t\t\tindices = append(indices, i)\n\t\t}\n\t}\n\treturn\n}", "func BinarySearchLastLessThanOrEqualTo(data []int, val int) int {\n\tlength := len(data)\n\tlow, high := 0, length-1\n\n\tfor low <= high {\n\t\tmid := low + (high-low)/2\n\t\tif data[mid] > val {\n\t\t\thigh = mid - 1\n\t\t} else {\n\t\t\tif mid == length-1 || data[mid+1] > val {\n\t\t\t\treturn mid\n\t\t\t}\n\t\t\tlow = mid + 1\n\t\t}\n\t}\n\n\treturn -1\n}", "func BinarySearch(arr []models.SlamPose, low int, high int, key uint64) int {\n\tmid := (low + high) / 2\n\tresultIndex := -1\n\tif low > high || key < arr[0].TimeNanos || key > arr[len(arr)-1].TimeNanos {\n\t\tresultIndex = -1\n\t} else {\n\t\tresult := 0\n\t\tflag := false\n\t\tif flag, result = CheckValue(arr, mid, key); flag {\n\t\t\tresultIndex = result\n\t\t} else if arr[mid].TimeNanos > key {\n\t\t\tresultIndex = BinarySearch(arr, low, mid-1, key)\n\t\t} else {\n\t\t\tresultIndex = BinarySearch(arr, mid+1, high, key)\n\t\t}\n\t}\n\n\treturn resultIndex\n}", "func getOccurrencePosition(arr []int, key, firstPos, lastPos, res int, findFirstOccr bool) int {\n\n\tif firstPos <= lastPos {\n\t\tmidIdx := (firstPos+lastPos)/2\n\t\tif arr[midIdx] == key {\n\t\t\tres = midIdx\n\t\t\tif findFirstOccr {\n\t\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t\t} else {\n\t\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t\t}\n\t\t} else if arr[midIdx] < key {\n\t\t\t// search in right hand side of array in case array is sorted in ascending order\n\t\t\treturn getOccurrencePosition(arr, key, midIdx+1, lastPos, res, findFirstOccr)\n\t\t} else {\n\t\t\t// arr[midIdx] > key, i.e. search in first half of the array\n\t\t\treturn getOccurrencePosition(arr, key, firstPos, midIdx-1, res, findFirstOccr)\n\t\t}\n\t}\n\treturn res\n}", "func hackerrankInString(s string) string {\n // Can build a trie as well\n hackerrank := \"hackerrank\"\n sPtr := 0\n hPtr := 0\n for hPtr < len(hackerrank) {\n // Find first instance\n for sPtr < len(s) {\n if s[sPtr] == hackerrank[hPtr] {\n hPtr++\n sPtr++\n break\n }\n sPtr++\n // Can't find\n if (sPtr == len(s)) {\n // fmt.Printf(\"Can't find %c\", hackerrank[hPtr])\n return \"NO\"\n }\n }\n // Can't find\n if (sPtr == len(s) && hPtr != len(hackerrank)) {\n // fmt.Printf(\"Can't find %c\", hackerrank[hPtr])\n return \"NO\"\n }\n }\n return \"YES\"\n}", "func BinarySearch[S ~[]E, E constraints.Ordered](x S, target E) (int, bool) {\n\treturn expslices.BinarySearch(x, target)\n}", "func find(slice [][]rune, val []rune) int {\n\tfor i, item := range slice {\n\t\tif utils.Equal(item, val) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (pn *offsetNode) searchString(s string, inLeft, inRight int64) (offset, left, right int64, ok bool) {\n\tf := func(node *offsetNode) int {\n\t\tif s < node.s {\n\t\t\treturn -1\n\t\t} else if s > node.s {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\n\tvar node *offsetNode\n\tnode, left, right = pn.search(f, inLeft, inRight)\n\tif node != nil {\n\t\toffset = node.offset\n\t\tok = true\n\t}\n\treturn\n}", "func (t *T) Search(needle string, f func(start, end int, match string) error) error {\n\treturn t.lhs.Search(needle, func(start, end int, binds pattern.Binds) error {\n\t\tout, err := t.rhs.Apply(binds)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(start, end, out)\n\t})\n}", "func findMin(nums []int) int {\n\tsize := len(nums)\n\tlow := 0\n\thigh := size - 1\n\tfor low < high {\n\t\tif nums[low] < nums[high] {\n\t\t\treturn nums[low]\n\t\t}\n\n\t\tmid := (low + high) / 2\n\t\tif nums[mid] == nums[high] {\n\t\t\tif nums[low] == nums[mid] {\n\t\t\t\tlow++\n\t\t\t\thigh--\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif nums[low] > nums[mid] {\n\t\t\t\thigh = mid\n\t\t\t} else {\n\t\t\t\tlow = mid + 1\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif nums[mid] > nums[high] {\n\t\t\tlow = mid + 1\n\t\t} else {\n\t\t\thigh = mid\n\t\t}\n\t}\n\treturn nums[low]\n}", "func searchLessThan(sorted []Stake, odds float64) (index int) {\n\tidx := binarySearch(sorted, odds)\n\tindex = -1\n\tif idx < 0 {\n\t\treturn\n\t}\n\n\tslice := sorted[idx:]\n\tindex = idx\n\tfor i := len(slice) - 1; i >= 0; i-- {\n\t\tif slice[i].Odds < odds {\n\t\t\tindex += i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func contains(haystack []string, needle string)(bool) {\n\tfor _, hay := range haystack {\n\t\tif hay == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func searchMatrix(matrix [][]int, target int) bool {\n if len(matrix) == 0 {\n return false\n }\n for i,j:=0, len(matrix[0])-1; i<len(matrix) && j>=0; {\n if matrix[i][j] == target {\n return true\n } else if matrix[i][j] < target {\n i++\n } else {\n j--\n }\n }\n return false\n}", "func ladderLength(beginWord string, endWord string, wordList []string) int {\n\tdict := make(map[string]bool) // 把word存入字典\n\tfor _, word := range wordList {\n\t\tdict[word] = true // 可以利用字典快速添加、删除和查找单词\n\t}\n\tif _, ok := dict[endWord]; !ok {\n\t\treturn 0\n\t}\n\t// queue := []string{beginWord} 定义辅助队列\n\tvar queue []string\n\tqueue = append(queue, beginWord)\n\n\tl := len(beginWord)\n\tsteps := 0\n\n\tfor len(queue) > 0 {\n\t\tsteps++\n\t\tsize := len(queue)\n\t\tfor i := size; i > 0; i-- { // 当前层级节点\n\t\t\ts := queue[0] // 原始单词\n\t\t\tqueue = queue[1:]\n\t\t\tchs := []rune(s)\n\t\t\tfor i := 0; i < l; i++ { // 对单词的每一位进行修改\n\t\t\t\tch := chs[i] // 对当前单词的一位\n\t\t\t\tfor c := 'a'; c <= 'z'; c++ { // 尝试从a-z\n\t\t\t\t\tif c == ch { // 跳过本身比如hot修改为hot\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tchs[i] = c\n\t\t\t\t\tt := string(chs)\n\t\t\t\t\tif t == endWord { // 找到结果\n\t\t\t\t\t\treturn steps + 1\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := dict[t]; !ok { // 不在dict中,跳过\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdelete(dict, t) // 从字典中删除该单词,因为已经访问过,若重复访问路径一定不是最短的\n\t\t\t\t\tqueue = append(queue, t) // 将新的单词添加到队列\n\t\t\t\t}\n\t\t\t\tchs[i] = ch // 单词的第i位复位,再进行下面的操作\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}" ]
[ "0.6595747", "0.632544", "0.62381077", "0.6193211", "0.6029436", "0.59904784", "0.58908707", "0.58887416", "0.58399254", "0.571156", "0.56969106", "0.56765", "0.5651476", "0.5580427", "0.5567114", "0.55530936", "0.55427927", "0.55240685", "0.5522829", "0.5516513", "0.5512351", "0.54904497", "0.5489181", "0.5471569", "0.5446299", "0.54386854", "0.5423294", "0.5422962", "0.54152477", "0.5413415", "0.5404862", "0.53953093", "0.5388036", "0.53876036", "0.5386838", "0.53771716", "0.53630435", "0.53416616", "0.5336032", "0.5321444", "0.53196913", "0.5318048", "0.53135574", "0.53133446", "0.5307355", "0.5291818", "0.5287636", "0.5255988", "0.5246905", "0.5220133", "0.5209674", "0.5197239", "0.5179323", "0.51786387", "0.51783496", "0.5177199", "0.51701546", "0.5169169", "0.5165121", "0.5164266", "0.5162331", "0.5161818", "0.51508296", "0.51437724", "0.51390344", "0.5128981", "0.5116894", "0.51132977", "0.5113127", "0.5112872", "0.5106394", "0.5102664", "0.5102405", "0.51017624", "0.50931895", "0.5088422", "0.50862116", "0.50787663", "0.50787187", "0.5074607", "0.50602365", "0.50579506", "0.5057476", "0.50548494", "0.50545025", "0.5044559", "0.5038972", "0.5037895", "0.5036489", "0.50313467", "0.5027287", "0.5024992", "0.50162244", "0.5010181", "0.50099117", "0.50073105", "0.50045884", "0.49960065", "0.49917245", "0.49852023" ]
0.60539454
4
Setup sets up logger for writing to stdout and a file
func Setup() { logger := logrus.New() logger.SetFormatter(&logrus.TextFormatter{}) logrus.SetLevel(getLogLevel()) logWriter := logger.Writer() // timestampMs := time.Now().UnixNano() / 1000000 // path := fmt.Sprintf("log-%v", timestampMs) // sessionFile := openFile(path) fullLogFile := getFile("logs") mw := io.MultiWriter(logWriter, fullLogFile) logrus.SetOutput(mw) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SetupLoggingFile(f *os.File, lvl string) {\n\tSetLogger(log.New(f, \"\", log.LstdFlags|log.Lshortfile|log.Lmicroseconds), strings.ToLower(lvl))\n}", "func setupLogging(toFile bool, file string) derrors.Error {\n\tzerolog.SetGlobalLevel(zerolog.InfoLevel)\n\tif debugLevel {\n\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t}\n\n\tif toFile {\n\t\terr := os.MkdirAll(filepath.Dir(file), 0755)\n\t\tif err != nil {\n\t\t\treturn derrors.NewPermissionDeniedError(\"unable to create log file directory\", err).WithParams(file)\n\t\t}\n\t\tf, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn derrors.NewPermissionDeniedError(\"unable to open log file for writing\", err).WithParams(file)\n\t\t}\n\t\tlogOut = f\n\t} else {\n\t\tlogOut = os.Stderr\n\t}\n\n\tif consoleLogging {\n\t\tlogOut = zerolog.ConsoleWriter{Out: logOut}\n\t}\n\n\tlog.Logger = log.Output(logOut)\n\n\treturn nil\n}", "func SetupLogging(fn string) (func() error, error) {\n\tf, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not open log file %s, %s\", fn, err)\n\t}\n\tlog.SetOutput(f)\n\n\treturn f.Close, nil\n}", "func Setup(logFilePath string, debugMode bool) {\n\t//if !debugMode {\n\t\tlog.SetOutput(&lumberjack.Logger{\n\t\t\tFilename: logFilePath,\n\t\t\tMaxBackups: 3,\n\t\t\tMaxAge: 28, //days\n\t\t})\n\t//}\n}", "func SetupLogging(lvl string) {\n\tSetLogger(log.New(os.Stderr, \"\", log.LstdFlags|log.Lshortfile|log.Lmicroseconds), strings.ToLower(lvl))\n}", "func (agent *SrlAgent) LogSetup() {\n\t// Handle stdout for logging\n\thostName, _ := os.Hostname()\n\tstdoutDir := \"/var/log/srlinux/stdout\"\n\tlogFileName := stdoutDir + \"/\" + hostName + agent.Name + \".log\"\n\t_, err := os.Stat(stdoutDir)\n\tif os.IsNotExist(err) {\n\t\tos.MkdirAll(stdoutDir, 0760)\n\t}\n\tlogWriter, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tagent.Logger = log.New()\n\tagent.Logger.SetOutput(logWriter)\n\tagent.Logger.SetFormatter(&log.TextFormatter{\n\t\tForceColors: true,\n\t\tTimestampFormat: \"2006-01-02 15:04:05\",\n\t\tFullTimestamp: true,\n\t})\n\tagent.Logger.SetLevel(log.InfoLevel)\n\tagent.Logger.Info(\"Starting agent \", agent.Name, \"...\")\n}", "func Setup(format string, level int) {\n\tformatter := logging.MustStringFormatter(format)\n\tlogging.SetFormatter(formatter)\n\tlogging.SetLevel(logging.Level(level), mainLoggerName)\n}", "func SetupLogging(prefix string) error {\n\tlogFile := fmt.Sprintf(\"%s_%s_pid_%d.log\",\n\t\tprefix, time.Now().Format(filenameTimestamp), os.Getpid())\n\n\tsender, err := send.MakeFileLogger(logFile)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"problem constructing log writer for file %s\", logFile)\n\t}\n\n\treturn errors.Wrapf(grip.SetSender(sender),\n\t\t\"problem setting logger to write to %s\", logFile)\n}", "func setupLogging() {\n\tlogFile := viper.GetString(\"log\")\n\tif logFile == \"\" {\n\t\thome, err := homedir.Dir()\n\t\tcli.ErrCheck(err, quiet, \"Failed to access home directory\")\n\t\tlogFile = filepath.FromSlash(home + \"/ethereal.log\")\n\t}\n\tf, err := os.OpenFile(logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)\n\tcli.ErrCheck(err, quiet, \"Failed to open log file\")\n\tlog.SetOutput(f)\n\tlog.SetFormatter(&log.JSONFormatter{})\n\n}", "func (u *Unpackerr) setupLogging() {\n\tu.Logger.debug = u.Config.Debug\n\n\tif u.Logger.Logger.SetFlags(log.LstdFlags); u.Config.Debug {\n\t\tu.Logger.Logger.SetFlags(log.Lshortfile | log.Lmicroseconds | log.Ldate)\n\t}\n\n\tlogFile, err := homedir.Expand(u.Config.LogFile)\n\tif err != nil {\n\t\tlogFile = u.Config.LogFile\n\t}\n\n\tu.Config.LogFile = logFile\n\trotate := &rotatorr.Config{\n\t\tFilepath: u.Config.LogFile, // log file name.\n\t\tFileSize: int64(u.Config.LogFileMb) * megabyte, // megabytes\n\t\tRotatorr: &timerotator.Layout{\n\t\t\tFileCount: u.Config.LogFiles,\n\t\t\tPostRotate: u.postLogRotate,\n\t\t}, // number of files to keep.\n\t\tDirMode: logsDirMode,\n\t}\n\n\tvar writer io.Writer\n\n\tswitch { // only use MultiWriter if we have > 1 writer.\n\tcase !u.Config.Quiet && u.Config.LogFile != \"\":\n\t\tu.rotatorr = rotatorr.NewMust(rotate)\n\t\twriter = io.MultiWriter(u.rotatorr, os.Stdout)\n\t\tlog.SetOutput(writer)\n\tcase !u.Config.Quiet && u.Config.LogFile == \"\":\n\t\twriter = os.Stdout\n\tcase u.Config.LogFile == \"\":\n\t\twriter = ioutil.Discard // default is \"nothing\"\n\tdefault:\n\t\tu.rotatorr = rotatorr.NewMust(rotate)\n\t\twriter = u.rotatorr\n\t\tlog.SetOutput(writer)\n\t}\n\n\tu.Logger.Logger.SetOutput(writer)\n\tu.postLogRotate(\"\", \"\")\n}", "func Setup() {\n\tlogger.SetOutput(os.Stdout) // Send all logs to console\n\n\t_logger := new(OCLogger)\n\tlogger.AddHook(_logger)\n\n\tLogger = _logger\n}", "func SetupLogger(spec *config.Specification) {\n\tlogrus.SetOutput(os.Stdout)\n\tif spec.Debug {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t\treturn\n\t}\n\tlogrus.SetLevel(logrus.InfoLevel)\n}", "func setupLogger() {\n\tif !knf.GetB(LOG_ENABLED, true) {\n\t\tlog.Set(os.DevNull, 0)\n\t\treturn\n\t}\n\n\tlog.Set(knf.GetS(LOG_FILE), knf.GetM(LOG_PERMS, 0644))\n\tlog.MinLevel(knf.GetS(LOG_LEVEL, \"info\"))\n}", "func SetupLogger(logStdout bool) {\n\tif logStdout {\n\t\tlogger := log.New(os.Stdout, \"exoip \", 0)\n\t\tLogger = &wrappedLogger{syslog: false, stdWriter: logger}\n\t} else {\n\t\tlogger, err := syslog.New(syslog.LOG_DAEMON, \"exoip\")\n\t\tif err != nil {\n\t\t\t_, errP := fmt.Fprintf(os.Stderr, \"fatal error: %s\\n\", err)\n\t\t\tif errP != nil {\n\t\t\t\tpanic(errP)\n\t\t\t}\n\t\t\tos.Exit(1)\n\t\t}\n\t\tLogger = &wrappedLogger{syslog: true, syslogWriter: logger}\n\t}\n}", "func SetupLogging(logDir string) {\n\tlogrus.SetFormatter(&utcFormatter{\n\t\t&logrus.TextFormatter{\n\t\t\tTimestampFormat: \"2006-01-02T15:04:05.000000000Z07:00\",\n\t\t\tFullTimestamp: true,\n\t\t\tDisableColors: false,\n\t\t\tDisableTimestamp: false,\n\t\t\tDisableSorting: false,\n\t\t},\n\t})\n\tif logDir != \"\" {\n\t\t_ = os.Mkdir(logDir, os.ModePerm)\n\t\tlogrus.AddHook(dugong.NewFSHook(\n\t\t\tfilepath.Join(logDir, \"info.log\"),\n\t\t\tfilepath.Join(logDir, \"warn.log\"),\n\t\t\tfilepath.Join(logDir, \"error.log\"),\n\t\t\t&utcFormatter{\n\t\t\t\t&logrus.TextFormatter{\n\t\t\t\t\tTimestampFormat: \"2006-01-02T15:04:05.000000000Z07:00\",\n\t\t\t\t\tDisableColors: true,\n\t\t\t\t\tDisableTimestamp: false,\n\t\t\t\t\tDisableSorting: false,\n\t\t\t\t},\n\t\t\t},\n\t\t\t&dugong.DailyRotationSchedule{GZip: true},\n\t\t))\n\t}\n}", "func SetupLogger() (err error) {\n\tvar (\n\t\tlf = strings.ToLower(viper.GetString(\"output\"))\n\t)\n\n\t// Set log format\n\tswitch lf {\n\tcase \"json\":\n\t\tlog.SetFormatter(&log.JSONFormatter{})\n\tdefault:\n\t\tlog.SetFormatter(&log.TextFormatter{\n\t\t\tDisableLevelTruncation: true,\n\t\t})\n\t}\n\treturn nil\n}", "func Setup() {\n\t// create a new instance of the logrus logger\n\tLog = logrus.New()\n\n\t// set the logger level to debug\n\tLog.Level = logrus.DebugLevel\n\n\t// set the logger output format\n\tLog.Formatter = &logrus.JSONFormatter{\n\t\tFieldMap: logrus.FieldMap{\n\t\t\tlogrus.FieldKeyTime: \"timestamp\",\n\t\t\tlogrus.FieldKeyLevel: \"severity\",\n\t\t\tlogrus.FieldKeyMsg: \"message\",\n\t\t},\n\t\tTimestampFormat: time.RFC3339Nano,\n\t}\n\n\t// set the logger output dest\n\tLog.Out = os.Stdout\n}", "func SetupLogger(cfg AppLogger) {\n\tlogLevel, err := logrus.ParseLevel(cfg.Level)\n\tif err != nil {\n\t\tlogLevel = logrus.DebugLevel\n\t}\n\n\tlogrus.SetLevel(logLevel)\n\n\tif !cfg.StdOut {\n\t\tlogrus.SetOutput(ioutil.Discard)\n\n\t\tlogrus.AddHook(NewRotateFileHook(RotateFileConfig{\n\t\t\tFilename: cfg.Path,\n\t\t\tMaxSize: cfg.MaxSize,\n\t\t\tMaxBackups: cfg.MaxBackups,\n\t\t\tMaxAge: cfg.MaxAge,\n\t\t\tLocalTime: true,\n\t\t\tCompress: true,\n\t\t\tLevel: logLevel,\n\t\t\tFormatter: &logrus.JSONFormatter{\n\t\t\t\tTimestampFormat: time.RFC3339,\n\t\t\t\tDisableTimestamp: false,\n\t\t\t\tFieldMap: logrus.FieldMap{\n\t\t\t\t\tlogrus.FieldKeyMsg: \"message\",\n\t\t\t\t\tlogrus.FieldKeyTime: \"timestamp\",\n\t\t\t\t},\n\t\t\t},\n\t\t}))\n\t} else {\n\t\tlogrus.SetOutput(os.Stdout)\n\n\t\tif logLevel == logrus.DebugLevel {\n\t\t\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\t\t\tFullTimestamp: true,\n\t\t\t\tTimestampFormat: time.RFC3339,\n\t\t\t})\n\t\t} else {\n\t\t\tlogrus.SetFormatter(&logrus.JSONFormatter{\n\t\t\t\tTimestampFormat: time.RFC3339,\n\t\t\t})\n\t\t}\n\t}\n\n\tlogrus.SetReportCaller(true)\n}", "func loggingSetup() {\n\tlogs := utility.NewLogging()\n\thandler.Logs = logs\n\tcontroller.Logs = logs\n\trepository.Logs = logs\n\tlogs.LogInfo(\"Global logs setup done.\")\n}", "func initLogging() {\n\n\tfile, err := os.OpenFile(viper.GetString(\"LogPath\"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)\n\tmultiWriter := io.MultiWriter(os.Stdout, file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tLogInfo = log.New(file, \"INFO: \", log.Ldate|log.Ltime|log.Lshortfile)\n\tLogWarn = log.New(file, \"WARNING: \", log.Ldate|log.Ltime|log.Lshortfile)\n\tLogError = log.New(file, \"ERROR: \", log.Ldate|log.Ltime|log.Lshortfile)\n\n\tLogInfo.SetOutput(multiWriter)\n\tLogWarn.SetOutput(multiWriter)\n\tLogError.SetOutput(multiWriter)\n}", "func SetupStdoutLogging() Logger {\n\tw := kitlog.NewSyncWriter(os.Stdout)\n\tlogger := kitlog.NewLogfmtLogger(w)\n\tlogger = kitlog.With(logger, \"timestamp\", kitlog.DefaultTimestampUTC)\n\tSetSystemLogger(logger)\n\treturn logger\n}", "func Setup(config *Configuration) error {\n\tl, err := newZapLogger(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog = l\n\treturn nil\n}", "func SetupLogger(cfg *viper.Viper, fields map[string]interface{}) error {\n\t// Add some context to global logger\n\tlog.Logger = log.With().Fields(fields).Logger()\n\n\t// Set log level\n\tlevel, err := zerolog.ParseLevel(cfg.GetString(\"log.level\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tzerolog.SetGlobalLevel(level)\n\n\t// Enable pretty logging (not JSON) if requested\n\tif cfg.GetBool(\"log.pretty\") {\n\t\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})\n\t}\n\n\treturn nil\n}", "func setupLogging(logWriter io.Writer, debug bool) {\n\toutput := zerolog.ConsoleWriter{Out: logWriter, TimeFormat: time.RFC822}\n\n\tzerolog.SetGlobalLevel(zerolog.WarnLevel)\n\tif debug {\n\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t}\n\n\tCtx.Logger = zerolog.New(output).With().Timestamp().Logger()\n}", "func SetupLoggingOutput(path string) error {\n\tif path == \"\" {\n\t\tapp := GetAppInfo()\n\t\tpath = app.LogsPath\n\t}\n\n\tfile, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open log file\\n%v\", err)\n\t}\n\n\tlogrus.SetFormatter(&logrus.JSONFormatter{})\n\tlogrus.SetOutput(file)\n\n\treturn nil\n}", "func init() {\n\tnf, err := os.Create(\"log.txt\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tlog.SetOutput(nf) // wer set all the log outputs to this file\n}", "func (ec *ExecutionContext) setupLogger() {\n\tif ec.Logger == nil {\n\t\tlogger := logrus.New()\n\t\tec.Logger = logger\n\t\tec.Logger.SetOutput(ec.Stderr)\n\t}\n\n\tif ec.LogLevel != \"\" {\n\t\tlevel, err := logrus.ParseLevel(ec.LogLevel)\n\t\tif err != nil {\n\t\t\tec.Logger.WithError(err).Error(\"error parsing log-level flag\")\n\t\t\treturn\n\t\t}\n\t\tec.Logger.SetLevel(level)\n\t}\n\n\tec.Logger.Hooks = make(logrus.LevelHooks)\n\tec.Logger.AddHook(newSpinnerHandlerHook(ec.Logger, ec.Spinner, ec.IsTerminal, ec.NoColor))\n\n\t// set the logger for telemetry\n\tif ec.Telemetry.Logger == nil {\n\t\tec.Telemetry.Logger = ec.Logger\n\t}\n}", "func setupLogging() error {\n\t// Based on how Kopia organizes its logs.\n\tlogFileName := fmt.Sprintf(\"%v-%v-%v%v\", \"kopialauncher\", time.Now().Format(\"20060102-150405\"), os.Getpid(), \".log\")\n\n\tlogDir := filepath.Join(os.Getenv(\"HOME\"), \"Library\", \"Logs\", \"kopialauncher\")\n\n\tif err := os.MkdirAll(logDir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"can't make log directory %s: %v\", logDir, err)\n\t}\n\n\tpath := filepath.Join(logDir, logFileName)\n\tfd, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't create log file %s: %v\", path, err)\n\t}\n\n\tlog.SetOutput(fd)\n\treturn nil\n}", "func (b *ToLog) Setup() {\n\tb.Kind = \"Core\"\n\tb.Desc = \"quick way to view data in your streams; logs both to STDOUT and the GUI\"\n\tb.in = b.InRoute(\"in\")\n\tb.quit = b.Quit()\n}", "func LogSetup(level int) {\n\n\tbackend1 := logging.NewLogBackend(os.Stderr, \"\", 0)\n\tbackend1Formatter := logging.NewBackendFormatter(backend1, format)\n\tbackend1Leveled := logging.AddModuleLevel(backend1Formatter)\n\tswitch level {\n\tcase 0:\n\t\tbackend1Leveled.SetLevel(logging.NOTICE, \"astralboot\")\n\tcase 1:\n\t\tbackend1Leveled.SetLevel(logging.INFO, \"astralboot\")\n\tcase 2:\n\t\tbackend1Leveled.SetLevel(logging.DEBUG, \"astralboot\")\n\t}\n\tlogging.SetBackend(backend1Leveled)\n}", "func initLogger() {\n\tlogFile, err := os.Create(\"/go/src/simple-go-server/var/log/access1.log\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"Log file: %v\\n\", logFile.Name())\n\n\tm := io.MultiWriter(os.Stdout, logFile)\n\n\tlog.SetOutput(m)\n}", "func setupLogOutput(verbosity verbosityLevel) {\n\tif verbosity == verbosityNormal {\n\t\tlogrus.SetOutput(ioutil.Discard)\n\t\treturn\n\t}\n\n\t// If we have any level of verbosity, start piping things to stderr\n\tlogrus.SetOutput(os.Stderr)\n\t// Any verbosity of very or higher (should one eventually exist) should emit debug logs.\n\tif verbosity >= verbosityVery {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t}\n}", "func initLogger() {\n\tlogdir := viper.GetString(\"log.log_dir\")\n\tstdout := viper.GetBool(\"log_stdout\")\n\n\tvar writer io.Writer\n\n\tif logdir != \"\" {\n\t\tfolderPath, err := filepath.Abs(logdir)\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on parsing log path: %s\", logdir))\n\n\t\tabspath, err := filepath.Abs(path.Join(logdir, \"run.log\"))\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on parsing log file path: %s\", logdir))\n\n\t\terr = os.MkdirAll(folderPath, os.ModePerm)\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on creating log dir: %s\", folderPath))\n\n\t\tif stdout {\n\t\t\tfmt.Println(\"Will be logged to stdout and \", abspath)\n\t\t\tfileWriter := mylog.RotateLog(abspath)\n\t\t\twriter = io.MultiWriter(os.Stdout, fileWriter)\n\t\t} else {\n\t\t\tfmt.Println(\"Will be logged to \", abspath)\n\t\t\twriter = mylog.RotateLog(abspath)\n\t\t}\n\t} else {\n\t\t// stdout only\n\t\tfmt.Println(\"Will be logged to stdout\")\n\t\twriter = os.Stdout\n\t}\n\tlogrus.SetOutput(writer)\n\n\t// Only log the warning severity or above.\n\tswitch viper.GetString(\"log.level\") {\n\tcase \"panic\":\n\t\tlogrus.SetLevel(logrus.PanicLevel)\n\tcase \"fatal\":\n\t\tlogrus.SetLevel(logrus.FatalLevel)\n\tcase \"error\":\n\t\tlogrus.SetLevel(logrus.ErrorLevel)\n\tcase \"warn\":\n\t\tlogrus.SetLevel(logrus.WarnLevel)\n\tcase \"info\":\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\tcase \"debug\":\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\tcase \"trace\":\n\t\tlogrus.SetLevel(logrus.TraceLevel)\n\tdefault:\n\t\tfmt.Println(\"Unknown level\", viper.GetString(\"log.level\"), \"Set to INFO\")\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t}\n\n\tFormatter := new(logrus.TextFormatter)\n\tFormatter.ForceColors = false\n\tFormatter.DisableColors = true\n\tFormatter.TimestampFormat = \"06-01-02 15:04:05.000000\"\n\tFormatter.FullTimestamp = true\n\tlogrus.SetFormatter(Formatter)\n\n\t// redirect standard log to logrus\n\t//log.SetOutput(logrus.StandardLogger().Writer())\n\t//log.Println(\"Standard logger. Am I here?\")\n\tlineNum := viper.GetBool(\"log_line_number\")\n\tif lineNum {\n\t\t//filenameHook := filename.NewHook()\n\t\t//filenameHook.Field = \"line\"\n\t\t//logrus.AddHook(filenameHook)\n\t\tlogrus.SetReportCaller(true)\n\t}\n\tbyLevel := viper.GetBool(\"multifile_by_level\")\n\tif byLevel && logdir != \"\" {\n\t\tpanicLog, _ := filepath.Abs(path.Join(logdir, \"panic.log\"))\n\t\tfatalLog, _ := filepath.Abs(path.Join(logdir, \"fatal.log\"))\n\t\twarnLog, _ := filepath.Abs(path.Join(logdir, \"warn.log\"))\n\t\terrorLog, _ := filepath.Abs(path.Join(logdir, \"error.log\"))\n\t\tinfoLog, _ := filepath.Abs(path.Join(logdir, \"info.log\"))\n\t\tdebugLog, _ := filepath.Abs(path.Join(logdir, \"debug.log\"))\n\t\ttraceLog, _ := filepath.Abs(path.Join(logdir, \"trace.log\"))\n\t\twriterMap := lfshook.WriterMap{\n\t\t\tlogrus.PanicLevel: mylog.RotateLog(panicLog),\n\t\t\tlogrus.FatalLevel: mylog.RotateLog(fatalLog),\n\t\t\tlogrus.WarnLevel: mylog.RotateLog(warnLog),\n\t\t\tlogrus.ErrorLevel: mylog.RotateLog(errorLog),\n\t\t\tlogrus.InfoLevel: mylog.RotateLog(infoLog),\n\t\t\tlogrus.DebugLevel: mylog.RotateLog(debugLog),\n\t\t\tlogrus.TraceLevel: mylog.RotateLog(traceLog),\n\t\t}\n\t\tlogrus.AddHook(lfshook.NewHook(\n\t\t\twriterMap,\n\t\t\tFormatter,\n\t\t))\n\t}\n\tlogger := logrus.StandardLogger()\n\tlogrus.Debug(\"Logger initialized.\")\n\tbyModule := viper.GetBool(\"multifile_by_module\")\n\tif !byModule {\n\t\tlogdir = \"\"\n\t}\n\n\tdownloader.InitLoggers(logger, logdir)\n\tfetcher.InitLoggers(logger, logdir)\n\tp2p.InitLoggers(logger, logdir)\n\tog.InitLoggers(logger, logdir)\n\tsyncer.InitLoggers(logger, logdir)\n\tannsensus.InitLoggers(logger, logdir)\n\n}", "func SetupLogging(token, env string, h ...RollrusInitializer) io.Closer {\n\tlog.SetFormatter(&log.TextFormatter{DisableTimestamp: true})\n\n\tvar closer io.Closer\n\tif token != \"\" {\n\t\th := NewHook(token, env, h...)\n\t\tlog.AddHook(h)\n\t\tcloser = h\n\t} else {\n\t\tcloser = noopCloser{}\n\t}\n\n\treturn closer\n}", "func setupLogs() {\n\tlogrus.SetOutput(ioutil.Discard) // Send all logs to nowhere by default\n\n\tlogrus.AddHook(&WriterHook{ // Send logs with level higher than warning to stderr\n\t\tWriter: os.Stderr,\n\t\tLogLevels: []logrus.Level{\n\t\t\tlogrus.PanicLevel,\n\t\t\tlogrus.FatalLevel,\n\t\t\tlogrus.ErrorLevel,\n\t\t\tlogrus.WarnLevel,\n\t\t},\n\t})\n\tlogrus.AddHook(&WriterHook{ // Send info and debug logs to stdout\n\t\tWriter: os.Stdout,\n\t\tLogLevels: []logrus.Level{\n\t\t\tlogrus.InfoLevel,\n\t\t\tlogrus.DebugLevel,\n\t\t},\n\t})\n}", "func initLogging() {\n\tswitch config.Config.LogPath {\n\tcase \"stdout\":\n\t\tlogger.Output = os.Stdout\n\tcase \"stderr\":\n\t\tlogger.Output = os.Stderr\n\tdefault:\n\t\tvar err error\n\t\tlogger.Output, err = os.OpenFile(config.Config.LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Error opening log file: %v\", err))\n\t\t}\n\t}\n\tlog.SetOutput(logger.Output)\n\tlogger.Level = config.Config.LogLevel\n}", "func setup() {\n\t// UNIX Time is faster and smaller than most timestamps\n\t// If you set zerolog.TimeFieldFormat to an empty string,\n\t// logs will write with UNIX time\n\tzerolog.TimeFieldFormat = \"\"\n\t// In order to always output a static time to stdout for these\n\t// examples to pass, we need to override zerolog.TimestampFunc\n\t// and log.Logger globals -- you would not normally need to do this\n\tzerolog.TimestampFunc = func() time.Time {\n\t\treturn time.Date(2008, 1, 8, 17, 5, 05, 0, time.UTC)\n\t}\n\tlog.Logger = zerolog.New(os.Stdout).With().Timestamp().Logger()\n}", "func SetupLogger(cfg *config.LogConf) error {\n\tzerolog.TimeFieldFormat = \"\"\n\tlevel, err := zerolog.ParseLevel(cfg.Level)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"error returned when parsing log level\")\n\t\treturn err\n\t}\n\tzerolog.SetGlobalLevel(level)\n\n\tif cfg.DevelopmentLogger {\n\t\tzerolog.ErrorStackMarshaler = func(err error) interface{} {\n\t\t\tfmt.Println(string(debug.Stack()))\n\t\t\treturn nil\n\t\t}\n\t\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).With().Timestamp().Caller().Stack().Logger()\n\t} else {\n\t\tzerolog.ErrorStackMarshaler = pkgerrors.MarshalStack\n\t\tlog.Logger = zerolog.New(os.Stdout).With().Timestamp().Caller().Stack().Logger()\n\n\t}\n\treturn nil\n}", "func (c *Config) setupLogging(appType AppType) error {\n\n\tvar output *os.File\n\tvar appDescription string\n\n\tswitch {\n\tcase appType.Inspecter:\n\t\t// CLI app logging goes to stdout\n\t\toutput = os.Stdout\n\t\tappDescription = appTypeInspecter\n\n\tcase appType.Plugin:\n\t\t// plugin logging goes to stderr to prevent mixing in with stdout output\n\t\t// intended for the Nagios console\n\t\toutput = os.Stderr\n\t\tappDescription = appTypePlugin\n\n\tcase appType.Scanner:\n\t\t// CLI app logging goes to stdout\n\t\toutput = os.Stdout\n\t\tappDescription = appTypeScanner\n\t}\n\n\t// We set some common fields here so that we don't have to repeat them\n\t// explicitly later. This approach is intended to help standardize the log\n\t// messages to make them easier to search through later when\n\t// troubleshooting. We can extend the logged fields as needed by each\n\t// CLI application or Nagios plugin to cover unique details.\n\tc.Log = zerolog.New(output).With().Timestamp().Caller().\n\t\tStr(\"version\", Version()).\n\t\tStr(\"logging_level\", c.LoggingLevel).\n\t\tStr(\"app_type\", appDescription).\n\t\tStr(\"filename\", c.Filename).\n\t\tStr(\"server\", c.Server).\n\t\tInt(\"port\", c.Port).\n\t\tStr(\"cert_check_timeout\", c.Timeout().String()).\n\t\tInt(\"age_warning\", c.AgeWarning).\n\t\tInt(\"age_critical\", c.AgeCritical).\n\t\tLogger()\n\n\tif err := setLoggingLevel(c.LoggingLevel); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func SetupLogging(logLevel string, daemonized bool) func() error {\n\tlevel, err := logrus.ParseLevel(logLevel)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\tif daemonized {\n\t\tlogFile := openLogFile()\n\n\t\tlogrus.SetOutput(logFile)\n\t\tlogrus.SetLevel(level)\n\t\treturn logFile.Close\n\t}\n\tlogrus.SetFormatter(&logrus.TextFormatter{DisableLevelTruncation: true, FullTimestamp: true})\n\tlogrus.SetLevel(level)\n\treturn func() error {\n\t\treturn nil\n\t}\n}", "func SetUp(c LogConf) error {\n\tswitch c.Mode {\n\tcase consoleMode:\n\t\tsetupWithConsole(c)\n\t\treturn nil\n\tcase volumeMode:\n\t\treturn setupWithVolume(c)\n\tdefault:\n\t\treturn setupWithFiles(c)\n\t}\n}", "func init() {\n\tSetupLogging()\n}", "func SetupLogging(config *logger.Config) error {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tvar err error\n\n\tglobal, err = New(config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating global logger: %w\", err)\n\t}\n\n\treturn nil\n}", "func init() {\n\tlog = logger.New()\n\tlog.Out = os.Stdout\n\tlog.Level = logger.DebugLevel\n}", "func setupLogging(verbosity verbosityLevel, nbdDevice, sourceFileName, backingFileName string) error {\n\tsetupLogOutput(verbosity)\n\tsetupLogFormatting()\n\terr := setupLogHooks(nbdDevice, sourceFileName, backingFileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not setup logging: %s\", err)\n\t}\n\n\treturn nil\n}", "func (dl *dummyLogger) Setup() error {\n return nil\n}", "func SetupLogging(token, env string) {\n\tsetupLogging(token, env, defaultTriggerLevels)\n}", "func setupLogger() {\n\tsl := logrus.New()\n\tsrvLog = sl.WithField(\"context\", \"server\")\n}", "func init(){\n\tlog.SetOutput(os.Stdout)\n}", "func SetupLogger(i GoSNMPServer.ILogger) {\n\tg_Logger = i\n}", "func setup(t *testing.T, h http.HandlerFunc) (*logrus.Logger, func()) {\n\tt.Helper()\n\n\tsrv := httptest.NewServer(h)\n\n\tclient, err := axiom.NewClient(srv.URL, \"\", axiom.SetClient(srv.Client()))\n\trequire.NoError(t, err)\n\n\thook, err := adapter.NewWithClient(client, \"test\")\n\trequire.NoError(t, err)\n\n\tlogger := logrus.New()\n\tlogger.AddHook(hook)\n\n\t// We don't want output in tests.\n\tlogger.Out = ioutil.Discard\n\n\treturn logger, func() { hook.Close(); srv.Close() }\n}", "func init() {\n\tlog.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)\n\tlog.SetOutput(os.Stdout)\n}", "func SetupLogging(c LogConfiguration) {\n\tvar cores []zapcore.Core\n\n\tif c.Console {\n\t\tatom := zap.NewAtomicLevel()\n\t\tatom.SetLevel(c.ConsoleLevel)\n\t\tencoderCfg := zap.NewDevelopmentEncoderConfig()\n\t\tencoderCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder\n\t\tconsoleCore := zapcore.NewCore(\n\t\t\tzapcore.NewConsoleEncoder(encoderCfg),\n\t\t\tzapcore.Lock(os.Stdout),\n\t\t\tatom,\n\t\t)\n\t\tcores = append(cores, consoleCore)\n\t}\n\n\tif c.FilePath != \"\" {\n\t\tfileCore, err := addFileLog(c.FilePath, c.FileLevel)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unable to open log file, %s: %v\\n\", c.FilePath, err)\n\t\t} else {\n\t\t\tcores = append(cores, fileCore)\n\t\t}\n\t}\n\n\tif c.GoogleCloudProject != \"\" && c.GoogleCloudCreds != \"\" {\n\t\tgcCore, err := addGoogleCloud(c.GoogleCloudProject, c.GoogleCloudCreds)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"unable to start cloud logging to project %s with creds %s: %v\\n\", c.GoogleCloudProject, c.GoogleCloudCreds, err)\n\t\t} else {\n\t\t\tcores = append(cores, gcCore)\n\t\t}\n\t}\n\n\ttee := zapcore.NewTee(cores...)\n\tsugarfree := zap.New(tee, zap.AddCaller(), zap.AddStacktrace(zap.FatalLevel))\n\tundo, err := zap.RedirectStdLogAt(sugarfree, zap.DebugLevel)\n\tif err != nil {\n\t\tundo()\n\t}\n\n\tLog = sugarfree.Sugar()\n}", "func TestOneLogger(t *testing.T) {\n\t// Default output to stderr\n\tSetLevel(LevelDebug)\n\tDebug(\"stderr: Debug\")\n\tDebugf(\"stderr: Debug%s\", \"f\")\n\tInfo(\"stderr: Info\")\n\tInfof(\"stderr: Info%s\", \"f\")\n\tWarn(\"stderr: Warn\")\n\tWarnf(\"stderr: Warn%s\", \"f\")\n\tError(\"stderr: Error\")\n\tErrorf(\"stderr: Error%s\", \"f\")\n\t//Panic(\"stderr: Panic\")\n\t//Panicf(\"stderr: Panic%s\", \"f\")\n\t//Fatal(\"stderr: Fatal\")\n\t//Fatalf(\"stderr: Fatal%s\", \"f\")\n\n\t// Change output to file\n\tfw, err := FileWriter(\"logs/test.log\")\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn\n\t}\n\tSetOutput(fw)\n\tSetLevel(LevelDebug)\n\tInfo(\"file: Info\")\n}", "func (reporter *ConsoleReporter) Setup() error {\n\tfmt.Println(\"== potentially duplicated files ==\")\n\tfmt.Println()\n\treturn nil\n}", "func init() {\n\tvar multiWriter io.Writer\n\tvar logSvr, logF bool\n\tvar logConn net.Conn\n\tvar logFile *os.File\n\n\t//load in environment variables from .env\n\t//will print error message when running from docker image\n\t//because env file is passed into docker run command\n\terr := godotenv.Load(\"/home/ubuntu/go/src/github.com/200106-uta-go/BAM-P2/.env\")\n\tif err != nil {\n\t\tif !strings.Contains(err.Error(), \"no such file or directory\") {\n\t\t\tlog.Println(\"Error loading .env: \", err)\n\t\t}\n\t}\n\tlogAddr := os.Getenv(\"LOG_ADDR\")\n\n\tif len(logAddr) < 1 {\n\t\t// failed to get log address env variable\n\t} else {\n\t\t// connect to log server\n\t\tlogConn, err = net.Dial(\"tcp\", logAddr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to connect to %+v :: %+v\", logAddr, err)\n\t\t\tlogSvr = false\n\t\t} else {\n\t\t\tlogSvr = true\n\t\t}\n\t}\n\n\t// make sure logSrv is false if Setenv fails\n\tif logConn == nil {\n\t\tlogSvr = false\n\t}\n\n\t// create file writer\n\tif !filewriter.CheckForFile(logPath) {\n\t\tif filewriter.CreateFile(logPath) {\n\t\t\tlogFile, err = os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to open file %+v :: %+v\", logPath, err)\n\t\t\t\tlogF = false\n\t\t\t} else {\n\t\t\t\tlogF = true\n\t\t\t}\n\t\t} else {\n\t\t\tlogF = false\n\t\t}\n\t} else {\n\t\tlogFile, err = os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to open file %+v :: %+v\", logPath, err)\n\t\t\tlogF = false\n\t\t} else {\n\t\t\tlogF = true\n\t\t}\n\t}\n\n\t// Create MultiWrite based on if a connections\n\tswitch {\n\tcase logF && logSvr:\n\t\tmultiWriter = io.MultiWriter(logFile, logConn, os.Stdout)\n\t\tfmt.Println(\"Output to SERVER, FILE, and STDOUT\")\n\tcase logF && !logSvr:\n\t\tmultiWriter = io.MultiWriter(logFile, os.Stdout)\n\t\tfmt.Println(\"Output to FILE and STDOUT\")\n\tcase logSvr && !logF:\n\t\tmultiWriter = io.MultiWriter(logConn, os.Stdout)\n\t\tfmt.Println(\"Output to SERVER and STDOUT\")\n\tdefault:\n\t\tmultiWriter = io.MultiWriter(os.Stdout)\n\t\tfmt.Println(\"Output to STDOUT only\")\n\t}\n\n\t// sets log to use multiWriter\n\tlog.SetOutput(multiWriter)\n}", "func Init(bfile bool) {\n\tvar mw io.Writer\n\tif bfile == true {\n\t\tfile, err := os.OpenFile(\"logs.txt\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tmw = io.MultiWriter(os.Stdout, file)\n\t} else {\n\t\tmw = io.MultiWriter(os.Stdout)\n\t}\n\n\tInfoLogger = log.New(mw, \"INFO : \", log.Ldate|log.Ltime|log.Lshortfile)\n\tWarnLogger = log.New(mw, \"WARN : \", log.Ldate|log.Ltime|log.Lshortfile)\n\tErrorLogger = log.New(mw, \"ERROR: \", log.Ldate|log.Ltime|log.Lshortfile)\n\tFatalLogger = log.New(mw, \"FATAL: \", log.Ldate|log.Ltime|log.Lshortfile)\n}", "func setLogger(filename *string) error {\n\n\tfn := defaultLoggingFile\n\tif filename != nil && strings.TrimSpace(*filename) != \"\" {\n\t\tfn = *filename\n\t}\n\n\tlogFile, err := os.OpenFile(fn, os.O_RDWR, 0740)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\n\t\tlogFile, err = os.Create(fn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.SetOutput(logFile)\n\tlog.SetReportCaller(true)\n\treturn nil\n}", "func Setup(logFlag bool, logstr, logDest string) error {\n\tif logDest != \"\" {\n\t\tn, err := strconv.Atoi(logDest)\n\t\tif err == nil {\n\t\t\tlogOut = os.NewFile(uintptr(n), \"delve-logs\")\n\t\t} else {\n\t\t\tfh, err := os.Create(logDest)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not create log file: %v\", err)\n\t\t\t}\n\t\t\tlogOut = fh\n\t\t}\n\t}\n\tlog.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)\n\tif !logFlag {\n\t\tlog.SetOutput(ioutil.Discard)\n\t\tif logstr != \"\" {\n\t\t\treturn errLogstrWithoutLog\n\t\t}\n\t\treturn nil\n\t}\n\tif logstr == \"\" {\n\t\tlogstr = \"debugger\"\n\t}\n\tany = true\n\tv := strings.Split(logstr, \",\")\n\tfor _, logcmd := range v {\n\t\t// If adding another value, do make sure to\n\t\t// update \"Help about logging flags\" in commands.go.\n\t\tswitch logcmd {\n\t\tcase \"debugger\":\n\t\t\tdebugger = true\n\t\tcase \"gdbwire\":\n\t\t\tgdbWire = true\n\t\tcase \"lldbout\":\n\t\t\tlldbServerOutput = true\n\t\tcase \"debuglineerr\":\n\t\t\tdebugLineErrors = true\n\t\tcase \"rpc\":\n\t\t\trpc = true\n\t\tcase \"dap\":\n\t\t\tdap = true\n\t\tcase \"fncall\":\n\t\t\tfnCall = true\n\t\tcase \"minidump\":\n\t\t\tminidump = true\n\t\tcase \"stack\":\n\t\t\tstack = true\n\t\tdefault:\n\t\t\tfmt.Fprintf(os.Stderr, \"Warning: unknown log output value %q, run 'dlv help log' for usage.\\n\", logcmd)\n\t\t}\n\t}\n\treturn nil\n}", "func SetupLogger(token string, level Level, tags []string, bulk bool, debugMode bool) {\n\tif loggerSingleton != nil {\n\t\treturn\n\t}\n\n\t// Setup logger with options.\n\tloggerSingleton = &logger{\n\t\ttoken: token,\n\t\tLevel: level,\n\t\turl: \"\",\n\t\tbulk: bulk,\n\t\tbufferSize: 1000,\n\t\tflushInterval: 10 * time.Second,\n\t\tbuffer: nil,\n\t\ttags: tags,\n\t\tdebugMode: debugMode,\n\t}\n\n\t// If the bulk option is set make sure we set the url to the bulk endpoint.\n\tif bulk {\n\t\tloggerSingleton.url = \"https://logs-01.loggly.com/bulk/\" + token + \"/tag/\" + tagList() + \"/\"\n\n\t\t// Start flush interval\n\t\tgo start()\n\t} else {\n\t\tloggerSingleton.url = \"https://logs-01.loggly.com/inputs/\" + token + \"/tag/\" + tagList() + \"/\"\n\t}\n\n}", "func SetupLog(name string) {\n\tlog.SetOutput(os.Stdout)\n\t// use unix timestamp instead of zonal one\n\tf := &ServiceFormatter{\n\t\tsvcName: name,\n\t\tFormatter: &log.JSONFormatter{DisableTimestamp: true},\n\t}\n\tlog.SetFormatter(f)\n\tlog.SetLevel(log.InfoLevel)\n\tif viper.GetBool(cst.EnvVerbose) {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n}", "func attachLogger(cmd *exec.Cmd, pfx string, stream int) (*logger, error) {\n\tdir, base := filepath.Split(pfx)\n\tstreamName, ok := streamNames[stream]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"invalid stream %v\", stream)\n\t}\n\tvar w io.Writer\n\tif stream == syscall.Stdout {\n\t\tw = cmd.Stdout\n\t} else if stream == syscall.Stderr {\n\t\tw = cmd.Stderr\n\t}\n\tfn := filepath.Join(dir, fmt.Sprintf(\"%v%v.%v.log\", base, cmd.Args[0], streamName))\n\tf, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not open %v\", fn)\n\t}\n\twriters := []io.Writer{f}\n\tif w != nil {\n\t\twriters = append(writers, w)\n\t}\n\tl := &logger{\n\t\tcmd: cmd,\n\t\tstartTime: time.Now(),\n\t\tf: f,\n\t\tWriter: io.MultiWriter(writers...),\n\t}\n\tl.intro()\n\tif stream == syscall.Stdout {\n\t\tcmd.Stdout = l\n\t} else if stream == syscall.Stderr {\n\t\tcmd.Stderr = l\n\t}\n\treturn l, nil\n}", "func (s *serviceInit) setupLogFile(args []string) {\n\tif len(args) > s.logIndex {\n\t\tvalue := args[s.logIndex]\n\t\tif value != \"\" {\n\t\t\ts.logFilePath = value\n\t\t}\n\t}\n}", "func setUp() {\n\tvar logger = apis.Logger\n\tmanager.Logger = logger.WithField(\"hook\", manager.LoggingTag)\n}", "func init() {\n\n\tlogfile := &lumberjack.Logger{\n\t\tFilename: \"event.log\",\n\t\tMaxSize: 1, // megabytes\n\t\tMaxBackups: 9,\n\t\tMaxAge: 28, //days\n\t}\n\n\tinfoLog := io.MultiWriter(logfile, os.Stdout)\n\terrLog := io.MultiWriter(logfile, os.Stderr)\n\n\tdoneLogger = log.New(infoLog, \"Done at \", log.LstdFlags)\n\tinfoLogger = log.New(infoLog, \"Happened at \", log.LstdFlags)\n\twarnLogger = log.New(errLog, \"Warning at \", log.LstdFlags|log.Lshortfile)\n\terrLogger = log.New(errLog, \"Error at \", log.LstdFlags|log.Lshortfile)\n}", "func setUpLogs(out io.Writer, level string) error {\n\tlogrus.SetOutput(out)\n\tlvl, err := logrus.ParseLevel(level)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}", "func init() {\n\tlogger = &log.Logger{\n\t\tOut: os.Stdout,\n\t\tLevel: log.DebugLevel,\n\t\tFormatter: &logStashFormatter{log.TextFormatter{\n\t\t\tTimestampFormat: \"2006-01-02 15:04:05\",\n\t\t\tFullTimestamp: true},\n\t\t},\n\t}\n}", "func SetUpLogs(stdErr io.Writer, level string) error {\n\tlogrus.SetOutput(stdErr)\n\tlvl, err := logrus.ParseLevel(level)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing log level: %w\", err)\n\t}\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}", "func setupLogging() {\n\tlogger := logrus.New()\n\tlogger.Formatter = &logrus.JSONFormatter{}\n\n\t// Log everything and colorize logs in development mode\n\t// You can customize to any level but \"info\" in development mode\n\tif viper.GetString(\"environment\") == \"development\" {\n\t\tlogger.Formatter = &logrus.TextFormatter{}\n\t\tlogger.Level = logrus.DebugLevel\n\t}\n\n\tmiddleware.SetLogger(logger)\n}", "func logSetup() {\n\n\tlog.Printf(\"Server will run on: %s\\n\", getListenAddress())\n}", "func (logger *Logger) init() {\n\toutfile, _ := os.Create(\"dbsearcher.log\")\n\tlogger.Logger = log.New(outfile, \"\", 0)\n}", "func init() {\n\tlog.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)\n\tlog.SetOutput(os.Stderr)\n}", "func init() {\n // change the device for logging to stdout\n log.SetOutput(os.Stdout)\n}", "func setLogFile() {\n\tif _, err := os.Stat(debugFile); os.IsNotExist(err) {\n\t\t_, err = os.Create(debugFile)\n\t\tpanicIf(err, \"Failed to create debug file \"+debugFile)\n\t}\n\tfile, err := os.OpenFile(debugFile, os.O_APPEND|os.O_WRONLY, 0666)\n\tpanicIf(err, \"Couldn't open debug file\"+debugFile)\n\t//defer file.Close()\n\tmulti := io.MultiWriter(file, os.Stdout)\n\tlog.SetOutput(multi)\n}", "func (a *WalletApplication) initLogger() {\n\tlogFile, err := os.OpenFile(a.paths.DAGDir+\"/wallet.log\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0664)\n\tif err != nil {\n\t\ta.log.Fatal(\"Unable to create log file.\")\n\t}\n\tmw := io.MultiWriter(os.Stdout, logFile)\n\ta.log.SetOutput(mw)\n\ta.log.SetFormatter(&log.TextFormatter{\n\t\tForceColors: true,\n\t\tFullTimestamp: true,\n\t})\n}", "func logSetup() {\n\tlog.Printf(\"Server will run on: %s\\n\", getListenAddress())\n}", "func SetupLogrus(LogFile string, LogLevel string, LogAsJSON bool) func() {\n\tos.MkdirAll(path.Dir(LogFile), os.ModePerm)\n\tpathMap := lfshook.PathMap{\n\t\tlogrus.DebugLevel: LogFile,\n\t\tlogrus.InfoLevel: LogFile,\n\t\tlogrus.WarnLevel: LogFile,\n\t\tlogrus.ErrorLevel: LogFile,\n\t\tlogrus.FatalLevel: LogFile,\n\t\tlogrus.PanicLevel: LogFile,\n\t}\n\tvar formatter logrus.Formatter\n\tif LogAsJSON {\n\t\tformatter = &logrus.JSONFormatter{}\n\t\tlogrus.SetFormatter(formatter)\n\t}\n\tfsHook := lfshook.NewHook(pathMap, formatter)\n\n\tlogrus.AddHook(fsHook)\n\n\tlevel, err := logrus.ParseLevel(LogLevel)\n\tif err != nil {\n\t\tlevel = logrus.DebugLevel\n\t}\n\tlogrus.SetLevel(level)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"Using default logrus level debug instead\")\n\t}\n\n\treturn func() {\n\t\terr := recover()\n\t\tif err != nil {\n\t\t\tdebug.PrintStack()\n\t\t\tlogrus.Fatal(err)\n\t\t} else {\n\t\t\tlogrus.Info(\"Goodbye!\")\n\t\t}\n\t}\n}", "func (dhtClient *DHTClient) setupLogger() {\n\tfields := map[string]string{\n\t\t\"package\": \"DHTClient\",\n\t\t\"relayid\": dhtClient.relayPeer.Pretty(),\n\t}\n\tif dhtClient.routedHost != nil {\n\t\tfields[\"peerid\"] = dhtClient.routedHost.ID().Pretty()\n\t}\n\tdhtClient.logger = utils.NewDefaultLoggerWithFields(fields)\n}", "func init() {\n\tLogger = log.New(os.Stderr, \"\", log.LstdFlags)\n}", "func (logger *Logger) Start(level int, writer io.Writer, fileName string) (err error) {\n\tlogger.level = level\n\tlogger.flags = log.Ldate | log.Ltime\n\tlogger.Logger = log.New(os.Stdout, logger.prefix, logger.flags)\n\tif len(fileName) > 0 {\n\t\tlogger.file, err = os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tlogger.Logger.Println(err)\n\t\t} else {\n\t\t\tlogger.Logger.SetOutput(logger.file)\n\t\t}\n\t} else if writer != nil {\n\t\tlogger.Logger.SetOutput(writer)\n\t}\n\treturn\n}", "func setLogFilename(fname string) {\n\tf := os.Stdout\n\tswitch fname {\n\tcase \"stdout\":\n\t\tf = os.Stdout\n\tcase \"stderr\":\n\t\tf = os.Stderr\n\tdefault:\n\t\tvar err error\n\t\tif f, err = os.Open(fname); err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"error\": err,\n\t\t\t\t\"file\": fname,\n\t\t\t}).Fatalf(\"failed to set log file, will not contine\")\n\t\t} else {\n\t\t\tlog.SetOutput(f)\n\t\t}\n\t}\n}", "func init() {\n\tcommandLine.StringVar(&logging.logDir, \"log_dir\", \"\", \"If non-empty, write log files in this directory (no effect when -logtostderr=true)\")\n\tcommandLine.StringVar(&logging.logFile, \"log_file\", \"\", \"If non-empty, use this log file (no effect when -logtostderr=true)\")\n\tcommandLine.Uint64Var(&logging.logFileMaxSizeMB, \"log_file_max_size\", 1800,\n\t\t\"Defines the maximum size a log file can grow to (no effect when -logtostderr=true). Unit is megabytes. \"+\n\t\t\t\"If the value is 0, the maximum file size is unlimited.\")\n\tcommandLine.BoolVar(&logging.toStderr, \"logtostderr\", true, \"log to standard error instead of files\")\n\tcommandLine.BoolVar(&logging.alsoToStderr, \"alsologtostderr\", false, \"log to standard error as well as files (no effect when -logtostderr=true)\")\n\tlogging.setVState(0, nil, false)\n\tcommandLine.Var(&logging.verbosity, \"v\", \"number for the log level verbosity\")\n\tcommandLine.BoolVar(&logging.addDirHeader, \"add_dir_header\", false, \"If true, adds the file directory to the header of the log messages\")\n\tcommandLine.BoolVar(&logging.skipHeaders, \"skip_headers\", false, \"If true, avoid header prefixes in the log messages\")\n\tcommandLine.BoolVar(&logging.oneOutput, \"one_output\", false, \"If true, only write logs to their native severity level (vs also writing to each lower severity level; no effect when -logtostderr=true)\")\n\tcommandLine.BoolVar(&logging.skipLogHeaders, \"skip_log_headers\", false, \"If true, avoid headers when opening log files (no effect when -logtostderr=true)\")\n\tlogging.stderrThreshold = severityValue{\n\t\tSeverity: severity.ErrorLog, // Default stderrThreshold is ERROR.\n\t}\n\tcommandLine.Var(&logging.stderrThreshold, \"stderrthreshold\", \"logs at or above this threshold go to stderr when writing to files and stderr (no effect when -logtostderr=true or -alsologtostderr=false)\")\n\tcommandLine.Var(&logging.vmodule, \"vmodule\", \"comma-separated list of pattern=N settings for file-filtered logging\")\n\tcommandLine.Var(&logging.traceLocation, \"log_backtrace_at\", \"when logging hits line file:N, emit a stack trace\")\n\n\tlogging.settings.contextualLoggingEnabled = true\n\tlogging.flushD = newFlushDaemon(logging.lockAndFlushAll, nil)\n}", "func Setup(config *Config, ui cli.Ui) (*logutils.LevelFilter, *GatedWriter, *LogWriter, io.Writer, bool) {\n\t// The gated writer buffers logs at startup and holds until it's flushed.\n\tlogGate := &GatedWriter{\n\t\tWriter: &cli.UiWriter{Ui: ui},\n\t}\n\n\t// Set up the level filter.\n\tlogFilter := LevelFilter()\n\tlogFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.LogLevel))\n\tlogFilter.Writer = logGate\n\tif !ValidateLevelFilter(logFilter.MinLevel, logFilter) {\n\t\tui.Error(fmt.Sprintf(\n\t\t\t\"Invalid log level: %s. Valid log levels are: %v\",\n\t\t\tlogFilter.MinLevel, logFilter.Levels))\n\t\treturn nil, nil, nil, nil, false\n\t}\n\n\t// Set up syslog if it's enabled.\n\tvar syslog io.Writer\n\tif config.EnableSyslog {\n\t\tretries := 12\n\t\tdelay := 5 * time.Second\n\t\tfor i := 0; i <= retries; i++ {\n\t\t\tl, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, \"consul\")\n\t\t\tif err == nil {\n\t\t\t\tsyslog = &SyslogWrapper{l, logFilter}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tui.Error(fmt.Sprintf(\"Syslog setup error: %v\", err))\n\t\t\tif i == retries {\n\t\t\t\ttimeout := time.Duration(retries) * delay\n\t\t\t\tui.Error(fmt.Sprintf(\"Syslog setup did not succeed within timeout (%s).\", timeout.String()))\n\t\t\t\treturn nil, nil, nil, nil, false\n\t\t\t}\n\n\t\t\tui.Error(fmt.Sprintf(\"Retrying syslog setup in %s...\", delay.String()))\n\t\t\ttime.Sleep(delay)\n\t\t}\n\t}\n\n\t// Create a log writer, and wrap a logOutput around it\n\tlogWriter := NewLogWriter(512)\n\tvar logOutput io.Writer\n\tif syslog != nil {\n\t\tlogOutput = io.MultiWriter(logFilter, logWriter, syslog)\n\t} else {\n\t\tlogOutput = io.MultiWriter(logFilter, logWriter)\n\t}\n\treturn logFilter, logGate, logWriter, logOutput, true\n}", "func Setup(logFlag bool, logstr string) error {\n\tlog.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)\n\tif !logFlag {\n\t\tlog.SetOutput(ioutil.Discard)\n\t\tif logstr != \"\" {\n\t\t\treturn errLogstrWithoutLog\n\t\t}\n\t\treturn nil\n\t}\n\tif logstr == \"\" {\n\t\tlogstr = \"debugger\"\n\t}\n\tv := strings.Split(logstr, \",\")\n\tfor _, logcmd := range v {\n\t\tswitch logcmd {\n\t\tcase \"debugger\":\n\t\t\tdebugger = true\n\t\tcase \"gdbwire\":\n\t\t\tgdbWire = true\n\t\tcase \"lldbout\":\n\t\t\tlldbServerOutput = true\n\t\tcase \"debuglineerr\":\n\t\t\tdebugLineErrors = true\n\t\tcase \"rpc\":\n\t\t\trpc = true\n\t\t}\n\t}\n\treturn nil\n}", "func SetLogger(l *log.Logger) {\n StdOutLogger = l\n}", "func setupLogging(level logging.Level) *logging.Logger {\n\tlogger := logging.MustGetLogger(\"libsteg\")\n\tformat := logging.MustStringFormatter(\n\t\t`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,\n\t)\n\n\tbackend1 := logging.NewLogBackend(os.Stdout, \"\", 0)\n\tbackend1Formatter := logging.NewBackendFormatter(backend1, format)\n\tbackend1Leveled := logging.AddModuleLevel(backend1Formatter)\n\tbackend1Leveled.SetLevel(level, \"\")\n\tlogging.SetBackend(backend1Leveled)\n\n\treturn logger\n}", "func init() {\n\t// set the device for logging to stdout\n\tlog.SetOutput(os.Stdout)\n}", "func SetupLogger(development *bool) {\n\tlogf.SetLogger(logf.ZapLogger(*development))\n\tLog = log.Log.WithName(\"controller-jenkins\")\n}", "func InitLogger(f *os.File) {\n\n\tLogger = logrus.New()\n\tLogger.SetFormatter(&logrus.JSONFormatter{\n\t\tTimestampFormat: \"\",\n\t\tPrettyPrint: true,\n\t})\n\n\t// Set output of logs to Stdout\n\t// Change to f for redirecting to file\n\tLogger.SetOutput(os.Stdout)\n\n}", "func init() {\n\tdebugLogger = log.New(os.Stderr, debugPrefix, log.Ldate|log.Ltime)\n\tinfoLogger = log.New(os.Stdout, infoPrefix, log.Ldate|log.Ltime)\n\tsuccessLogger = log.New(os.Stdout, successPrefix, log.Ldate|log.Ltime)\n\twarningLogger = log.New(os.Stdout, warningPrefix, log.Ldate|log.Ltime)\n\terrorLogger = log.New(os.Stderr, errorPrefix, log.Ldate|log.Ltime)\n\tfatalLogger = log.New(os.Stderr, fatalPrefx, log.Ldate|log.Ltime)\n\tpanicLogger = log.New(os.Stderr, panicPrefix, log.Ldate|log.Ltime)\n}", "func initialiseLogger() {\n // make and set location of log file\n date := time.Now().Format(\"2006-01-02\")\n var logpath = getCurrentExecDir() + \"/log/\" + date + \"_server.log\"\n os.MkdirAll(getCurrentExecDir()+\"/log/\", os.ModePerm)\n // open file for create and append\n var file, err = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n if err != nil { panic(fmt.Sprintf(\"Could not open logfile `%s`: %s\", logpath, err)) }\n // make new Logger io\n log_writer := io.MultiWriter(os.Stdout, file)\n Logger = log.New(log_writer, \" \", log.LstdFlags)\n Logger.Println(\"LogFile : \" + logpath)\n}", "func LogSetup(server config.Server) {\n\tforwardHost := utils.IfEmpty(server.Upstream.Host, \"*\")\n\tforwardProto := server.Upstream.Scheme\n\n\tlbEndpointList := fmt.Sprintf(\"%v\", server.Upstream.Endpoints)\n\tif len(server.Upstream.Endpoints) == 0 {\n\t\tlbEndpointList = \"VOID\"\n\t}\n\n\tlogrus.Infof(\"Server will run on :%s and :%s and redirects to url: %s://%s -> %s\\n\", server.Port.HTTP, server.Port.HTTPS, forwardProto, forwardHost, lbEndpointList)\n}", "func init() {\n\tlogger = log.New(os.Stderr, \"\", 0)\n\tLogKeys = make(map[string]bool)\n\tlogNoTime = false\n}", "func initLogger(cfg *config.GlobalConfig) {\n\tvar writers []io.Writer\n\twriters = append(writers, zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: \"15:04:05\"})\n\n\tfileLoggingEnabled := false\n\tif len(cfg.Logger.LogsDir) > 0 {\n\t\tfileLoggingEnabled = true\n\t}\n\tif fileLoggingEnabled {\n\t\tlogsDir := cfg.Logger.LogsDir\n\t\tif err := os.MkdirAll(logsDir, 0744); err != nil {\n\t\t\tfmt.Printf(\"can't create log directory, so file logging is disabled, error: %s\", err.Error())\n\t\t} else {\n\t\t\tfileWriter := &lumberjack.Logger{\n\t\t\t\tFilename: path.Join(logsDir, \"starling.log\"),\n\t\t\t\tMaxBackups: 3, // files\n\t\t\t\tMaxSize: 10, // megabytes\n\t\t\t\tMaxAge: 30, // days\n\t\t\t}\n\n\t\t\twriters = append(writers, fileWriter)\n\t\t\t//fmt.Printf(\"file logging is enabled, logsDir: %s\\n\", logsDir)\n\t\t}\n\t}\n\tmw := io.MultiWriter(writers...)\n\n\tlog.Logger = zerolog.New(mw).With().Timestamp().Logger()\n\t//log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: \"15:04:05\"})\n\n\tswitch strings.ToLower(cfg.Logger.LogLevel) {\n\tcase \"panic\":\n\t\tzerolog.SetGlobalLevel(zerolog.PanicLevel)\n\tcase \"fatal\":\n\t\tzerolog.SetGlobalLevel(zerolog.FatalLevel)\n\tcase \"error\":\n\t\tzerolog.SetGlobalLevel(zerolog.ErrorLevel)\n\tcase \"warn\":\n\t\tzerolog.SetGlobalLevel(zerolog.WarnLevel)\n\tcase \"info\":\n\t\tzerolog.SetGlobalLevel(zerolog.InfoLevel)\n\tcase \"trace\":\n\t\tzerolog.SetGlobalLevel(zerolog.TraceLevel)\n\tdefault:\n\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t}\n}", "func Initialize(useLog bool) {\n\tif !useLog {\n\t\treturn\n\t}\n\n\tvar tempWriter io.Writer\n\n\ttempWriter, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)\n\n\tif err != nil {\n\t\tlog.Printf(\"trace initialize: %v\", err)\n\t}\n\n\tif f, ok := tempWriter.(*os.File); ok {\n\t\tlogWriter = f\n\t}\n}", "func setupLogger(l log.Logger, cfg *operator.Config) log.Logger {\n\tnewLogger, err := cortex_log.NewPrometheusLogger(cfg.LogLevel, cfg.LogFormat)\n\tif err != nil {\n\t\tlevel.Error(l).Log(\"msg\", \"failed to create logger\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\tl = newLogger\n\n\tadapterLogger := logutil.Wrap(l)\n\n\t// NOTE: we don't set up a caller field here, unlike the normal agent.\n\t// There's too many multiple nestings of the logger that prevent getting the\n\t// caller from working properly.\n\n\t// Set up the global logger and the controller-local logger.\n\tcontroller.SetLogger(adapterLogger)\n\tcfg.Controller.Logger = adapterLogger\n\treturn l\n}", "func init() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n}", "func init() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n}", "func init() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n}", "func initFileLog(cfg *FileLogConfig, logger *log.Logger) error {\n\tif st, err := os.Stat(cfg.Filename); err == nil {\n\t\tif st.IsDir() {\n\t\t\treturn errors.New(\"can't use directory as log file name\")\n\t\t}\n\t}\n\tif cfg.MaxSize == 0 {\n\t\tcfg.MaxSize = DefaultLogMaxSize\n\t}\n\n\t// use lumberjack to logrotate\n\toutput := &lumberjack.Logger{\n\t\tFilename: cfg.Filename,\n\t\tMaxSize: int(cfg.MaxSize),\n\t\tMaxBackups: int(cfg.MaxBackups),\n\t\tMaxAge: int(cfg.MaxDays),\n\t\tLocalTime: true,\n\t}\n\n\tif logger == nil {\n\t\tlog.SetOutput(output)\n\t} else {\n\t\tlogger.Out = output\n\t}\n\treturn nil\n}" ]
[ "0.74559295", "0.7438469", "0.73214", "0.7285313", "0.7268446", "0.71519774", "0.70177907", "0.698466", "0.6980594", "0.6966565", "0.69569176", "0.68867934", "0.6859939", "0.68274504", "0.67815405", "0.67797464", "0.67763656", "0.67729414", "0.67655355", "0.67301327", "0.6715228", "0.6684924", "0.66788954", "0.66663724", "0.66587", "0.6652688", "0.6644025", "0.66385704", "0.6553135", "0.6539837", "0.65261465", "0.6520579", "0.6491397", "0.64663047", "0.6451623", "0.644818", "0.64476234", "0.6441807", "0.64408624", "0.6422608", "0.639967", "0.6393712", "0.63844955", "0.6382733", "0.6381306", "0.63674986", "0.636573", "0.6332958", "0.63201344", "0.62706554", "0.6269977", "0.6254441", "0.6246183", "0.62432665", "0.6240768", "0.6217753", "0.62152445", "0.6200328", "0.6196324", "0.619582", "0.61605686", "0.61560273", "0.6155669", "0.615492", "0.61471504", "0.6145093", "0.61450475", "0.61408395", "0.6113387", "0.6106868", "0.6097714", "0.6062482", "0.6060535", "0.6057771", "0.6046067", "0.6033999", "0.60168433", "0.60007155", "0.59984803", "0.5997008", "0.5994275", "0.59908277", "0.59903854", "0.5989912", "0.5986326", "0.5980527", "0.59726423", "0.59709936", "0.59518504", "0.59396046", "0.5937785", "0.5936428", "0.5931771", "0.59313095", "0.59083045", "0.5907178", "0.59045005", "0.59045005", "0.59045005", "0.5901048" ]
0.74550486
1
CombinedPatternsGiven returns one regex considering all given patterns.
func CombinedPatternsGiven(patterns []*regexp.Regexp) *regexp.Regexp { var allPatterns []string for _, pattern := range patterns { allPatterns = append(allPatterns, pattern.String()) } return regexp.MustCompile(strings.Join(allPatterns, "|")) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func buildRegexFromList(patterns []string) *regexp.Regexp {\n\tif patterns == nil || len(patterns) == 0 {\n\t\tpatterns = make([]string, 0)\n\t}\n\treturn compileOrDie(\"(?i)^(\" + strings.Join(patterns, \"|\") + \")$\")\n}", "func Compose(patterns ...goji.Pattern) goji.Pattern {\n\treturn compose(patterns)\n}", "func GobwasMatcherFromPatterns(patterns []string) ([]Matcher, error) {\n\tret := make([]Matcher, 0, len(patterns))\n\tfor _, p := range patterns {\n\t\tmatcher, err := glob.Compile(p)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can not instantiate matcher\")\n\t\t}\n\t\tret = append(ret, matcher)\n\t}\n\treturn ret, nil\n}", "func unionRegexp(values []string) string {\n\tif len(values) == 0 {\n\t\t// As a regular expression, \"()\" and \"\" are equivalent so this\n\t\t// condition wouldn't ordinarily be needed to distinguish these\n\t\t// values. But, our internal search engine assumes that \"\"\n\t\t// implies \"no regexp\" (no values), while \"()\" implies \"match\n\t\t// empty regexp\" (all values) for file patterns.\n\t\treturn \"\"\n\t}\n\tif len(values) == 1 {\n\t\t// Cosmetic format for regexp value, wherever this happens to be\n\t\t// pretty printed.\n\t\treturn values[0]\n\t}\n\treturn \"(\" + strings.Join(values, \")|(\") + \")\"\n}", "func compile(regex string) (regslc []rune) {\n regslc = make([]rune, 0, len(regex) + 10)\n \n for _, r := range regex {\n if r == '+' {\n regslc = append(regslc, regslc[len(regslc) - 1], '*')\n } else {\n regslc = append(regslc, r)\n }\n } \n return regslc\n }", "func Concat(patts ...Pattern) Pattern {\n\tif len(patts) <= 0 {\n\t\treturn &EmptyNode{}\n\t}\n\n\tacc := patts[0]\n\tfor _, p := range patts[1:] {\n\t\tacc = &SeqNode{\n\t\t\tLeft: acc,\n\t\t\tRight: p,\n\t\t}\n\t}\n\n\treturn acc\n}", "func repeated(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `+`)\n}", "func repeated(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `+`)\n}", "func repeated(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `+`)\n}", "func (mg *MultiGlob) FindAllPatterns(input string) []string {\n\tresults, _ := match(mg.node, input, true)\n\tduplicates := make(map[string]bool)\n\n\tcleaned := make([]string, 0, len(results))\n\tfor _, result := range results {\n\t\tif duplicates[result] {\n\t\t\tcontinue\n\t\t}\n\t\tduplicates[result] = true\n\t\tcleaned = append(cleaned, result)\n\t}\n\n\treturn cleaned\n}", "func NewConcat(l, r Regex) Regex {\n\tswitch l.(type) {\n\tcase *empty:\n\t\treturn NewEmpty()\n\tcase *epsilon:\n\t\treturn r\n\tdefault:\n\t\treturn &concat{\n\t\t\tl: l,\n\t\t\tr: r,\n\t\t}\n\t}\n}", "func ParsePatterns(pattern []string) []Pattern {\n\tpatpat := make([]Pattern, 0)\n\tfor _, pat := range pattern {\n\t\tif pat == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tpats := preparePattern(pat)\n\t\tpatpat = append(patpat, pats)\n\t}\n\treturn patpat\n}", "func ParseMultiSourceMatchingPatterns(strs []string) (MultiSourceMatchingPatterns, error) {\n\tif len(strs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tret := make(MultiSourceMatchingPatterns, len(strs))\n\tfor i, str := range strs {\n\t\tparts := strings.Split(str, \"/\")\n\t\tif len(parts) < 2 || len(parts) > 3 {\n\t\t\treturn nil, fmt.Errorf(\"invalid provider matching pattern %q: must have either two or three slash-separated segments\", str)\n\t\t}\n\t\thost := defaultRegistryHost\n\t\texplicitHost := len(parts) == 3\n\t\tif explicitHost {\n\t\t\tgivenHost := parts[0]\n\t\t\tif givenHost == \"*\" {\n\t\t\t\thost = svchost.Hostname(Wildcard)\n\t\t\t} else {\n\t\t\t\tnormalHost, err := svchost.ForComparison(givenHost)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid hostname in provider matching pattern %q: %s\", str, err)\n\t\t\t\t}\n\n\t\t\t\t// The remaining code below deals only with the namespace/type portions.\n\t\t\t\thost = normalHost\n\t\t\t}\n\n\t\t\tparts = parts[1:]\n\t\t}\n\n\t\tpType, err := normalizeProviderNameOrWildcard(parts[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid provider type %q in provider matching pattern %q: must either be the wildcard * or a provider type name\", parts[1], str)\n\t\t}\n\t\tnamespace, err := normalizeProviderNameOrWildcard(parts[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid registry namespace %q in provider matching pattern %q: must either be the wildcard * or a literal namespace\", parts[1], str)\n\t\t}\n\n\t\tret[i] = addrs.Provider{\n\t\t\tHostname: host,\n\t\t\tNamespace: namespace,\n\t\t\tType: pType,\n\t\t}\n\n\t\tif ret[i].Hostname == svchost.Hostname(Wildcard) && !(ret[i].Namespace == Wildcard && ret[i].Type == Wildcard) {\n\t\t\treturn nil, fmt.Errorf(\"invalid provider matching pattern %q: hostname can be a wildcard only if both namespace and provider type are also wildcards\", str)\n\t\t}\n\t\tif ret[i].Namespace == Wildcard && ret[i].Type != Wildcard {\n\t\t\treturn nil, fmt.Errorf(\"invalid provider matching pattern %q: namespace can be a wildcard only if the provider type is also a wildcard\", str)\n\t\t}\n\t}\n\treturn ret, nil\n}", "func CompileStrs(regStrs []string) (*regexp.Regexp, error) {\n\tif len(regStrs) == 0 {\n\t\treturn nil, fmt.Errorf(\"regStrs must be greater than or equal to 1\")\n\t}\n\tregStr := \"(\" + strings.Join(regStrs, \"|\") + \")\"\n\tre, err := regexp.Compile(regStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn re, nil\n}", "func combineManifests(manifests []*bytes.Buffer, disablingTemplating bool) *bytes.Buffer {\n\tparts := make([]string, len(manifests))\n\tfor i, m := range manifests {\n\t\ts := m.String()\n\n\t\tif disablingTemplating {\n\t\t\t// When templating is disabled we append \"^\" to avoid YAML to JSON conversion issues. We revert that change here.\n\t\t\ts = strings.ReplaceAll(s, \"^{{\", \"{{\")\n\t\t\ts = strings.ReplaceAll(s, \"}}^\", \"}}\")\n\t\t}\n\n\t\ts = strings.TrimSuffix(s, \"\\n\")\n\t\ts = strings.TrimSpace(s)\n\t\tparts[i] = s\n\t}\n\n\treturn bytes.NewBufferString(strings.Join(parts, \"\\n---\\n\") + \"\\n\")\n}", "func DefaultPatterns(domain []string) []gitignore.Pattern {\n\tall := strings.Join([]string{ExcludeExt, ExcludeCI, ExcludeExtra}, \",\")\n\tvar ps []gitignore.Pattern\n\tfor _, p := range strings.Split(all, \",\") {\n\t\tps = append(ps, gitignore.ParsePattern(p, domain))\n\t}\n\treturn ps\n}", "func NewRegexPatternSet(ctx *pulumi.Context,\n\tname string, args *RegexPatternSetArgs, opts ...pulumi.ResourceOption) (*RegexPatternSet, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.RegularExpressionList == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RegularExpressionList'\")\n\t}\n\tif args.Scope == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Scope'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource RegexPatternSet\n\terr := ctx.RegisterResource(\"aws-native:wafv2:RegexPatternSet\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func concatRepetition(r *syntax.Regexp) (bool, *syntax.Regexp) {\n\tif r.Op != syntax.OpConcat {\n\t\t// don't iterate sub-expressions if top-level is no OpConcat\n\t\treturn false, r\n\t}\n\n\t// check if concatenated op is already a repetition\n\tif isConcatRepetition(r) {\n\t\treturn false, r\n\t}\n\n\t// concatenate repetitions in sub-expressions first\n\tvar subs []*syntax.Regexp\n\tchanged := false\n\tfor _, sub := range r.Sub {\n\t\tchangedSub, tmp := concatRepetition(sub)\n\t\tchanged = changed || changedSub\n\t\tsubs = append(subs, tmp)\n\t}\n\n\tvar concat []*syntax.Regexp\n\tlastMerged := -1\n\tfor i, j := 0, 1; j < len(subs); i, j = j, j+1 {\n\t\tif subs[i].Op == syntax.OpRepeat && eqRegex(subs[i].Sub[0], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpRepeat,\n\t\t\t\t\tSub: r.Sub,\n\t\t\t\t\tMin: r.Min + 1,\n\t\t\t\t\tMax: r.Max + 1,\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tif isConcatRepetition(subs[i]) && eqRegex(subs[i].Sub[0], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpConcat,\n\t\t\t\t\tSub: append(r.Sub, r.Sub[0]),\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tif eqRegex(subs[i], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpRepeat,\n\t\t\t\t\tSub: []*syntax.Regexp{r},\n\t\t\t\t\tMin: 2,\n\t\t\t\t\tMax: 2,\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tconcat = append(concat, subs[i])\n\t}\n\n\tif lastMerged+1 != len(subs) {\n\t\tconcat = append(concat, subs[len(subs)-1])\n\t}\n\n\tr = &syntax.Regexp{\n\t\tOp: syntax.OpConcat,\n\t\tSub: concat,\n\t\tFlags: r.Flags,\n\t}\n\treturn changed, r\n}", "func MatchOneOf(text string, patterns ...string) []string {\n\tvar (\n\t\tre *regexp.Regexp\n\t\tvalue []string\n\t)\n\tfor _, pattern := range patterns {\n\t\t// (?flags): set flags within current group; non-capturing\n\t\t// s: let . match \\n (default false)\n\t\t// https://github.com/google/re2/wiki/Syntax\n\t\tre = regexp.MustCompile(pattern)\n\t\tvalue = re.FindStringSubmatch(text)\n\t\tif len(value) > 0 {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}", "func combineUrls(urls ...string) string {\n\tresult, _ := url.Parse(\"\")\n\tfor _, u := range urls {\n\t\ttmp, _ := url.Parse(u)\n\t\tresult = result.ResolveReference(tmp)\n\t}\n\treturn result.String()\n}", "func CombinePrefixAndSuffix(prefix, suffix string, itself, hyphenate, fuse bool, minLength int) []string {\n\tvar output []string\n\tif prefix == suffix && !itself {\n\t\treturn output\n\t}\n\tstr := prefix + suffix\n\tif len(str) >= minLength {\n\t\toutput = append(output, str)\n\t}\n\tif fuse {\n\t\tif strings.HasSuffix(prefix, suffix[0:1]) {\n\t\t\toutput = append(output, prefix+suffix[1:])\n\t\t}\n\t\tif strings.HasSuffix(prefix, suffix[0:2]) {\n\t\t\toutput = append(output, prefix+suffix[2:])\n\t\t}\n\t}\n\tif hyphenate {\n\t\tstr := prefix + \"-\" + suffix\n\t\tif len(str) >= minLength {\n\t\t\toutput = append(output, prefix+\"-\"+suffix)\n\t\t}\n\t}\n\treturn output\n}", "func generatePatternForRegexp(pattern string) (string, error) {\n\tpattern = patternRegexp.ReplaceAllStringFunc(pattern, func(subMatch string) string {\n\t\t// The sub match string conforms the parameter pattern: `{parameter-name:regexp-expression}`.\n\t\tfoos := strings.SplitN(subMatch, \":\", 2)\n\t\tif len(foos) < 2 {\n\t\t\treturn `([^/]+)`\n\t\t} else {\n\t\t\treturn \"(\" + foos[1][0:len(foos[1])-1] + \")\"\n\t\t}\n\t})\n\t// Checking for abnormal patterns.\n\t_, err := regexp.Compile(pattern)\n\treturn pattern, err\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func (ie *CommonIE) SearchRegexMulti(patterns []string, str, name string,\n\tdef interface{}, fatal bool, flags int, group interface{}) OptString {\n\n\tvar match Match\n\tfor _, pattern := range patterns {\n\t\tif match = ReSearch(pattern, str, flags); match != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif match != nil {\n\t\tif group == nil {\n\t\t\t// return first group that is present in the match\n\t\t\tfor i := 1; i <= match.Groups(); i++ {\n\t\t\t\tif match.GroupPresentByIdx(i) {\n\t\t\t\t\treturn AsOptString(match.GroupByIdx(i))\n\t\t\t\t}\n\t\t\t}\n\t\t\t// this should not be\n\t\t\treturn AsOptString(\"\")\n\t\t}\n\t\t// return the group requested by index/name or None if it isn't present\n\t\treturn ReMatchGroupOne(match, group)\n\t} else if !isNoDefault(def) {\n\t\tif def == nil {\n\t\t\treturn OptString{}\n\t\t}\n\t\treturn AsOptString(def.(string))\n\t} else if fatal {\n\t\tpanic(newExtractorError(fmt.Sprintf(\"Unable to extract %v\", name)))\n\t} else {\n\t\tie.log(\"WARNING: Unable to extract %v\", name)\n\t\treturn OptString{}\n\t}\n}", "func compileRegexps(regexps []string) ([]*regexp.Regexp, error) {\n\tvar errs []error\n\tvar compiled []*regexp.Regexp\n\n\tfor _, exp := range regexps {\n\t\tre, err := regexp.Compile(exp)\n\t\tif err == nil {\n\t\t\tcompiled = append(compiled, re)\n\t\t} else {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\treturn compiled, nil\n}", "func GlobMatch(patterns ...string) MatcherFunc { return GlobMatches(patterns) }", "func compileRegex() {\n\tfor _, value := range filterObj.Signatures {\n\t\tr, _ := regexp.Compile(value.Regex)\n\t\tsignatureRegex = append(signatureRegex, r)\n\t}\n\tfor _, value := range filterObj.Shallows {\n\t\tr, _ := regexp.Compile(value.Regex)\n\t\tshallowRegex = append(shallowRegex, r)\n\t}\n}", "func ClassicPattern(pattern string) []*ClassicMatcher {\n\tsr := splitPattern(pattern)\n\tms := make(ClassicList, len(sr))\n\tfor k, val := range sr {\n\t\tms[k] = GenerateClassicMatcher(val)\n\t}\n\treturn ms\n}", "func RegexpSimplify(re *syntax.Regexp,) *syntax.Regexp", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func Combine(prefixes, suffixes, psl []string, single, hyphenate, itself, hacks, fuse bool, minLength int) []string {\n\tvar domains []string\n\tif single {\n\t\tfor _, prefix := range prefixes {\n\t\t\tdomains = append(domains, CombinePhraseAndPublicSuffixes(prefix, psl, hacks)...)\n\t\t}\n\t\tfor _, suffix := range suffixes {\n\t\t\tdomains = append(domains, CombinePhraseAndPublicSuffixes(suffix, psl, hacks)...)\n\t\t}\n\t}\n\tfor _, prefix := range prefixes {\n\t\tfor _, suffix := range suffixes {\n\t\t\tphrases := CombinePrefixAndSuffix(prefix, suffix, itself, hyphenate, fuse, minLength)\n\t\t\tfor _, phrase := range phrases {\n\t\t\t\tdomains = append(domains, CombinePhraseAndPublicSuffixes(phrase, psl, hacks)...)\n\t\t\t}\n\t\t}\n\t}\n\treturn domains\n}", "func (client PatternClient) BatchAddPatterns(ctx context.Context, appID uuid.UUID, versionID string, patterns []PatternRuleCreateObject) (result ListPatternRuleInfo, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: patterns,\n\t\t\tConstraints: []validation.Constraint{{Target: \"patterns\", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"programmatic.PatternClient\", \"BatchAddPatterns\", err.Error())\n\t}\n\n\treq, err := client.BatchAddPatternsPreparer(ctx, appID, versionID, patterns)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.PatternClient\", \"BatchAddPatterns\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.BatchAddPatternsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.PatternClient\", \"BatchAddPatterns\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.BatchAddPatternsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"programmatic.PatternClient\", \"BatchAddPatterns\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func New(patterns []string, ms MatchSet) (*MatchPattern, error) {\n\tmatchers, err := getMatchers(patterns, ms)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MatchPattern{matchers}, nil\n}", "func reg(m map[string][][]string, n string, d int) string {\n if d >= 14 {\n return \"\"\n }\n\n rules := m[n]\n ret := make([]string, 0)\n \n for _, rule := range rules {\n a := \"\"\n for _, c := range rule {\n if c == \"\\\"a\\\"\" || c == \"\\\"b\\\"\" {\n a += strings.ReplaceAll(c, \"\\\"\", \"\")\n } else {\n a += reg(m, c, d+1)\n }\n ret = append(ret, a)\n }\n }\n return fmt.Sprintf(\"(?:%s)\", strings.Join(ret, \"|\"))\n}", "func (p *DefaultParser) CompileRegex(fields []string) ([]*regexp.Regexp, error) {\n\tr := make([]*regexp.Regexp, len(fields))\n\tfor i, f := range fields {\n\t\t/*\n\t\t\tvar nextField string\n\t\t\tif i == len(fields)-1 {\n\t\t\t\tnextField = \"\"\n\t\t\t} else {\n\t\t\t\tnextField = fields[i+1]\n\t\t\t}\n\t\t*/\n\t\tfieldName := p.NamedGroup(f)\n\t\t// TODO(stratus): This is the foundation for possibly two\n\t\t// regexes - one for easy single line fields and another one for\n\t\t// multi-field.\n\t\tre, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)\\n`, f, fieldName))\n\t\t//re, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)%s`, f, fieldName, nextField))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr[i] = re\n\t}\n\treturn r, nil\n}", "func ValidatePatterns(patterns []string) error {\n\tinvalidPatterns := make([]string, 0)\n\n\tfor _, Pattern := range ParsePatterns(patterns) {\n\t\t// Validate all pattern parts\n\t\tfor _, part := range Pattern.parts {\n\t\t\t// Validate the pattern part by trying to match it against itself\n\t\t\tif _, validErr := filepath.Match(part.pattern, part.pattern); validErr != nil {\n\t\t\t\tinvalidPatterns = append(invalidPatterns, Pattern.original)\n\n\t\t\t\t// If a single part is invalid, stop processing this pattern\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(invalidPatterns) > 0 {\n\t\treturn &InvalidPatternError{InvalidPatterns: invalidPatterns}\n\t}\n\treturn nil\n}", "func (q AndOrQuery) RegexpPatterns(field string) (values, negatedValues []string) {\n\tVisitField(q.Query, field, func(visitedValue string, negated bool, _ Annotation) {\n\t\tif negated {\n\t\t\tnegatedValues = append(negatedValues, visitedValue)\n\t\t} else {\n\t\t\tvalues = append(values, visitedValue)\n\t\t}\n\t})\n\treturn values, negatedValues\n}", "func r(pattern string) *regexp.Regexp { return regexp.MustCompile(pattern) }", "func (process *Process) evalGlobPatterns(patterns []cwl.Expression) ([]string, error) {\n\tvar out []string\n\n\tfor _, pattern := range patterns {\n\t\t// TODO what is \"self\" here?\n\t\tval, err := process.eval(pattern, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch z := val.(type) {\n\t\tcase string:\n\t\t\tout = append(out, z)\n\t\tcase []string:\n\t\t\tout = append(out, z...)\n\t\tcase []interface{}:\n\t\t\tfor _, val := range z {\n\t\t\t\tz, ok := val.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\t\"glob expression returned an invalid type. Only string or []string \"+\n\t\t\t\t\t\t\t\"are allowed. Got: %#v\", z)\n\t\t\t\t}\n\t\t\t\tout = append(out, z)\n\t\t\t}\n\t\tcase []cwl.Value:\n\t\t\tfor _, val := range z {\n\t\t\t\tz, ok := val.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\t\"glob expression returned an invalid type. Only string or []string \"+\n\t\t\t\t\t\t\t\"are allowed. Got: %#v\", z)\n\t\t\t\t}\n\t\t\t\tout = append(out, z)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"glob expression returned an invalid type. Only string or []string \"+\n\t\t\t\t\t\"are allowed. Got: %#v\", z)\n\t\t}\n\t}\n\treturn out, nil\n}", "func combineStrings(s ...string) string {\n\tvar out string\n\tspacer := ``\n\tfor _, in := range s {\n\t\t// ensure a single trailing .\n\t\tout = fmt.Sprintf(\"%s%s\", out+spacer, strings.TrimRight(in, `.`)+`.`)\n\t\tspacer = \"\\n\"\n\t}\n\treturn out\n}", "func CompositeMatches(matches [][]uint32) []uint32 {\n\tswitch len(matches) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn matches[0]\n\tdefault:\n\t\tresult := make([]uint32, 0, 5)\n\t\tfor i := 0; i < len(matches); i++ {\n\t\t\tresult = append(result, matches[i]...)\n\t\t}\n\t\treturn result\n\t}\n}", "func anchored(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`^` + expression(res...).String() + `$`)\n}", "func anchored(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`^` + expression(res...).String() + `$`)\n}", "func anchored(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`^` + expression(res...).String() + `$`)\n}", "func BuildGlobPattern(paths []string) glob.Glob {\n\tvar globString string\n\tif len(paths) == 0 {\n\t\tglobString = \"\"\n\t} else if len(paths) == 1 {\n\t\tglobString = paths[0]\n\t} else {\n\t\tglobString = fmt.Sprintf(\"{%s}\", strings.Join(paths, \",\"))\n\t}\n\n\treturn glob.MustCompile(globString)\n}", "func PlusConcatLiteral(src string) bool {\n\tidx := 0\n\tisMatching := true\n\n\tplusBoolResult58 := false\n\tplusBoolResult62 := false\n\n\tstaticStr57 := \"a\"\n\tstaticStr57Len := len(staticStr57)\n\n\tif staticStr57Len+idx > len(src) {\n\t\tisMatching = false\n\t} else if staticStr57 == src[idx:idx+staticStr57Len] {\n\t\tidx += staticStr57Len\n\t\tisMatching = true\n\t} else {\n\t\tisMatching = false\n\t}\n\tplusIdxResult59 := idx\n\n\tif isMatching {\n\t\tfor {\n\n\t\t\tstaticStr60 := \"a\"\n\t\t\tstaticStr60Len := len(staticStr60)\n\n\t\t\tif staticStr60Len+plusIdxResult59 > len(src) {\n\t\t\t\tplusBoolResult58 = false\n\t\t\t} else if staticStr60 == src[plusIdxResult59:plusIdxResult59+staticStr60Len] {\n\t\t\t\tplusIdxResult59 += staticStr60Len\n\t\t\t\tplusBoolResult58 = true\n\t\t\t} else {\n\t\t\t\tplusBoolResult58 = false\n\t\t\t}\n\n\t\t\tif !plusBoolResult58 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tisMatching = plusBoolResult58\n\t\t\t\tidx = plusIdxResult59\n\t\t\t}\n\t\t}\n\t}\n\tif isMatching {\n\n\t\tstaticStr61 := \"b\"\n\t\tstaticStr61Len := len(staticStr61)\n\n\t\tif staticStr61Len+idx > len(src) {\n\t\t\tisMatching = false\n\t\t} else if staticStr61 == src[idx:idx+staticStr61Len] {\n\t\t\tidx += staticStr61Len\n\t\t\tisMatching = true\n\t\t} else {\n\t\t\tisMatching = false\n\t\t}\n\t\tplusIdxResult63 := idx\n\n\t\tif isMatching {\n\t\t\tfor {\n\n\t\t\t\tstaticStr64 := \"b\"\n\t\t\t\tstaticStr64Len := len(staticStr64)\n\n\t\t\t\tif staticStr64Len+plusIdxResult63 > len(src) {\n\t\t\t\t\tplusBoolResult62 = false\n\t\t\t\t} else if staticStr64 == src[plusIdxResult63:plusIdxResult63+staticStr64Len] {\n\t\t\t\t\tplusIdxResult63 += staticStr64Len\n\t\t\t\t\tplusBoolResult62 = true\n\t\t\t\t} else {\n\t\t\t\t\tplusBoolResult62 = false\n\t\t\t\t}\n\n\t\t\t\tif !plusBoolResult62 {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tisMatching = plusBoolResult62\n\t\t\t\t\tidx = plusIdxResult63\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif idx != len(src) {\n\t\tisMatching = false\n\t}\n\n\treturn isMatching\n\t// End of PlusConcatLiteral\n}", "func (matcher *Matcher) MatchRegex(corpus string) (bool, []string) {\n\tvar matchedRegexes []string\n\t// Iterate over all the regexes accepted as valid\n\tfor i, regex := range matcher.regexCompiled {\n\t\t// Continue if the regex doesn't match\n\t\tif !regex.MatchString(corpus) {\n\t\t\t// If we are in an AND request and a match failed,\n\t\t\t// return false as the AND condition fails on any single mismatch.\n\t\t\tswitch matcher.condition {\n\t\t\tcase ANDCondition:\n\t\t\t\treturn false, []string{}\n\t\t\tcase ORCondition:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcurrentMatches := regex.FindAllString(corpus, -1)\n\t\t// If the condition was an OR, return on the first match.\n\t\tif matcher.condition == ORCondition && !matcher.MatchAll {\n\t\t\treturn true, currentMatches\n\t\t}\n\n\t\tmatchedRegexes = append(matchedRegexes, currentMatches...)\n\n\t\t// If we are at the end of the regex, return with true\n\t\tif len(matcher.regexCompiled)-1 == i && !matcher.MatchAll {\n\t\t\treturn true, matchedRegexes\n\t\t}\n\t}\n\tif len(matchedRegexes) > 0 && matcher.MatchAll {\n\t\treturn true, matchedRegexes\n\t}\n\treturn false, []string{}\n}", "func (rs RegexpSet) Patterns() []string {\n\treturn rs.patterns\n}", "func MatchPatterns(p Pattern, v string) error {\n\tswitch {\n\tcase p == \"\": // No pattern is specified.\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"const:\"):\n\t\tw := string(p[len(\"const:\"):])\n\t\tif w != v {\n\t\t\treturn fmt.Errorf(\"const not matched: %q %q\", p, v)\n\t\t}\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"pattern:\"):\n\t\tw := string(p[len(\"pattern:\"):])\n\t\tif matchSuffix(w, v) != nil {\n\t\t\treturn fmt.Errorf(\"pattern not matched: %q %q\", p, v)\n\t\t}\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"split_pattern:\"):\n\t\tws := strings.Split(string(p[len(\"split_pattern:\"):]), \";\")\n\t\tfor _, w := range ws {\n\t\t\tif matchSuffix(w, v) == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"split_pattern not matched: %q %q\", p, v)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unkown pattern\")\n\t}\n}", "func (p *Generic) CompileRegexps(patterns map[string]string) (map[string]*regexp.Regexp, error) {\n\tresults := make(map[string]*regexp.Regexp)\n\tfor name, str := range patterns {\n\t\tre, err := regexp.Compile(str)\n\t\tif nil != err {\n\t\t\treturn results, fmt.Errorf(\"Cannot compile '%s' regexp: %s\", name, err.Error())\n\t\t}\n\t\tresults[name] = re\n\t}\n\n\treturn results, nil\n}", "func (o GoogleCloudRetailV2alphaProductResponseOutput) Patterns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaProductResponse) []string { return v.Patterns }).(pulumi.StringArrayOutput)\n}", "func MultiShiftOr(text string, patterns []string) [][]int {\n\tocc := make([][]int, len(patterns))\n\tsizes, bigPattern := bigPattern(&patterns)\n\tmasks := PreShiftOr(&bigPattern)\n\tvar init uint = (1 << len(bigPattern)) - 1\n\tvar final uint = (1 << len(bigPattern)) - 1\n\tvar match uint = (1 << len(bigPattern)) - 1\n\tPreMultiShiftOr(&sizes, &init, &final)\n\tvar d uint = (1 << len(bigPattern)) - 1\n\tfor i := 0; i < len(text); i++ {\n\t\td = ((d << 1) & init) | masks[0].Get(text[i])\n\t\tif (d | final) != match {\n\t\t\ts := 0\n\t\t\tfor pos, size := range sizes {\n\t\t\t\ts += size\n\t\t\t\tif d|(1<<(s-1)) > d {\n\t\t\t\t\tocc[len(occ)-pos-1] = append(occ[len(occ)-pos-1], i-size+1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn occ\n}", "func (s *sqlStatement) MatchPatterns(str string) bool {\n\tfor _, pattern := range s.patterns {\n\t\tif !pattern.MatchString(str) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Grep(pattern string, operand []string) ([]string, error) {\n\trex, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar matching []string\n\tfor _, elem := range operand {\n\t\tif rex.MatchString(elem) {\n\t\t\tmatching = append(matching, elem)\n\t\t}\n\t}\n\treturn matching, nil\n}", "func TransformRegExp(pattern string) (string, error) {\n\n\tlog.Printf(\"runtime.Caller(1): %#+v\\n\", myutils.Slice(runtime.Caller(1))...)\n\tos.Exit(349857394)\n\n\t// if pattern == \"\" {\n\t// \treturn \"\", nil\n\t// }\n\n\tswitch pattern {\n\t// common cases that will leave as is\n\t// but frequently occurred in many\n\t// popular frameworks like react.js etc.\n\tcase _regexp_empty,\n\t\t_regexp_any_nc,\n\t\t_regexp_any_c,\n\t\t_regexp_anyplus_nc,\n\t\t_regexp_anyplus_c,\n\n\t\t_regexp_squote_nc,\n\t\t_regexp_squote_c,\n\t\t_regexp_dquote_nc,\n\t\t_regexp_dquote_c,\n\n\t\t_regexp_plus_nc,\n\t\t_regexp_plus_c,\n\n\t\t_regexp_urlenc_space_nc,\n\t\t_regexp_urlenc_space_c,\n\t\t_regexp_http_validation,\n\n\t\t_regexp_any_uppercase_nc,\n\t\t_regexp_any_uppercase_c,\n\n\t\t_regexp_is_ms_pref:\n\t\treturn pattern, nil\n\t}\n\n\t// TODO If without \\, if without (?=, (?!, then another shortcut\n\n\tparser := _RegExp_parser{\n\t\tstr: pattern,\n\t\tlength: len(pattern),\n\t\tgoRegexp: bytes.NewBuffer(make([]byte, 0, 3*len(pattern)/2)),\n\t}\n\tparser.read() // Pull in the first character\n\tparser.scan()\n\tvar err error\n\tif len(parser.errors) > 0 {\n\t\terr = parser.errors[0]\n\t}\n\tif parser.invalid {\n\t\tlog.Printf(\"Input: regexp=[%s]\\n\", pattern)\n\t\tlog.Printf(\"Output: regexp=[%s] err=[%s]\\n\", parser.goRegexp.String(), err)\n\t\treturn \"\", err\n\t}\n\n\t// Might not be re2 compatible, but is still a valid JavaScript RegExp\n\treturn parser.goRegexp.String(), err\n}", "func (c Configuration) compileRegex(listofPaths []string) []*regexp.Regexp {\n\tlogger := c.logger()\n\tvar regexpObjects []*regexp.Regexp\n\tfor _, path := range listofPaths {\n\t\treg, err := regexp.Compile(path)\n\t\tif err != nil {\n\t\t\tlogger.Error().Err(err).Msgf(\"Error while compiling regex: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tregexpObjects = append(regexpObjects, reg)\n\t}\n\treturn regexpObjects\n}", "func commute(r string, arch arch) []string {\n\tmatch, cond, result := Rule{rule: r}.parse()\n\ta := commute1(match, varCount(match), arch)\n\tfor i, m := range a {\n\t\tif cond != \"\" {\n\t\t\tm += \" && \" + cond\n\t\t}\n\t\tm += \" -> \" + result\n\t\ta[i] = m\n\t}\n\tif len(a) == 1 && normalizeWhitespace(r) != normalizeWhitespace(a[0]) {\n\t\tfmt.Println(normalizeWhitespace(r))\n\t\tfmt.Println(normalizeWhitespace(a[0]))\n\t\tlog.Fatalf(\"commute() is not the identity for noncommuting rule\")\n\t}\n\tif false && len(a) > 1 {\n\t\tfmt.Println(r)\n\t\tfor _, x := range a {\n\t\t\tfmt.Println(\" \" + x)\n\t\t}\n\t}\n\treturn a\n}", "func Multi(matches ...Matcher) Matcher {\n\treturn multiMatcher(matches)\n}", "func GlobPatterns(fSys filesys.FileSystem, patterns []string) ([]string, error) {\n\tvar result []string\n\tfor _, pattern := range patterns {\n\t\tfiles, err := fSys.Glob(pattern)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(files) == 0 {\n\t\t\tlog.Printf(\"%s has no match\", pattern)\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, files...)\n\t}\n\treturn result, nil\n}", "func NewRegexPatternSet(ctx *pulumi.Context,\n\tname string, args *RegexPatternSetArgs, opts ...pulumi.ResourceOption) (*RegexPatternSet, error) {\n\tif args == nil {\n\t\targs = &RegexPatternSetArgs{}\n\t}\n\n\tvar resource RegexPatternSet\n\terr := ctx.RegisterResource(\"aws:waf/regexPatternSet:RegexPatternSet\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client PatternClient) BatchAddPatternsSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func RegexFromGlobWithOptions(glob string, config Options) string {\n\treStr := \"\"\n\n\tdelimiter := '/'\n\tif config.Delimiter != 0 {\n\t\tdelimiter = config.Delimiter\n\t}\n\n\tdelimiterOutsideClass, delimiterInsideClass := escapeDelimiter(delimiter)\n\n\tinGroup := false\n\n\tglobLen := len(glob)\n\n\tfor i := 0; i < globLen; i++ {\n\t\tc := glob[i]\n\n\t\tswitch c {\n\t\tcase '/', '$', '^', '+', '.', '(', ')', '=', '!', '|':\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '?':\n\t\t\tif config.Extended {\n\t\t\t\treStr += \".\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '[', ']':\n\t\t\tif config.Extended {\n\t\t\t\treStr += string(c)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '{':\n\t\t\tif config.Extended {\n\t\t\t\tinGroup = true\n\t\t\t\treStr += \"(\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '}':\n\t\t\tif config.Extended {\n\t\t\t\tinGroup = false\n\t\t\t\treStr += \")\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase ',':\n\t\t\tif inGroup {\n\t\t\t\treStr += \"|\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '*':\n\t\t\t// Move over all consecutive \"*\"'s.\n\t\t\t// Also store the previous and next characters\n\t\t\tvar nextChar, prevChar rune\n\t\t\tif i > 0 {\n\t\t\t\tprevChar = rune(glob[i-1])\n\t\t\t}\n\t\t\tstarCount := 1\n\t\t\tfor i < globLen-1 && glob[i+1] == '*' {\n\t\t\t\tstarCount++\n\t\t\t\ti++\n\t\t\t}\n\n\t\t\tif i < globLen-1 {\n\t\t\t\tnextChar = rune(glob[i+1])\n\t\t\t}\n\n\t\t\tif !config.GlobStar {\n\t\t\t\t// globstar is disabled, so treat any number of \"*\" as one\n\t\t\t\treStr += \".*\"\n\t\t\t} else {\n\t\t\t\t// globstar is enabled, so determine if this is a globstar segment\n\t\t\t\tisGlobstar := starCount > 1 && // multiple \"*\"'s\n\t\t\t\t\t(prevChar == delimiter || prevChar == 0) && // from the start of the segment\n\t\t\t\t\t(nextChar == delimiter || nextChar == 0) // to the end of the segment\n\n\t\t\t\tif isGlobstar {\n\t\t\t\t\t// it's a globstar, so match zero or more path segments\n\t\t\t\t\treStr += \"(?:(?:[^\" + delimiterInsideClass + \"]*(?:\" + delimiterOutsideClass + \"|$))*)\"\n\t\t\t\t\ti++ // move over the delimiter\n\t\t\t\t} else {\n\t\t\t\t\t// it's not a globstar, so only match one path segment\n\t\t\t\t\treStr += \"(?:[^\" + delimiterInsideClass + \"]*)\"\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\treStr += string(c)\n\t\t}\n\t}\n\n\treturn \"^\" + reStr + \"$\"\n}", "func optional(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `?`)\n}", "func optional(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `?`)\n}", "func optional(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(group(expression(res...)).String() + `?`)\n}", "func match(requestStr string, patterns []string) (ok bool, prefixStr, suffixStr string) {\n\tvar str, last string\n\tvar err error\n\tln := len(patterns)\n\tfor j := 0; j < ln && !ok; j++ {\n\t\tpattern := patterns[j]\n\t\tstr = requestStr\n\t\tlast = \"\"\n\t\tfor last != str && !ok && err == nil {\n\t\t\tok, err = path.Match(pattern, str)\n\t\t\tif err == nil {\n\t\t\t\tif ok {\n\t\t\t\t\tprefixStr = str\n\t\t\t\t\tsuffixStr = requestStr[len(str):]\n\t\t\t\t} else {\n\t\t\t\t\tlast = str\n\t\t\t\t\tstr = filepath.Dir(str)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func NewRegexpSet(patterns []string) (retVal *RegexpSet, err error) {\n\tfor _, pattern := range patterns {\n\t\t_, err := regexp.Compile(pattern)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Invalid regular pattern: '%v'.\\n\", pattern)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &RegexpSet{patterns}, nil\n}", "func (c *Config) CompileRegexps() error {\n\tfor _, licenseRegexps := range c.Licenses {\n\t\tlicenseRegexp := strings.Join(licenseRegexps, \"\\n\")\n\t\tre, err := regexp.Compile(licenseRegexp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.licensesRegexps = append(c.licensesRegexps, re)\n\t}\n\n\tc.accept = make([]rule, 0, len(c.Accept))\n\tfor _, rule := range c.Accept {\n\t\tc.accept = append(c.accept, accept(rule))\n\t}\n\n\tc.reject = make([]rule, 0, len(c.Reject))\n\tfor _, rule := range c.Reject {\n\t\tc.reject = append(c.reject, reject(rule))\n\t}\n\n\treturn nil\n}", "func (m MatchPattern) Apply(ctx context.Context, results *[]github.CodeResult) *[]github.CodeResult {\n\treturn filterResultsWith(results, getPatternFilterFunc(m.Pattern))\n}", "func groupOnlyMatches(group *syntax.Regexp, s string) bool {\n\tswitch group.Op {\n\tcase syntax.OpLiteral:\n\t\tfor _, r := range group.Rune {\n\t\t\tif !strings.ContainsRune(s, r) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\n\tcase syntax.OpCharClass:\n\t\tfor i := 0; i < len(group.Rune); i += 2 {\n\t\t\tlo, hi := group.Rune[i], group.Rune[i+1]\n\t\t\tfor r := lo; r <= hi; r++ {\n\t\t\t\tif !strings.ContainsRune(s, r) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\n\tcase syntax.OpStar, syntax.OpPlus, syntax.OpRepeat, syntax.OpQuest, syntax.OpCapture:\n\t\treturn groupOnlyMatches(group.Sub[0], s)\n\n\tcase syntax.OpConcat, syntax.OpAlternate:\n\t\tfor _, sub := range group.Sub {\n\t\t\tif !groupOnlyMatches(sub, s) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func ApplyPattern(patterns []Pattern, depth int, value string) (result Match, newValue string) {\n\tif depth >= len(patterns) {\n\t\treturn NoPattern, value\n\t}\n\tpattern := patterns[depth]\n\tif pattern.Expression == nil {\n\t\tif pattern.Subtitution != \"\" {\n\t\t\tpanic(\"unexpected substitution with nil pattern expression\")\n\t\t}\n\t\treturn Matched, value\n\t}\n\tif pattern.Expression.MatchString(value) {\n\t\tif pattern.Subtitution == \"\" {\n\t\t\treturn Matched, value\n\t\t}\n\t\treturn Matched, pattern.Expression.ReplaceAllString(value, pattern.Subtitution)\n\t}\n\treturn NotMatched, value\n}", "func GetPatterns(org string, name string, long bool) {\n\tmsgPrinter := i18n.GetMessagePrinter()\n\n\t// set env to call agbot url\n\tif err := os.Setenv(\"HORIZON_URL\", cliutils.GetAgbotUrlBase()); err != nil {\n\t\tcliutils.Fatal(cliutils.CLI_GENERAL_ERROR, msgPrinter.Sprintf(\"unable to set env var 'HORIZON_URL', error %v\", err))\n\t}\n\n\tif name != \"\" && org == \"\" {\n\t\tcliutils.Fatal(cliutils.CLI_INPUT_ERROR, msgPrinter.Sprintf(\"org must be specified with -o when pattern name is specified.\"))\n\t}\n\n\t// base url upon which to add arguments and flag\n\tpatUrl := \"cache/pattern\"\n\t// if org is specified add it to url\n\t// if name is specified add it to url and ignore value for long\n\tif org != \"\" {\n\t\tpatUrl = fmt.Sprintf(\"%v/%v\", patUrl, org)\n\t\tif name != \"\" {\n\t\t\tpatUrl = fmt.Sprintf(\"%v/%v\", patUrl, name)\n\t\t\tlong = false\n\t\t}\n\t}\n\n\tif long {\n\t\t// Show detailed info if long, else only orgs and names\n\t\tpatUrl = fmt.Sprintf(\"%v?long==1\", patUrl)\n\t\tif org == \"\" {\n\t\t\t// Get the agbot servedorgs info\n\t\t\tpatInfo := map[string]map[string]*agreementbot.PatternEntry{} //the structure we will output\n\n\t\t\tcliutils.HorizonGet(patUrl, []int{200}, &patInfo, false)\n\n\t\t\t// Output the combined info\n\t\t\tjsonBytes, err := json.MarshalIndent(patInfo, \"\", cliutils.JSON_INDENT)\n\t\t\tif err != nil {\n\t\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal output: %v\", err))\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\\n\", jsonBytes)\n\n\t\t} else if name == \"\" {\n\t\t\t// Get the agbot servedorgs info\n\t\t\tpatInfo := map[string]*agreementbot.PatternEntry{} //the structure we will output\n\n\t\t\tif httpCode, _ := cliutils.HorizonGet(patUrl, []int{200, 404}, &patInfo, false); httpCode == 404 {\n\t\t\t\tmsgPrinter.Printf(\"%v does not exist in the pattern management cache.\", org)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t} else {\n\t\t\t\t// Output the combined info\n\t\t\t\tjsonBytes, err := json.MarshalIndent(patInfo, \"\", cliutils.JSON_INDENT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal output: %v\", err))\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%s\\n\", jsonBytes)\n\t\t\t}\n\t\t}\n\n\t} else if org != \"\" {\n\t\t// display detailed info of pattern if name is specified, else only list names\n\t\tif name != \"\" {\n\t\t\tvar patInfo *agreementbot.PatternEntry //the structure we will output\n\t\t\tif httpCode, _ := cliutils.HorizonGet(patUrl, []int{200, 404}, &patInfo, false); httpCode == 404 {\n\t\t\t\tmsgPrinter.Printf(\"%v/%v does not exist in the pattern management cache.\", org, name)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t} else {\n\t\t\t\t// Output the combined info\n\t\t\t\tjsonBytes, err := json.MarshalIndent(patInfo, \"\", cliutils.JSON_INDENT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal output: %v\", err))\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%s\\n\", jsonBytes)\n\t\t\t}\n\t\t} else {\n\n\t\t\tpatInfo := []string{} //the structure we will output\n\t\t\tif httpCode, _ := cliutils.HorizonGet(patUrl, []int{200, 404}, &patInfo, false); httpCode == 404 {\n\t\t\t\tmsgPrinter.Printf(\"%v does not exist in the pattern management cache.\", org)\n\t\t\t\tmsgPrinter.Println()\n\t\t\t} else {\n\t\t\t\t// Output the combined info\n\t\t\t\tjsonBytes, err := json.MarshalIndent(patInfo, \"\", cliutils.JSON_INDENT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal output: %v\", err))\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%s\\n\", jsonBytes)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Get the agbot servedorgs info\n\t\tpatInfo := map[string][]string{} //the structure we will output\n\t\tcliutils.HorizonGet(patUrl, []int{200}, &patInfo, false)\n\n\t\t// Output the combined info\n\t\tjsonBytes, err := json.MarshalIndent(patInfo, \"\", cliutils.JSON_INDENT)\n\t\tif err != nil {\n\t\t\tcliutils.Fatal(cliutils.JSON_PARSING_ERROR, msgPrinter.Sprintf(\"failed to marshal output: %v\", err))\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", jsonBytes)\n\t}\n\n}", "func expandOr(r string) []string {\n\t// Find every occurrence of |-separated things.\n\t// They look like MOV(B|W|L|Q|SS|SD)load or MOV(Q|L)loadidx(1|8).\n\t// Generate rules selecting one case from each |-form.\n\n\t// Count width of |-forms. They must match.\n\tn := 1\n\tfor _, idx := range findAllOpcode(r, -1) {\n\t\tif excludeFromExpansion(r, idx) {\n\t\t\tcontinue\n\t\t}\n\t\ts := r[idx[0]:idx[1]]\n\t\tc := strings.Count(s, \"|\") + 1\n\t\tif c == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif n > 1 && n != c {\n\t\t\tlog.Fatalf(\"'|' count doesn't match in %s: both %d and %d\\n\", r, n, c)\n\t\t}\n\t\tn = c\n\t}\n\tif n == 1 {\n\t\t// No |-form in this rule.\n\t\treturn []string{r}\n\t}\n\t// Build each new rule.\n\tres := make([]string, n)\n\tfor i := 0; i < n; i++ {\n\t\tbuf := new(strings.Builder)\n\t\tx := 0\n\t\tfor _, idx := range findAllOpcode(r, -1) {\n\t\t\tif excludeFromExpansion(r, idx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbuf.WriteString(r[x:idx[0]]) // write bytes we've skipped over so far\n\t\t\ts := r[idx[0]+1 : idx[1]-1] // remove leading \"(\" and trailing \")\"\n\t\t\tbuf.WriteString(strings.Split(s, \"|\")[i]) // write the op component for this rule\n\t\t\tx = idx[1] // note that we've written more bytes\n\t\t}\n\t\tbuf.WriteString(r[x:])\n\t\tres[i] = buf.String()\n\t}\n\treturn res\n}", "func matches(regex string, input string) bool {\n\tif len(regex) == 0 && len(input) == 0 {\n\t\treturn true\n\t}\n\tvar fi, fr, sr, tr byte\n\tif len(regex) > 0 {\n\t\tfr = regex[0]\n\t}\n\tif len(regex) > 1 {\n\t\tsr = regex[1]\n\t}\n\tif len(regex) > 2 {\n\t\ttr = regex[2]\n\t}\n\tif len(input) > 0 {\n\t\tfi = input[0]\n\t}\n\tif sr == '*' {\n\t\tif fr == fi {\n\t\t\treturn matches(regex, input[1:])\n\t\t} else {\n\t\t\tfor i := 0; i < len(input); i++ {\n\t\t\t\tif input[i] == tr {\n\t\t\t\t\treturn matches(regex[2:], input[i:])\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tif fr == fi {\n\t\t\treturn matches(regex[1:], input[1:])\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func parseGlobPatterns(globPatterns []string) []glob.Glob {\n\tresults := make([]glob.Glob, 0)\n\tfor _, exp := range globPatterns {\n\t\tglobP, err := glob.Compile(exp)\n\t\tif err != nil {\n\t\t\tutils.Log.Errorln(\"Ignoring invalid glob pattern provided as cache control matcher rule\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresults = append(results, globP)\n\t}\n\treturn results\n}", "func (c *WAF) ListRegexPatternSetsWithContext(ctx aws.Context, input *ListRegexPatternSetsInput, opts ...request.Option) (*ListRegexPatternSetsOutput, error) {\n\treq, out := c.ListRegexPatternSetsRequest(input)\n\treq.SetContext(ctx)\n\treq.ApplyOptions(opts...)\n\treturn out, req.Send()\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func CompositeMatchesReverse(matches [][]uint32) []uint32 {\n\tswitch len(matches) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn matches[0]\n\tdefault:\n\t\tresult := make([]uint32, 0, 5)\n\t\tfor i := len(matches) - 1; i >= 0; i-- {\n\t\t\tresult = append(result, matches[i]...)\n\t\t}\n\t\treturn result\n\t}\n}", "func wildCardToRegexp(pattern string) string {\n\tvar result strings.Builder\n\tfor i, literal := range strings.Split(pattern, \"*\") {\n\n\t\t// Replace * with .*\n\t\tif i > 0 {\n\t\t\tresult.WriteString(\".*\")\n\t\t}\n\n\t\t// Quote any regular expression meta characters in the\n\t\t// literal text.\n\t\tresult.WriteString(regexp.QuoteMeta(literal))\n\t}\n\treturn result.String()\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func (m *Builder) Compile() (*MultiGlob, error) {\n\tvar final *parser.Node\n\tfor _, p := range m.patterns {\n\t\tif final == nil {\n\t\t\tfinal = p\n\t\t} else {\n\t\t\tfinal = parser.Merge(final, p)\n\t\t}\n\t}\n\n\tpatterns := make(map[string]*parser.Node)\n\tfor k, v := range m.patterns {\n\t\tpatterns[k] = v\n\t}\n\n\treturn &MultiGlob{\n\t\tnode: final,\n\t\tpatterns: patterns,\n\t}, nil\n}", "func getCombinedText(values ...stringable) string {\n\tvar result strings.Builder\n\tfor _, v := range values {\n\t\t_, _ = result.WriteString(v.toString())\n\t}\n\treturn result.String()\n}", "func (c *Combine) Combine(vars []interface{}) (interface{}, error) {\n\tvar combiner interface {\n\t\tCombine(vars []interface{}) (interface{}, error)\n\t}\n\n\tswitch c.Strategy {\n\tcase CombineStrategyString:\n\t\tcombiner = c.String\n\tdefault:\n\t\treturn nil, errors.Errorf(errFmtCombineStrategyNotSupported, string(c.Strategy))\n\t}\n\n\t// Check for nil interface requires reflection.\n\tif reflect.ValueOf(combiner).IsNil() {\n\t\treturn nil, errors.Errorf(errFmtCombineConfigMissing, string(c.Strategy))\n\t}\n\tout, err := combiner.Combine(vars)\n\t// Note: There are currently no tests or triggers to exercise this error as\n\t// our only strategy (\"String\") uses fmt.Sprintf, which cannot return an error.\n\treturn out, errors.Wrapf(err, errFmtCombineStrategyFailed, string(c.Strategy))\n}", "func Combine(c v1.Combine, vars []any) (any, error) {\n\tvar out any\n\tvar err error\n\n\tswitch c.Strategy {\n\tcase v1.CombineStrategyString:\n\t\tif c.String == nil {\n\t\t\treturn nil, errors.Errorf(errFmtCombineConfigMissing, c.Strategy)\n\t\t}\n\t\tout, err = CombineString(c.String.Format, vars)\n\tdefault:\n\t\treturn nil, errors.Errorf(errFmtCombineStrategyNotSupported, c.Strategy)\n\t}\n\n\t// Note: There are currently no tests or triggers to exercise this error as\n\t// our only strategy (\"String\") uses fmt.Sprintf, which cannot return an error.\n\treturn out, errors.Wrapf(err, errFmtCombineStrategyFailed, string(c.Strategy))\n}", "func GlobMany(filePatterns []string) ([]string, error) {\n\tvar files []string\n\tfor _, filePattern := range filePatterns {\n\t\tglobResult, err := Glob(filePattern)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles = append(files, globResult...)\n\t}\n\treturn files, nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func TestRegexMatch(t *testing.T) {\n\n\tinput := `N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N`\n\n\tfmt.Println(NormalizedSummary(input, false))\n\n}", "func R(pattern string) *regexp.Regexp {\n\treturn regexp.MustCompile(pattern)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesPtrOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPattern {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesPtrOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPattern {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func rawPattern(s string) *regexp.Regexp {\n\treturn regexp.MustCompile(regexp.QuoteMeta(s))\n}", "func MatchAny(values ...string) Matcher {\n\tdistinct := make([]string, 0, len(values))\n\tdistinct = misc.AppendDistinct(distinct, values...)\n\tfor i, s := range distinct {\n\t\tdistinct[i] = regexp.QuoteMeta(s)\n\t}\n\tpattern := fmt.Sprintf(`^(%s)$`, strings.Join(distinct, \"|\"))\n\trx, _ := regexp.Compile(pattern)\n\treturn rx\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesOutput) MatchPatterns() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookies) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPattern {\n\t\treturn v.MatchPatterns\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchCookiesMatchPatternArrayOutput)\n}", "func OnePlusRunes(parser Parser) Parser {\n\treturn ParserFunc(func(s Scanner) (Result, Scanner) {\n\t\tr, next := parser.Parse(s)\n\t\tif !r.Matched() {\n\t\t\treturn r, next\n\t\t}\n\n\t\tfor {\n\t\t\tr, maybeNext := parser.Parse(next)\n\t\t\tif !r.Matched() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnext = maybeNext\n\t\t}\n\n\t\treturn Result{\n\t\t\tRunes: s.Between(next),\n\t\t}, next\n\t})\n}" ]
[ "0.55337286", "0.5300413", "0.5257774", "0.52043813", "0.5074849", "0.50482696", "0.5016077", "0.5016077", "0.5016077", "0.500318", "0.4974787", "0.48794165", "0.47393712", "0.47348255", "0.47301033", "0.47214684", "0.47154647", "0.4709186", "0.4682616", "0.46738783", "0.46599308", "0.46455568", "0.46208686", "0.46208686", "0.46208686", "0.46124747", "0.4611281", "0.45972332", "0.45955458", "0.45916858", "0.45898062", "0.45695597", "0.45695597", "0.45695597", "0.45625126", "0.4561457", "0.45309898", "0.45085308", "0.4494995", "0.44868872", "0.44789043", "0.4476483", "0.44326738", "0.44317463", "0.4430737", "0.4422958", "0.4422958", "0.4422958", "0.44083375", "0.44018316", "0.43853262", "0.43844536", "0.4373365", "0.43643337", "0.43599552", "0.43591592", "0.43535462", "0.43386683", "0.43348214", "0.4333307", "0.43310615", "0.43214864", "0.4296465", "0.42956322", "0.42889696", "0.4287048", "0.42864802", "0.42864802", "0.42864802", "0.4275486", "0.42701063", "0.42686903", "0.4267419", "0.4246094", "0.423079", "0.4228398", "0.4228221", "0.42030558", "0.41783518", "0.41651258", "0.4157544", "0.41472772", "0.4137469", "0.41352716", "0.41352266", "0.4129596", "0.41261363", "0.41243", "0.412173", "0.4121638", "0.41163874", "0.41154367", "0.41132572", "0.4112732", "0.41082472", "0.41078123", "0.410573", "0.41053906", "0.41032097", "0.41013536" ]
0.8576184
0
Given finds the right tracker for lookup given a story issue.
func Given(tag string, trackers []LookupTracker) LookupTracker { for _, tracker := range trackers { match := tracker.AllPatterns().FindAllStringSubmatch(tag, -1) if len(match) > 0 { return tracker } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Reitveld) Issue(issue int64) (*Issue, error) {\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(\"https://codereview.chromium.org/api/%d/\", issue), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to build request: %s\", err)\n\t}\n\tresp, err := r.client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to retrieve issue info: %s\", err)\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"No such issue %d\", issue)\n\t}\n\tdec := json.NewDecoder(resp.Body)\n\tinfo := &Issue{}\n\tif err := dec.Decode(info); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read Reitveld issue info: %s\", err)\n\n\t}\n\treturn info, nil\n}", "func getJiraIssue(issueKey string, jiraClient *jira.Client) (JiraIssue, error) {\n\n\tvar jiraIssue JiraIssue\n\n\tissue, _, err := jiraClient.Issue.Get(issueKey, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot find %v\", issueKey)\n\t\treturn jiraIssue, err\n\t}\n\n\t//Fields from ticket itself\n\tjiraIssue.Key = issue.Key //Task key\n\tjiraIssue.Summary = issue.Fields.Summary //Task name\n\tjiraIssue.Estimation = issue.Fields.TimeTracking.OriginalEstimate //Estimation\n\n\tif issue.Fields.Parent != nil {\n\t\tjiraIssue.ParentKey = issue.Fields.Parent.Key //Parent task key\n\t}\n\n\t//Fields from parent ticket\n\tif jiraIssue.ParentKey == \"\" {\n\t\treturn jiraIssue, fmt.Errorf(\"issue %v does not have parent ticket, do nothing\", issueKey)\n\t}\n\tissue, _, err = jiraClient.Issue.Get(jiraIssue.ParentKey, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot find parent ticket %v\", issueKey)\n\t\treturn jiraIssue, err\n\t}\n\n\tjiraIssue.ParentSummary = issue.Fields.Summary //Parent task summary\n\tjiraIssue.ParentDescription = issue.Fields.Description\n\n\t//Example of issue.Fields.Unknowns[\"customfield_10416\"]:\n\t//customfield_10416:map[id:12016 self:https://inchcapeglobal.atlassian.net/rest/api/2/customFieldOption/12016 value:IMP_22]\n\tbudgetMap := issue.Fields.Unknowns[\"customfield_10416\"] //Budget\n\tbudgetMap2, ok := budgetMap.(map[string]interface{})\n\tif ok {\n\t\tjiraIssue.ParentBudget = budgetMap2[\"value\"].(string)\n\t}\n\n\treturn jiraIssue, nil\n\n}", "func getMatchingSprintForTask(sprints []*jiraCommunicator.Sprint,\n\ttask *mavenlinkCommunicator.Task) *jiraCommunicator.Sprint {\n\n\tvar taskId int32\n\ttaskId64, taskIdErr := strconv.ParseInt(task.Id, 10, 32)\n\tif taskIdErr != nil {\n\t\treturn nil\n\t}\n\ttaskId = int32(taskId64)\n\ttaskInDb := doesTaskExistInDatasource(taskId)\n\tif nil != taskInDb {\n\t\tfor _, sprint := range sprints {\n\t\t\tif sprint.Id == taskInDb.Source1SprintId {\n\t\t\t\texists := doesSprintAndTaskExistInDatasource(taskId, sprint.Id)\n\t\t\t\tif exists == true {\n\t\t\t\t\treturn sprint\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func GetAnIssue(db *gorm.DB, issue *Issue, id string) (err error) {\n\tif err := db.Where(\"id = ?\", id).First(issue).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func getIssuesInfo(p *api.IssuePayload) (issueTitle, link, by, operator, operateResult, assignees string) {\n\tissueTitle = fmt.Sprintf(\"[Issue-%s #%d]: %s\\n%s\", p.Repository.FullName, p.Issue.Index, p.Action, p.Issue.Title)\n\tassignList := p.Issue.Assignees\n\tassignStringList := make([]string, len(assignList))\n\n\tfor i, user := range assignList {\n\t\tassignStringList[i] = user.UserName\n\t}\n\tif p.Action == api.HookIssueAssigned {\n\t\toperateResult = fmt.Sprintf(\"%s assign this to %s\", p.Sender.UserName, assignList[len(assignList)-1].UserName)\n\t} else if p.Action == api.HookIssueUnassigned {\n\t\toperateResult = fmt.Sprintf(\"%s unassigned this for someone\", p.Sender.UserName)\n\t} else if p.Action == api.HookIssueMilestoned {\n\t\toperateResult = fmt.Sprintf(\"%s/milestone/%d\", p.Repository.HTMLURL, p.Issue.Milestone.ID)\n\t}\n\tlink = p.Issue.HTMLURL\n\tby = fmt.Sprintf(\"Issue by %s\", p.Issue.Poster.UserName)\n\tif len(assignStringList) > 0 {\n\t\tassignees = fmt.Sprintf(\"Assignees: %s\", strings.Join(assignStringList, \", \"))\n\t}\n\toperator = fmt.Sprintf(\"Operator: %s\", p.Sender.UserName)\n\treturn issueTitle, link, by, operator, operateResult, assignees\n}", "func (s *IssueService) Issue(id int64) (*domain.Issue, error) {\n\treturn s.IssueRepository.GetById(id)\n}", "func (rg *reportGenerator) getExistingIssue() *github.Issue {\n\tissues, response, err := rg.client.Issues.ListByRepo(\n\t\trg.ctx,\n\t\trg.envVariables[projectUsernameKey],\n\t\trg.envVariables[projectRepoNameKey],\n\t\t&github.IssueListByRepoOptions{\n\t\t\tState: \"open\",\n\t\t},\n\t)\n\tif err != nil {\n\t\trg.logger.Fatal(\"Failed to search GitHub Issues\", zap.Error(err))\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\trg.handleBadResponses(response)\n\t}\n\n\trequiredTitle := rg.getIssueTitle()\n\tfor _, issue := range issues {\n\t\tif *issue.Title == requiredTitle {\n\t\t\treturn issue\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *Store) GetIssue(id uint) (*Issue, error) {\n\tfor _, issue := range s.Issues {\n\t\tif issue.ID == id {\n\t\t\treturn issue, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"no issue with id %d\", id)\n}", "func (it *IssueTracker) IssueURLFor(taskID string) string {\n\treturn it.issueAPIOrigin() + it.taskURLFrom(taskID)\n}", "func GetIssue(params martini.Params) string {\n\tnumber, err := strconv.Atoi(params[\"issue\"])\n\tif err != nil {\n\t\treturn GenerateErrorMessage(err)\n\t}\n\n\tmsg := messages.GetIssue{\n\t\tIssue: &messages.Issue{\n\t\t\tID: params[\"issue\"],\n\t\t\tNumber: number,\n\t\t\tOrg: params[\"owner\"],\n\t\t\tRepo: params[\"repo\"],\n\t\t},\n\t\tConfig: config(),\n\t}\n\tresponse := Request(\"issues.details\", msg)\n\n\treturn response\n}", "func (c *client) GetIssue(org, repo string, number int) (*Issue, error) {\n\tdurationLogger := c.log(\"GetIssue\", org, repo, number)\n\tdefer durationLogger()\n\n\tvar i Issue\n\t_, err := c.request(&request{\n\t\t// allow emoji\n\t\t// https://developer.github.com/changes/2018-02-22-label-description-search-preview/\n\t\taccept: \"application/vnd.github.symmetra-preview+json\",\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/issues/%d\", org, repo, number),\n\t\torg: org,\n\t\texitCodes: []int{200},\n\t}, &i)\n\treturn &i, err\n}", "func (it IssueTracker) GetBug(project string, id int) (*Issue, error) {\n\terrFmt := fmt.Sprintf(\"error retrieving issue %d: %s\", id, \"%s\")\n\tif !it.IsAuthenticated() {\n\t\treturn nil, fmt.Errorf(errFmt, \"user is not authenticated!\")\n\t}\n\trequestURL := ISSUE_API_URL + project + \"/issues/\" + strconv.Itoa(id)\n\tresp, err := it.OAuthTransport.Client().Get(requestURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(errFmt, fmt.Sprintf(\n\t\t\t\"issue tracker returned code %d:%v\", resp.StatusCode, string(body)))\n\t}\n\tvar issue Issue\n\tif err := json.Unmarshal(body, &issue); err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, err)\n\t}\n\treturn &issue, nil\n}", "func IssueGet(project string, issueNum int) (*gitlab.Issue, error) {\n\tp, err := FindProject(project)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tissue, _, err := lab.Issues.GetIssue(p.ID, issueNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn issue, nil\n}", "func (j *DSGitHub) GetFirstIssueAttention(issue map[string]interface{}) (dt time.Time) {\n\tiUserLogin, _ := Dig(issue, []string{\"user\", \"login\"}, false, true)\n\tuserLogin, _ := iUserLogin.(string)\n\tdts := []time.Time{}\n\tudts := []time.Time{}\n\tiComments, ok := issue[\"comments_data\"]\n\tif ok && iComments != nil {\n\t\tary, _ := iComments.([]interface{})\n\t\tfor _, iComment := range ary {\n\t\t\tcomment, _ := iComment.(map[string]interface{})\n\t\t\tiCommentLogin, _ := Dig(comment, []string{\"user\", \"login\"}, false, true)\n\t\t\tcommentLogin, _ := iCommentLogin.(string)\n\t\t\tiCreatedAt, _ := comment[\"created_at\"]\n\t\t\tcreatedAt, _ := TimeParseInterfaceString(iCreatedAt)\n\t\t\tif userLogin == commentLogin {\n\t\t\t\tudts = append(udts, createdAt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdts = append(dts, createdAt)\n\t\t}\n\t}\n\t// NOTE: p2o does it but reactions API doesn't have any datetimefield specifying when reaction was made\n\t/*\n\t\tiReactions, ok := issue[\"reactions_data\"]\n\t\tif ok && iReactions != nil {\n\t\t\tary, _ := iReactions.([]interface{})\n\t\t\tfor _, iReaction := range ary {\n\t\t\t\treaction, _ := iReaction.(map[string]interface{})\n\t\t\t\tiReactionLogin, _ := Dig(reaction, []string{\"user\", \"login\"}, false, true)\n\t\t\t\treactionLogin, _ := iReactionLogin.(string)\n\t\t\t\tif userLogin == reactionLogin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tiCreatedAt, _ := reaction[\"created_at\"]\n\t\t\t\tcreatedAt, _ := TimeParseInterfaceString(iCreatedAt)\n\t\t\t\tdts = append(dts, createdAt)\n\t\t\t}\n\t\t}\n\t*/\n\tnDts := len(dts)\n\tif nDts == 0 {\n\t\t// If there was no action of anybody else that author's, then fallback to author's actions\n\t\tdts = udts\n\t\tnDts = len(dts)\n\t}\n\tswitch nDts {\n\tcase 0:\n\t\tdt = time.Now()\n\tcase 1:\n\t\tdt = dts[0]\n\tdefault:\n\t\tsort.Slice(dts, func(i, j int) bool {\n\t\t\treturn dts[i].Before(dts[j])\n\t\t})\n\t\tdt = dts[0]\n\t}\n\treturn\n}", "func (registry *Registry) Lookup(handle string) *task.Task {\n\t// TODO: Refactor the interface here to explicitly add an `ok`\n\t// return value (in the style of reading a map[...]...)\n\t// to differentiate a present nil value return vs. a\n\t// not-present-at-all value.\n\tregistry.lock.RLock()\n\tdefer registry.lock.RUnlock()\n\n\tif t, exists := registry.db[handle]; exists {\n\t\treturn t\n\t}\n\n\treturn nil\n}", "func ConvertIssue(repostitory string, in github.Issue) Issue {\n\n\tissue := Issue{\n\t\tNumber: *in.Number,\n\t\tState: *in.State,\n\t\tTitle: *in.Title,\n\t\tLabels: []Label{},\n\t\tClosedAt: in.ClosedAt,\n\t\tCreatedAt: in.CreatedAt,\n\t\tUpdatedAt: in.UpdatedAt,\n\t\tRepository: repostitory,\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintln(os.Stderr, in)\n\t\t\tpanic(\"unknown data\")\n\t\t}\n\t}()\n\n\tif in.Body != nil {\n\t\tissue.Body = *in.Body\n\t}\n\n\tif in.User != nil {\n\t\tissue.User = *in.User.Login\n\t}\n\n\tif in.Assignee != nil {\n\t\tissue.Assignee = *in.Assignee.Login\n\t}\n\n\tif in.Milestone != nil {\n\t\tissue.Milestone = *in.Milestone.Title\n\t}\n\n\tfor _, ghLabel := range in.Labels {\n\t\tissue.Labels = append(issue.Labels, ConvertLabel(ghLabel))\n\t}\n\n\treturn issue\n}", "func (g Gitlab) ResolveIssue(ctx context.Context, projectID, issueIID IntID, resolution Resolution) error {\n\t// Try to add a comment.\n\terr1 := trace.Wrap(g.PostResolutionComment(ctx, projectID, issueIID, resolution))\n\n\t// Try to close the issue.\n\terr2 := trace.Wrap(g.CloseIssue(ctx, projectID, issueIID, resolution))\n\n\treturn trace.NewAggregate(err1, err2)\n}", "func (c *client) GetIssue(\n\tpid interface{},\n\tid int,\n\toptions ...glab.RequestOptionFunc,\n) (*glab.Issue, *glab.Response, error) {\n\treturn c.c.Issues.GetIssue(pid, id, options...)\n}", "func (g Gitlab) GetIssue(ctx context.Context, projectID, issueIID IntID) (Issue, error) {\n\tvar issue Issue\n\tresp, err := g.NewRequest(ctx).\n\t\tSetResult(&issue).\n\t\tGet(g.APIV4URL(\"projects\", projectID, \"issues\", issueIID))\n\tif err != nil {\n\t\treturn Issue{}, trace.Wrap(err)\n\t}\n\tif resp.IsError() {\n\t\treturn Issue{}, trace.Wrap(responseError(resp))\n\t}\n\treturn issue, nil\n}", "func (a *RepoAPI) readIssue(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\tname := m.Get(\"name\").Str()\n\treference := m.Get(\"reference\").Str()\n\treturn rpc.Success(util.Map{\n\t\t\"data\": a.mods.Repo.ReadIssue(name, reference),\n\t})\n}", "func GetIssue(owner, repo string, params map[string]string, issueN int) (*Issue, error) {\n\turl := APIURL + strings.Join([]string{\"repos\", owner, repo, \"issues\", strconv.Itoa(issueN)}, \"/\")\n\turl += \"?\"\n\tfor k, v := range params {\n\t\turl += k + \"=\" + v\n\t}\n\n\tresp, err := get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result Issue\n\n\tif err := json.NewDecoder(resp.Body).Decode(&result); err != nil {\n\t\tresp.Body.Close()\n\t\treturn nil, err\n\t}\n\tresp.Body.Close()\n\treturn &result, nil\n}", "func issues(ctx context.Context, c *client.Client, org string, project string, since time.Time, until time.Time, users []string, state string) ([]*github.Issue, error) {\n\tresult := []*github.Issue{}\n\topts := &github.IssueListByRepoOptions{\n\t\tState: state,\n\t\tSort: \"updated\",\n\t\tDirection: \"desc\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: 100,\n\t\t},\n\t}\n\n\tmatchUser := map[string]bool{}\n\tfor _, u := range users {\n\t\tmatchUser[strings.ToLower(u)] = true\n\t}\n\n\tlogrus.Infof(\"Gathering issues for %s/%s, users=%q: %+v\", org, project, users, opts)\n\tfor page := 1; page != 0; {\n\t\topts.ListOptions.Page = page\n\t\tissues, resp, err := c.GitHubClient.Issues.ListByRepo(ctx, org, project, opts)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\n\t\tlogrus.Infof(\"Processing page %d of %s/%s issue results ...\", page, org, project)\n\n\t\tpage = resp.NextPage\n\n\t\t// Repo has no issues!\n\t\tif len(issues) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tlogrus.Infof(\"Current issue updated at %s\", issues[0].GetUpdatedAt())\n\n\t\tfor _, i := range issues {\n\t\t\tif i.IsPullRequest() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i.GetClosedAt().After(until) {\n\t\t\t\tlogrus.Infof(\"issue #%d closed at %s\", i.GetNumber(), i.GetUpdatedAt())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif i.GetUpdatedAt().Before(since) {\n\t\t\t\tlogrus.Infof(\"Hit issue #%d updated at %s\", i.GetNumber(), i.GetUpdatedAt())\n\t\t\t\tpage = 0\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif !i.GetClosedAt().IsZero() && i.GetClosedAt().Before(since) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif state != \"\" && i.GetState() != state {\n\t\t\t\tlogrus.Infof(\"Skipping issue #%d (state=%q)\", i.GetNumber(), i.GetState())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tt := issueDate(i)\n\n\t\t\tlogrus.Infof(\"Fetching #%d (closed %s, updated %s): %q\", i.GetNumber(), i.GetClosedAt().Format(dateForm), i.GetUpdatedAt().Format(dateForm), i.GetTitle())\n\n\t\t\tfull, err := ghcache.IssuesGet(ctx, c.Cache, c.GitHubClient, t, org, project, i.GetNumber())\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tfull, err = ghcache.IssuesGet(ctx, c.Cache, c.GitHubClient, t, org, project, i.GetNumber())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"failed IssuesGet: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcreator := strings.ToLower(full.GetUser().GetLogin())\n\t\t\tcloser := strings.ToLower(full.GetClosedBy().GetLogin())\n\t\t\tif len(matchUser) > 0 && !matchUser[creator] && !matchUser[closer] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult = append(result, full)\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Returning %d issues\", len(result))\n\treturn result, nil\n}", "func (_Registry *RegistryTransactor) Issue(opts *bind.TransactOpts, _to common.Address, _validityData []byte, _topic *big.Int, _value *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Registry.contract.Transact(opts, \"issue\", _to, _validityData, _topic, _value, _data)\n}", "func GetIssuesInfo(conf *modules.Config, para modules.IssuePara, resChan chan interface{}) (interface{}, error) {\n\trequestPara := new(httppara.HTTPParameters)\n\tissues := make([]modules.Issue, 0)\n\tURL := initIssueQuery(conf, para)\n\ttoken := token.PersonalToken{Name: \"PRIVATE-TOKEN\", Value: conf.AccessInfo.PersonalToken}\n\tfmt.Println(\"URL\", URL)\n\trequestPara.InitPara(URL, \"GET\", token)\n\tissuesInfo, err := HTTPRequestWithHeader(requestPara, \"issue\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif para.FirstGet == true {\n\t\tresult := issuesInfo.(httppara.HTTPResponse)\n\t\terr = json.Unmarshal(result.HTTPResponse, &issues)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tissueList, err := processIssueInfo(issues, conf, para.TargetID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata := modules.IssueWithHeader{\n\t\t\tHeader: result.HTTPHeader,\n\t\t\tIssues: issueList,\n\t\t}\n\t\treturn data, nil\n\t}\n\terr = json.Unmarshal(issuesInfo.(httppara.HTTPResponse).HTTPResponse, &issues)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tissueList, err := processIssueInfo(issues, conf, para.TargetID)\n\tfmt.Println(issueList)\n\tresChan <- modules.IssueResult{Data: issueList, OK: err}\n\treturn nil, err\n}", "func GetIssueType(issue *github.Issue) string {\n\tfor _, l := range issue.Labels {\n\t\tswitch l.GetName() {\n\t\tcase enhancementTag:\n\t\t\treturn enhancementDisplayName\n\t\tcase bugTag:\n\t\t\treturn bugDisplayName\n\t\tdefault:\n\t\t\treturn closedDisplayName\n\t\t}\n\t}\n\treturn closedDisplayName\n}", "func Issues(ctx *context.Context) {\n\tif unit.TypeIssues.UnitGlobalDisabled() {\n\t\tlog.Debug(\"Issues overview page not available as it is globally disabled.\")\n\t\tctx.Status(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tctx.Data[\"Title\"] = ctx.Tr(\"issues\")\n\tctx.Data[\"PageIsIssues\"] = true\n\tctx.Data[\"SingleRepoAction\"] = \"issue\"\n\tbuildIssueOverview(ctx, unit.TypeIssues)\n}", "func TestIssueTracker(t *testing.T) {\n\tgomega.RegisterFailHandler(ginkgo.Fail)\n\tginkgo.RunSpecs(t, \"Tracker Suite\")\n}", "func (j *Jira) Issue(id string) (i Issue, err error) {\n\turi := j.ApiPath + \"/issue/\" + id\n\n\tcontents, err := j.getRequest(uri)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar issue Issue\n\terr = json.Unmarshal(contents, &issue)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn issue, nil\n}", "func getStory(w http.ResponseWriter, r *http.Request) {\n\t// read the id\n\tid := mux.Vars(r)[\"id\"]\n\t// format the url\n\tstoryURL := fmtURL(id)\n\t// Make request and get response body\n\tdata := fmtRes(storyURL)\n\tfmt.Println(\"data:\", data)\n\tw.Write([]byte(data))\n}", "func (w *ServerInterfaceWrapper) GetIssue(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"project_id\" -------------\n\tvar projectId string\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"project_id\", ctx.Param(\"project_id\"), &projectId)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter project_id: %s\", err))\n\t}\n\n\t// ------------- Path parameter \"id\" -------------\n\tvar id string\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"id\", ctx.Param(\"id\"), &id)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter id: %s\", err))\n\t}\n\n\t// HasSecurity is set\n\n\tctx.Set(\"OpenId.Scopes\", []string{\"exitus/issue.read\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetIssue(ctx, projectId, id)\n\treturn err\n}", "func MatchKnownIssue(r Kind, err error, goos string) *Kind {\n\t// The kind passed in has specified that it should not be rematched\n\tif r.NoMatch {\n\t\treturn nil\n\t}\n\n\tvar genericMatch *Kind\n\n\tfor _, ki := range knownIssues() {\n\t\tki := ki\n\t\tif ki.Regexp == nil {\n\t\t\tklog.Errorf(\"known issue has no regexp: %+v\", ki)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !ki.Regexp.MatchString(err.Error()) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Does this match require an OS matchup?\n\t\tif len(ki.GOOS) > 0 {\n\t\t\tfor _, o := range ki.GOOS {\n\t\t\t\tif o == goos {\n\t\t\t\t\treturn &ki.Kind\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif genericMatch == nil {\n\t\t\tgenericMatch = &ki.Kind\n\t\t}\n\t}\n\n\treturn genericMatch\n}", "func Setup(r *http.Request, params martini.Params) string {\n\tstates, err := getStatuses()\n\tif err != nil {\n\t\treturn \"{\\\"error\\\":\\\"\" + err.Error() + \"\\\"}\"\n\t}\n\n\tmsg := messages.Setup{\n\t\tOrg: r.URL.Query().Get(\"org\"),\n\t\tRepo: r.URL.Query().Get(\"repo\"),\n\t\tStates: states,\n\t\tConfig: config(),\n\t}\n\n\treturn Request(\"issue-tracker.setup\", msg)\n}", "func getIssues(user, repo, label string) []Datos {\n\t// Format the http link\n\turl := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/issues?labels=%s&page=1&per_page=100\", user, repo, label)\n\n\t// Get response\n\tbody := connectHTML(url)\n\n\t// Filter data\n\tdata := getData(body)\n\n\treturn data\n\n}", "func search() {\n\tr := *repo\n\ti := *issue\n\trepos := setRepositories()\n\n\tfor key, value := range repos {\n\t\tif repos[key].name == r {\n\t\t\tclient := &http.Client{}\n\t\t\trepoName := value\n\t\t\treq, err := http.NewRequest(\"GET\", \"https://api.github.com/search/issues\", nil)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"[ERROR] Some issue with request.\")\n\t\t\t}\n\t\t\tq := req.URL.Query()\n\t\t\tq.Add(\"q\", fmt.Sprintf(\"%s+repo:%s\", i, repoName.repo))\n\t\t\treq.URL.RawQuery = q.Encode()\n\t\t\tresp, _ := client.Do(req)\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tdefer resp.Body.Close()\n\t\t\tprintResults(body)\n\t\t}\n\t}\n}", "func (i *IssuesEvent) GetIssue() *Issue {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Issue\n}", "func (b *GithubBridge) GetIssueLocal(ctx context.Context, owner string, project string, number int) (*pbgh.Issue, error) {\n\turlv := \"https://api.github.com/repos/\" + owner + \"/\" + project + \"/issues/\" + strconv.Itoa(number)\n\tbody, _, err := b.visitURL(ctx, urlv)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data map[string]interface{}\n\terr = json.Unmarshal([]byte(body), &data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, ok := data[\"title\"]; !ok {\n\t\tb.RaiseIssue(\"Bad parse\", fmt.Sprintf(\"Bad parse %v\", string(body)))\n\t}\n\n\trbody := \"\"\n\tif _, ok := data[\"body\"]; ok {\n\t\trbody = fmt.Sprintf(\"%v\", data[\"body\"])\n\t}\n\n\tissue := &pbgh.Issue{Number: int32(number), Service: project, Title: data[\"title\"].(string), Body: rbody}\n\tif data[\"state\"].(string) == \"open\" {\n\t\tissue.State = pbgh.Issue_OPEN\n\t} else {\n\t\tissue.State = pbgh.Issue_CLOSED\n\t}\n\n\treturn issue, nil\n}", "func (p *Pattern) FindTrack(name string) *Track {\n\tfor _, t := range p.Tracks {\n\t\tif t.Name == name {\n\t\t\treturn t\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Source) GetIssue() *Issue {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn s.Issue\n}", "func (m *MaintainerManager) GetIssue(number string, comments bool) (*gh.Issue, []gh.Comment, error) {\n\tvar c []gh.Comment\n\tnum, err := strconv.Atoi(number)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tissue, err := m.client.Issue(m.repo, num, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif comments {\n\t\tc, err = m.GetComments(number)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn issue, c, nil\n}", "func (g *GH) GetIssue(repo string, number int) (*github.Issue, *github.Response) {\n\tctx := context.Background()\n\ti, rsp, err := g.c.Issues.Get(ctx, g.org, repo, number)\n\tif err != nil {\n\t\tlog.Println(\"Error Retrieving Issue\")\n\t\treturn nil, rsp\n\t}\n\treturn i, rsp\n}", "func issueSearchKey(org string, project string, state string, days int) string {\n\tif days > 0 {\n\t\treturn fmt.Sprintf(\"%s-%s-%s-issues-within-%dd\", org, project, state, days)\n\t}\n\treturn fmt.Sprintf(\"%s-%s-%s-issues\", org, project, state)\n}", "func (rg *reportGenerator) createIssue() *github.Issue {\n\ttitle := rg.getIssueTitle()\n\tbody := os.Expand(issueBodyTemplate, rg.templateHelper)\n\n\tissue, response, err := rg.client.Issues.Create(\n\t\trg.ctx,\n\t\trg.envVariables[projectUsernameKey],\n\t\trg.envVariables[projectRepoNameKey],\n\t\t&github.IssueRequest{\n\t\t\tTitle: &title,\n\t\t\tBody: &body,\n\t\t\t// TODO: Set Assignees and labels\n\t\t})\n\tif err != nil {\n\t\trg.logger.Fatal(\"Failed to create GitHub Issue\", zap.Error(err))\n\t}\n\n\tif response.StatusCode != http.StatusCreated {\n\t\trg.handleBadResponses(response)\n\t}\n\n\treturn issue\n}", "func (it IssueTracker) GetBugs(project string, owner string) (*IssueList, error) {\n\terrFmt := \"error retrieving issues: %s\"\n\tif !it.IsAuthenticated() {\n\t\treturn nil, fmt.Errorf(errFmt, \"user is not authenticated!\")\n\t}\n\tparams := map[string]string{\n\t\t\"owner\": url.QueryEscape(owner),\n\t\t\"can\": \"open\",\n\t\t\"maxResults\": \"9999\",\n\t}\n\trequestURL := ISSUE_API_URL + project + \"/issues?\"\n\tfirst := true\n\tfor k, v := range params {\n\t\tif first {\n\t\t\tfirst = false\n\t\t} else {\n\t\t\trequestURL += \"&\"\n\t\t}\n\t\trequestURL += k + \"=\" + v\n\t}\n\tresp, err := it.OAuthTransport.Client().Get(requestURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(errFmt, fmt.Sprintf(\n\t\t\t\"issue tracker returned code %d:%v\", resp.StatusCode, string(body)))\n\t}\n\n\tvar bugList IssueList\n\tif err := json.Unmarshal(body, &bugList); err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, err)\n\t}\n\treturn &bugList, nil\n}", "func SortedTimeTracking(delay string, jobInputs chan<- *fetcher.TicketFetcherJob) (UserWorkLogs, error) {\n\t// JIRA credentials\n\tuser := viper.GetString(\"user\")\n\tpassword := viper.GetString(\"password\")\n\tendpoint := viper.GetString(\"endpoint\")\n\n\t// Seach for issue in JIRA using jql query language\n\tjql := fmt.Sprintf(\"%s ORDER BY updated DESC\", fetcher.UpdatedJql(delay))\n\tlog.WithFields(log.Fields{\n\t\t\"endpoint\": endpoint,\n\t}).Infof(\"Fetching JIRA tickets using JQL: '%s'\", jql)\n\n\t// Get all tickets for analysis\n\trawIssues, err := fetcher.Tickets(endpoint, user, password, jql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch details for all selected issues\n\tfetchedTickets := fetcher.FetchTicketsDetail(rawIssues, jobInputs)\n\n\t// Hold every time tracking line\n\tvar timetracking UserWorkLogs\n\n\tfor i := 1; i <= len(rawIssues); i++ {\n\t\tticket := <-fetchedTickets\n\n\t\t// By issue, export worked log by issue\n\t\tif ticket.Fields.Worklog != nil {\n\t\t\tfor _, worklog := range ticket.Fields.Worklog.Worklogs {\n\t\t\t\tt := time.Time(worklog.Started)\n\t\t\t\tdate := fmt.Sprintf(\"%d/%02d/%02d\", t.Day(), t.Month(), t.Year())\n\t\t\t\ttimetracking = append(timetracking, &UserWorkLog{Ticket: ticket.Fields.Summary, TicketURL: fetcher.TicketURL(endpoint, ticket.Key), User: snaker.SnakeToCamel(strings.Split(worklog.Author.Name, \".\")[0]), Date: date, Timestamp: t.Unix(), Duration: (time.Duration(worklog.TimeSpentSeconds) * time.Second).Hours(), WorklogURL: fetcher.WorklogURL(endpoint, ticket.Key, worklog.ID), WorklogID: worklog.ID})\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Issue %s assigned to %s doesn't have any work logged !\", ticket.Key, ticket.Fields.Assignee)\n\t\t}\n\t}\n\n\t// Let's return everything we collected in chronological order\n\tlog.Infof(\"There are %d timetracking line generated.\", len(timetracking))\n\tsort.Sort(sort.Reverse(timetracking))\n\n\treturn timetracking, nil\n}", "func ReportFinding(ir *IssueReporter, fset *token.FileSet, rootCommitID string, repo Repository) Reporter {\n\treturn func(contents map[string][]byte) func(analysis.Diagnostic) {\n\t\treturn func(d analysis.Diagnostic) {\n\t\t\tif len(d.Related) < 1 {\n\t\t\t\tlog.Printf(\"could not read diagnostic with empty 'Related' field: %v\", d.Related)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfilename := d.Related[0].Message\n\t\t\tvar extraInfo string\n\t\t\tif len(d.Related) >= 2 {\n\t\t\t\textraInfo = d.Related[1].Message\n\t\t\t}\n\t\t\tstart := fset.Position(d.Pos)\n\t\t\tend := fset.Position(d.End)\n\t\t\t// split off into a separate thread so any API call to create the issue doesn't block the remaining analysis.\n\t\t\tir.ReportVetResult(VetResult{\n\t\t\t\tRepository: repo,\n\t\t\t\tFilePath: fset.File(d.Pos).Name(),\n\t\t\t\tRootCommitID: rootCommitID,\n\t\t\t\tQuote: QuoteFinding(contents[filename], start.Line, end.Line),\n\t\t\t\tStart: start,\n\t\t\t\tEnd: end,\n\t\t\t\tMessage: d.Message,\n\t\t\t\tExtraInfo: extraInfo,\n\t\t\t})\n\t\t}\n\t}\n}", "func (s *TrackerService) Get(trackerName string, id int) (*Ticket, *Response, error) {\n\trel := path.Join(s.client.Project, trackerName, strconv.Itoa(id))\n\n\treq, err := s.client.NewRequest(\"GET\", rel, nil)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tticketResponse := new(TicketResponse)\n\tresp, err := s.client.Do(req, ticketResponse)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &ticketResponse.Ticket, resp, err\n}", "func constructKttIssueFromJiraIssue(jiraIssue JiraIssue) KttIssue {\n\n\tvar kttIssue KttIssue\n\n\t//Filled from Jira issue\n\tkttIssue.Description = jiraIssue.ParentDescription\n\tkttIssue.Name = jiraIssue.ParentKey + \": \" + jiraIssue.ParentSummary + \"_\" + jiraIssue.Summary\n\tkttIssue.Field1130 = jiraIssue.ParentKey\n\tkttIssue.Field1131 = convertEstimationToHours(jiraIssue.Estimation)\n\tkttIssue.Field1211 = jiraIssue.Key\n\n\t//Filled from configuration file\n\tkttIssue.ExecutorIds = globalConfig.KTT.TicketDefaults.ExecutorIds\n\tkttIssue.PriorityId = globalConfig.KTT.TicketDefaults.PriorityId\n\tkttIssue.ServiceId = 150 //TODO: Create mapping\n\tkttIssue.StatusId = globalConfig.KTT.TicketDefaults.StatusId\n\tkttIssue.TypeId = globalConfig.KTT.TicketDefaults.TypeId\n\tkttIssue.WorkflowId = globalConfig.KTT.TicketDefaults.WorkflowId\n\n\t//Calculated fields\n\tmonday, friday := GetTicketWorkdays(globalConfig.KTT.Parameters.AddWeeks)\n\n\tkttIssue.Deadline = friday.Format(time.RFC3339) //TODO: Разобраться, почему не присваивается это поле\n\tkttIssue.Field1133 = monday.Format(time.RFC3339)\n\n\t/*\n\tif(applicationMode == \"test\") {\n\t\tfmt.Printf(\"\\n\\n%v\\n\\n\", kttIssue)\n\t}\n\t*/\n\treturn kttIssue\n}", "func (m *Model) lookUp(expr ast.Expr, bound_type int, spawning_for_loop bool) (*promela_ast.Ident, error) {\n\n\tvar ident *promela_ast.Ident\n\tvar err error\n\tvar bound string = \"for bound\"\n\tvar mandatory string = \"false\"\n\tswitch bound_type {\n\tcase CHAN_BOUND:\n\t\tbound = \"chan bound\"\n\t\tmandatory = \"true\"\n\tcase LOWER_FOR_BOUND:\n\t\tbound = \"for lower bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning for lower bound\"\n\t\t}\n\tcase RANGE_BOUND:\n\t\tbound = \"range bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning range bound\"\n\t\t}\n\tcase UPPER_FOR_BOUND:\n\t\tbound = \"for upper bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning for upper bound\"\n\t\t}\n\tcase ADD_BOUND:\n\t\tmandatory = \"true\"\n\t\tbound = \"add bound\"\n\t}\n\tident, _, err = m.TranslateArg(expr)\n\n\t// if _, err := strconv.Atoi(var_name); err != nil {\n\t// \tvar_name = VAR_PREFIX + var_name\n\t// }\n\tif err != nil {\n\t\tident = &promela_ast.Ident{Name: \"not_found_\" + strconv.Itoa(m.Fileset.Position(expr.Pos()).Line) + strconv.Itoa(m.Fileset.Position(expr.Pos()).Column)}\n\n\t\tm.PrintFeature(Feature{\n\t\t\tProj_name: m.Project_name,\n\t\t\tModel: m.Name,\n\t\t\tFun: m.Fun.Name.String(),\n\t\t\tName: \"Candidate Param\",\n\t\t\tInfo: ident.Name,\n\t\t\tMandatory: mandatory,\n\t\t\tLine: 0,\n\t\t\tCommit: m.Commit,\n\t\t\tFilename: m.Fileset.Position(m.Fun.Pos()).Filename,\n\t\t})\n\n\t\tif spawning_for_loop {\n\t\t\tm.Defines = append(m.Defines, promela_ast.DefineStmt{Name: ident, Rhs: &promela_ast.Ident{Name: DEFAULT_BOUND}})\n\t\t} else {\n\t\t\tm.Defines = append(m.Defines, promela_ast.DefineStmt{Name: ident, Rhs: &promela_ast.Ident{Name: OPTIONAL_BOUND}})\n\t\t}\n\t}\n\tm.PrintFeature(Feature{\n\t\tProj_name: m.Project_name,\n\t\tModel: m.Name,\n\t\tFun: m.Fun.Name.String(),\n\t\tName: \"Comm Param\",\n\t\tMandatory: mandatory,\n\t\tInfo: ident.Name,\n\t\tLine: m.Fileset.Position(expr.Pos()).Line,\n\t\tCommit: m.Commit,\n\t\tFilename: m.Fileset.Position(expr.Pos()).Filename,\n\t})\n\n\tm.PrintCommParFeature(expr, bound, mandatory)\n\n\treturn &promela_ast.Ident{Name: ident.Print(0)}, nil\n}", "func (i *IssueEvent) GetIssue() *Issue {\n\tif i == nil {\n\t\treturn nil\n\t}\n\treturn i.Issue\n}", "func (bt *Hackerbeat) fetchStory(stories chan<- story, storyID uint) {\n\tstory := story{\n\t\tID: storyID,\n\t}\n\n\t// Generate getStoryURL from getItemURL and storyID\n\tgetStoryURL := strings.Replace(getItemURL, storyIDToken, strconv.FormatUint(uint64(storyID), 10), -1)\n\n\t// Get story from HackerNews API\n\tresp, err := bt.httpClient.Get(getStoryURL)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to get story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Read all bytes from response body\n\tstoryInfos, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to parse story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Unmarshal response body into our story data structure\n\terr = json.Unmarshal(storyInfos, &story)\n\tif err != nil {\n\t\tbt.logger.Errorw(\n\t\t\t\"Failed to unmarshal story\",\n\t\t\t\"error\", err,\n\t\t)\n\t\treturn\n\t}\n\n\t// Send story back to the main thread\n\tstories <- story\n}", "func generateURLIssue(h string) string {\n\tconst (\n\t\ttitle = \"Move your ass\"\n\t\turlFormat = \"https://github.com/sjeandeaux/nexus-cli/issues/new?title=%s&body=%s\"\n\t\tbodyFormat = \"Could you add the hash %q lazy man?\\n%s\"\n\t)\n\tescapedTitle := url.QueryEscape(title)\n\tbody := fmt.Sprintf(bodyFormat, h, information.Print())\n\tescapedBody := url.QueryEscape(body)\n\turlIssue := fmt.Sprintf(urlFormat, escapedTitle, escapedBody)\n\treturn urlIssue\n}", "func lookupTip(r *git.Repository, refname string) *git.Commit {\n\tref, err := r.References.Lookup(refname)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcommit, err := lookupCommit(r, ref.Target())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn commit\n}", "func TestIssue(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tcheckAuth(t, r)\n\t\tval := `{\"expand\":\"renderedFields,names,schema,transitions,operations,editmeta,changelog\",\"id\":\"1234\",\"self\":\"https://test.atlassian.net/rest/api/2/issue/1234\",\"key\":\"ABC-01\",\"fields\":{\"summary\":\"This is a test\"}}`\n\t\tfmt.Fprintln(w, val)\n\t}))\n\tdefer ts.Close()\n\n\tc := NewJiraClient(ts.URL, \"foo\", \"bar\", 100)\n\ti, err := c.Issue(\"abc\", nil)\n\tif err != nil {\n\t\tt.Error(\"Error loading issue:\", err)\n\t}\n\n\tif i == nil {\n\t\tt.Error(\"issue is nil\")\n\t}\n\n\tif i.ID != \"1234\" {\n\t\tt.Error(\"Error expected issue ID to be 1234 got:\", i.ID)\n\t}\n\n\tif i.Key != \"ABC-01\" {\n\t\tt.Error(\"Error expected issue Key to be ABC-01 got:\", i.Key)\n\t}\n}", "func (a *Action) GetIssueTitle() string {\n\tindex, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)\n\tissue, err := issues_model.GetIssueByIndex(db.DefaultContext, a.RepoID, index)\n\tif err != nil {\n\t\tlog.Error(\"GetIssueByIndex: %v\", err)\n\t\treturn \"500 when get issue\"\n\t}\n\treturn issue.Title\n}", "func NewIssueTrackerFrom(issueTrackerType config.IssueTracker, authCfg *config.Auth, origin string) (issuetracker.IssueTracker, error) {\n\tswitch issueTrackerType {\n\tcase config.IssueTrackerGithub:\n\t\treturn github.New(origin, authCfg)\n\tcase config.IssueTrackerJira:\n\t\treturn jira.New(origin, authCfg)\n\tcase config.IssueTrackerGitlab:\n\t\treturn gitlab.New(origin, authCfg)\n\tcase config.IssueTrackerRedmine:\n\t\treturn redmine.New(origin, authCfg)\n\tcase config.IssueTrackerPivotal:\n\t\treturn pivotaltracker.New(origin, authCfg)\n\tcase config.IssueTrackerYoutrack:\n\t\treturn youtrack.New(origin, authCfg)\n\tcase config.IssueTrackerAzure:\n\t\treturn azureboards.NewIssueTrackerAzure(origin, authCfg)\n\t}\n\n\treturn nil, errors.New(\"unknown issue tracker \" + string(issueTrackerType))\n}", "func NewLineByIssue(repoName string, issue github.Issue) Line {\n\treturn Line{\n\t\ttitle: *issue.Title,\n\t\trepoName: repoName,\n\t\turl: *issue.HTMLURL,\n\t\tuser: *issue.User.Login,\n\t\tstatus: getIssueStatus(issue),\n\t}\n}", "func (a *RepoAPI) createIssue(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\tname := m.Get(\"name\").Str()\n\tcallParams := m.Get(\"params\").MSI()\n\treturn rpc.Success(util.Map{\n\t\t\"data\": a.mods.Repo.CreateIssue(name, callParams),\n\t})\n}", "func (s StoryRepository) Find(id int) (story chronicle.Story, err error) {\n\tdefer func() {\n\t\tif err != nil && err != sql.ErrNoRows {\n\t\t\terr = errors.Wrap(err, function.GetFunctionName(s.Find))\n\t\t}\n\t}()\n\n\tstory = chronicle.Story{}\n\tquery := `SELECT\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\tslug, \n\t\t\t\t\t\t\texcerpt, \n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\treporter,\n\t\t\t\t\t\t\teditor,\n\t\t\t\t\t\t\tauthor,\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tmedia, \n\t\t\t\t\t\t\tlikes,\n\t\t\t\t\t\t\tshares,\n\t\t\t\t\t\t\tviews,\n\t\t\t\t\t\t\tcreatedAt, \n\t\t\t\t\t\t\tupdatedAt\n\t\t\t\t\t\tFROM stories \n\t\t\t\t\t\tWHERE id=$1`\n\n\terr = s.db.Get(&story, query, id)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\t// fill Topics\n\n\tstory.Topics, err = s.getTopicsForStory(story.ID)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\treturn story, nil\n}", "func NewJiraIssue(from jira.Issue) (JiraIssue, error) {\n\t// Parse assignee\n\tassnKey := \"\"\n\tvar assn *JiraUser = nil\n\n\tif from.Fields.Assignee != nil {\n\t\tassnKey = from.Fields.Assignee.Key\n\n\t\tuser := NewJiraUser(*from.Fields.Assignee)\n\t\tassn = &user\n\t}\n\n\t// Parse resolution\n\tres := \"\"\n\tif from.Fields.Resolution != nil {\n\t\tres = from.Fields.Resolution.Name\n\t}\n\n\t// Parse progress\n\tvar prog float32\n\n\tif from.Fields.Progress.Total != 0 {\n\t\tprog = float32(from.Fields.Progress.Progress) / float32(from.Fields.Progress.Total)\n\t}\n\n\t// Parse links\n\tlinks := []JiraIssueLink{}\n\tfor _, jLink := range from.Fields.IssueLinks {\n\t\tlinks = append(links, NewJiraIssueLink(*jLink))\n\t}\n\n\t// Parse comments\n\tcomments := []JiraIssueComment{}\n\n\tif from.Fields.Comments != nil {\n\t\tfor _, jCom := range from.Fields.Comments.Comments {\n\t\t\tcomments = append(comments, NewJiraIssueComment(*jCom))\n\t\t}\n\t}\n\n\t// Parse updated\n\t/*var updated *time.Time = nil\n\n\tt, err := time.Parse(JiraDateFormat, from.Fields.Updated)\n\tif err != nil {\n\t\treturn JiraIssue{}, fmt.Errorf(\"error parsing issue updated \"+\n\t\t\t\"field into date: %s\", err.Error())\n\t}\n\tupdated = &t*/\n\n\treturn JiraIssue{\n\t\tID: from.ID,\n\t\tType: from.Fields.Type.Name,\n\t\tAssigneeKey: assnKey,\n\t\tAssignee: assn,\n\t\tProjectID: from.Fields.Project.ID,\n\t\tResolution: res,\n\t\tPriority: from.Fields.Priority.Name,\n\t\tStatus: from.Fields.Status.Name,\n\t\tTitle: from.Fields.Summary,\n\t\tDescription: from.Fields.Description,\n\t\tProgress: prog,\n\t\tLinks: links,\n\t\tComments: comments,\n\t\tLabels: from.Fields.Labels,\n\t\t//Updated: updated,\n\t}, nil\n}", "func (ts *TechStoryService) findById (w http.ResponseWriter, r *http.Request) {\n\tvar techStory model.TechStory\n\ttechStory.Key = mux.Vars(r)[\"id\"]\n\tWithTechStoryDao(func(dao techStoryDao) {\n\t\terr := dao.FindById(&techStory)\n\t\tmodel.CheckErr(err)\n\t\tmodel.WriteResponse(true, nil, techStory, w)\n\t})\n}", "func (h *HubBub) LookupTactic(id string) (Tactic, error) {\n\tt, ok := h.tactics[id]\n\tif !ok {\n\t\treturn t, fmt.Errorf(\"tactic %q is undefined - typo?\", id)\n\t}\n\tt.ID = id\n\tif len(h.reposOverride) > 0 {\n\t\tt.Repos = h.reposOverride\n\t}\n\n\tif len(t.Repos) == 0 {\n\t\tt.Repos = h.settings.Repos\n\t}\n\treturn t, nil\n}", "func lookupTip(r *git.Repository, refname string) *git.Commit {\n\tref, err := r.LookupReference(refname)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcommit, err := lookupCommit(r, ref.Target())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn commit\n}", "func (_Registry *RegistryTransactorSession) Issue(_to common.Address, _validityData []byte, _topic *big.Int, _value *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.Issue(&_Registry.TransactOpts, _to, _validityData, _topic, _value, _data)\n}", "func IssueCreate(project string, opts *gitlab.CreateIssueOptions) (string, error) {\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tspew.Dump(opts)\n\t}\n\n\tp, err := FindProject(project)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmr, _, err := lab.Issues.CreateIssue(p.ID, opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn mr.WebURL, nil\n}", "func PopulateIssueInteractive(ctx context.Context, client *github.Client, settings *Settings, inputTitle, inputDescription string, labelSlice []string) (ir *github.IssueRequest, err error) {\n\tlabels, err := Labels(ctx, client, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabelSet := make(map[string]bool)\n\tfor _, l := range labelSlice {\n\t\tlabelSet[l] = true\n\t}\n\n\ttempFile, err := ioutil.TempFile(\"\", \"git-open-pull\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// fmt.Printf(\"drafting %s\\n\", tempFile.Name())\n\tdefer os.Remove(tempFile.Name())\n\n\tif inputTitle != \"\" {\n\t\tfmt.Fprintf(tempFile, \"%s\\n\", inputTitle)\n\t}\n\tif inputDescription != \"\" {\n\t\tfmt.Fprintf(tempFile, \"%s\\n\", inputDescription)\n\t}\n\n\t// seed template with commit history\n\tmergeBase, err := MergeBase(ctx, settings)\n\tif err != nil {\n\t\tlog.Printf(\"error getting merge base %s\", err)\n\t} else {\n\t\t// fmt.Printf(\"merge base is %s\\n\", mergeBase)\n\t\tif mergeBase != \"\" {\n\t\t\tcommits, err := Commits(ctx, mergeBase)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error getting commits %s\", err)\n\t\t\t}\n\t\t\tfor i, c := range commits {\n\t\t\t\t// log.Printf(\"[%d] commit %s\", i, c)\n\t\t\t\tt, b, err := CommitDetails(ctx, c)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif t == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tswitch i {\n\t\t\t\tcase 0:\n\t\t\t\t\tfmt.Fprintf(tempFile, \"%s\\n\", t)\n\t\t\t\tcase 1:\n\t\t\t\t\tfmt.Fprintf(tempFile, \"\\n * %s\\n\", t)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Fprintf(tempFile, \" * %s\\n\", t)\n\t\t\t\t}\n\t\t\t\tif b != \"\" {\n\t\t\t\t\tfmt.Fprintf(tempFile, \"%s\\n\", b)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tio.WriteString(tempFile, \"\\n# Uncomment to assign labels\\n\")\n\tfor _, l := range labels {\n\t\t// if labels are passed as command line input, uncomment them\n\t\tif labelSet[l] {\n\t\t\tfmt.Fprintf(tempFile, \"Label: %s\\n\", l)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(tempFile, \"# Label: %s\\n\", l)\n\t}\n\n\tio.WriteString(tempFile, `\n# Please enter a title and description for your new issue. The first\n# line will be used as the issue title, and any subsequent lines will\n# be used as the issue description.\n#\n# Lines starting with '#' will be ignored.`)\n\n\ttempFile.Sync()\n\ttempFile.Close()\n\n\t// pre process template\n\tif settings.PreProcess != \"\" {\n\t\tcmd := exec.CommandContext(ctx, settings.PreProcess, tempFile.Name())\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error running pre process template: %s:\\n %s\", settings.PreProcess, out)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcmd := exec.CommandContext(ctx, settings.Editor, tempFile.Name())\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\tif err != nil {\n\t\ttempFile.Close()\n\t\t// os.Remove(tempFile.Name())\n\t\treturn nil, err\n\t}\n\tif cmd.ProcessState != nil && !cmd.ProcessState.Success() {\n\t\treturn nil, fmt.Errorf(\"non-zero exit code from editor\")\n\t}\n\n\t// post process template\n\tif settings.PostProcess != \"\" {\n\t\tcmd = exec.CommandContext(ctx, settings.PostProcess, tempFile.Name())\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error running post process template: %s:\\n %s\", settings.PostProcess, out)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// re-open the temp file\n\ttempFile, err = os.Open(tempFile.Name())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar title string\n\tvar descriptions, selectedLabels []string\n\tscanner := bufio.NewScanner(tempFile)\n\tfor scanner.Scan() {\n\t\t// log.Printf(\"line %#v\", scanner.Text())\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tswitch {\n\t\tcase strings.HasPrefix(line, \"Label:\"):\n\t\t\tlabel := strings.TrimSpace(line[len(\"Label:\"):])\n\t\t\tif label != \"\" {\n\t\t\t\tselectedLabels = append(selectedLabels, label)\n\t\t\t}\n\t\tcase strings.HasPrefix(line, \"#\"):\n\t\tcase title == \"\" && line != \"\":\n\t\t\ttitle = line\n\t\tdefault:\n\t\t\tdescriptions = append(descriptions, strings.TrimRight(scanner.Text(), \" \\t\\r\\n\"))\n\t\t}\n\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdescription := strings.TrimSpace(strings.Join(descriptions, \"\\n\"))\n\n\tif title == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing title\")\n\t}\n\n\tissue := &github.IssueRequest{\n\t\tTitle: &title,\n\t\tAssignee: &settings.User,\n\t}\n\tif description != \"\" {\n\t\tissue.Body = &description\n\t}\n\tif len(selectedLabels) > 0 {\n\t\tissue.Labels = &selectedLabels\n\t}\n\n\treturn issue, nil\n}", "func GetAuditInfoForIssues(issues [][]byte, metadata []driver.IssueMetadata) ([][]*AuditableToken, error) {\n\tif len(issues) != len(metadata) {\n\t\treturn nil, errors.Errorf(\"number of issues does not match number of provided metadata\")\n\t}\n\toutputs := make([][]*AuditableToken, len(issues))\n\tfor k, md := range metadata {\n\t\tia := &issue2.IssueAction{}\n\t\terr := json.Unmarshal(issues[k], ia)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(ia.OutputTokens) != len(md.ReceiversAuditInfos) || len(ia.OutputTokens) != len(md.TokenInfo) {\n\t\t\treturn nil, errors.Errorf(\"number of output does not match number of provided metadata\")\n\t\t}\n\t\tfor i := 0; i < len(md.ReceiversAuditInfos); i++ {\n\t\t\tti := &token.Metadata{}\n\t\t\terr := json.Unmarshal(md.TokenInfo[i], ti)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif ia.OutputTokens[i] == nil {\n\t\t\t\treturn nil, errors.Errorf(\"output token at index [%d] is nil\", i)\n\t\t\t}\n\t\t\tif ia.OutputTokens[i].IsRedeem() {\n\t\t\t\treturn nil, errors.Errorf(\"issue cannot redeem tokens\")\n\t\t\t}\n\t\t\tao, err := NewAuditableToken(ia.OutputTokens[i], md.ReceiversAuditInfos[i], ti.Type, ti.Value, ti.BlindingFactor)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\toutputs[k] = append(outputs[k], ao)\n\t\t}\n\t}\n\treturn outputs, nil\n}", "func (wl *Workload) issueVisible(issue *Issue) bool {\n\t// Cycle breaker: We wrap the recursive term O in the function above with\n\t// a check of its parameter, returning zero if it's already been seen as\n\t// part of the recursion. There are meta and cyclicly referential tracking\n\t// issues that become each other's parent AND child.\n\tvisited := map[*Issue]struct{}{}\n\n\tf := func(rec issueRec, issue *Issue) bool {\n\t\tif _, ok := visited[issue]; ok {\n\t\t\treturn false\n\t\t}\n\t\tvisited[issue] = struct{}{}\n\n\t\treturn wl.issueVisibleRec(rec, issue)\n\t}\n\n\treturn f(f, issue)\n}", "func (m *Moderator) findAndHandleNewlyResolvedActions(timestamp time.Time) {\n\tactions, err := (*m.forum).GetActions(\"open\", timestamp)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, action := range actions {\n\t\tif action.Comments == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcomments, err := (*m.forum).GetNewComments(action, timestamp)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif resolution, ok := m.getResolution(comments); ok {\n\t\t\tif m.actionHandler != nil {\n\t\t\t\tif err := (*m.forum).CloseAction(action.ID); err == nil {\n\t\t\t\t\tif id, err := parseItemIdFromAction(action.Title, m.titleFormat); err == nil {\n\t\t\t\t\t\t(*m.actionHandler)(id, resolution)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *HubBub) LookupStrategy(id string) (Strategy, error) {\n\tfor _, s := range h.strategies {\n\t\tif s.ID == id {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\treturn Strategy{}, fmt.Errorf(\"%q not found\", id)\n}", "func (_Registry *RegistrySession) Issue(_to common.Address, _validityData []byte, _topic *big.Int, _value *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.Issue(&_Registry.TransactOpts, _to, _validityData, _topic, _value, _data)\n}", "func (c Client) GetIssue(ctx context.Context, ID it.IssueID) (it.Issue, error) {\n\tmi, err := c.getIssue(ctx, ID)\n\tif err != nil {\n\t\treturn it.Issue{}, err\n\t}\n\treturn it.Issue{\n\t\tID: it.IssueID(strconv.Itoa(*mi.ID)),\n\t\tSummary: *mi.Summary,\n\t\tAuthor: readMU(mi.Handler),\n\t\tCreatedAt: time.Time(*mi.DateSubmitted),\n\t\tState: it.State(mi.Status.Name),\n\t}, nil\n}", "func (comment *Comment) LoadRefIssue() (err error) {\n\tif comment.RefIssue != nil {\n\t\treturn nil\n\t}\n\tcomment.RefIssue, err = GetIssueByID(comment.RefIssueID)\n\tif err == nil {\n\t\terr = comment.RefIssue.loadRepo(x)\n\t}\n\treturn\n}", "func (j *DSGitHub) ProcessIssue(ctx *Ctx, inIssue map[string]interface{}) (issue map[string]interface{}, err error) {\n\tissue = inIssue\n\tissue[\"user_data\"] = map[string]interface{}{}\n\tissue[\"assignee_data\"] = map[string]interface{}{}\n\tissue[\"assignees_data\"] = []interface{}{}\n\tissue[\"comments_data\"] = []interface{}{}\n\tissue[\"reactions_data\"] = []interface{}{}\n\t// [\"user\", \"assignee\", \"assignees\", \"comments\", \"reactions\"]\n\tuserLogin, ok := Dig(issue, []string{\"user\", \"login\"}, false, true)\n\tif ok {\n\t\tissue[\"user_data\"], _, err = j.githubUser(ctx, userLogin.(string))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tassigneeLogin, ok := Dig(issue, []string{\"assignee\", \"login\"}, false, true)\n\tif ok {\n\t\tissue[\"assignee_data\"], _, err = j.githubUser(ctx, assigneeLogin.(string))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tiAssignees, ok := Dig(issue, []string{\"assignees\"}, false, true)\n\tif ok {\n\t\tassignees, _ := iAssignees.([]interface{})\n\t\tassigneesAry := []map[string]interface{}{}\n\t\tfor _, assignee := range assignees {\n\t\t\taLogin, ok := Dig(assignee, []string{\"login\"}, false, true)\n\t\t\tif ok {\n\t\t\t\tassigneeData, _, e := j.githubUser(ctx, aLogin.(string))\n\t\t\t\tif e != nil {\n\t\t\t\t\terr = e\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tassigneesAry = append(assigneesAry, assigneeData)\n\t\t\t}\n\t\t}\n\t\tissue[\"assignees_data\"] = assigneesAry\n\t}\n\tnumber, ok := Dig(issue, []string{\"number\"}, false, true)\n\tif ok {\n\t\tissue[\"comments_data\"], err = j.githubIssueComments(ctx, j.Org, j.Repo, int(number.(float64)))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tiCnt, ok := Dig(issue, []string{\"reactions\", \"total_count\"}, false, true)\n\t\tif ok {\n\t\t\tissue[\"reactions_data\"] = []interface{}{}\n\t\t\tcnt := int(iCnt.(float64))\n\t\t\tif cnt > 0 {\n\t\t\t\tissue[\"reactions_data\"], err = j.githubIssueReactions(ctx, j.Org, j.Repo, int(number.(float64)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m *DataHistoryManager) CheckCandleIssue(job *DataHistoryJob, multiplier int64, apiData, dbData float64, candleField string) (issue string, replace bool) {\n\tif m == nil {\n\t\treturn ErrNilSubsystem.Error(), false\n\t}\n\tif atomic.LoadInt32(&m.started) == 0 {\n\t\treturn ErrSubSystemNotStarted.Error(), false\n\t}\n\tif job == nil {\n\t\treturn errNilJob.Error(), false\n\t}\n\n\tfloatiplier := float64(multiplier)\n\tif floatiplier > 0 {\n\t\tapiData = math.Round(apiData*floatiplier) / floatiplier\n\t\tdbData = math.Round(dbData*floatiplier) / floatiplier\n\t}\n\tif apiData != dbData {\n\t\tvar diff float64\n\t\tif apiData > dbData {\n\t\t\tdiff = gctmath.CalculatePercentageGainOrLoss(apiData, dbData)\n\t\t} else {\n\t\t\tdiff = gctmath.CalculatePercentageGainOrLoss(dbData, apiData)\n\t\t}\n\t\tif diff > job.IssueTolerancePercentage {\n\t\t\tissue = fmt.Sprintf(\"%s api: %v db: %v diff: %v %%\", candleField, apiData, dbData, diff)\n\t\t}\n\t\tif job.ReplaceOnIssue &&\n\t\t\tjob.IssueTolerancePercentage != 0 &&\n\t\t\tdiff > job.IssueTolerancePercentage &&\n\t\t\tjob.SecondaryExchangeSource == \"\" {\n\t\t\treplace = true\n\t\t}\n\t}\n\treturn issue, replace\n}", "func (c *EventClient) FindProblemID(ctx context.Context, keptnEvent adapter.EventContentAdapter) (string, error) {\n\t// Step 1 - see if we have a Problem Url in the labels\n\tproblemID := TryGetProblemIDFromLabels(keptnEvent)\n\tif problemID != \"\" {\n\t\treturn problemID, nil\n\t}\n\n\t// Step 2 - lets see if we have a ProblemOpenEvent for this KeptnContext - if so - we try to extract the Problem ID\n\tevents, mErr := c.client.GetEvents(ctx,\n\t\t&v2.EventFilter{\n\t\t\tProject: keptnEvent.GetProject(),\n\t\t\tEventType: keptncommon.ProblemOpenEventType,\n\t\t\tKeptnContext: keptnEvent.GetShKeptnContext(),\n\t\t},\n\t\tv2.EventsGetEventsOptions{})\n\n\tif mErr != nil {\n\t\treturn \"\", fmt.Errorf(\"could not retrieve problem.open event for incoming event: %s\", mErr.GetMessage())\n\t}\n\n\tif len(events) == 0 {\n\t\treturn \"\", errors.New(\"could not retrieve problem.open event for incoming event: no events returned\")\n\t}\n\n\tproblemOpenEvent := &keptncommon.ProblemEventData{}\n\terr := keptnv2.Decode(events[0].Data, problemOpenEvent)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not decode problem.open event: %w\", err)\n\t}\n\n\tif problemOpenEvent.PID == \"\" {\n\t\treturn \"\", errors.New(\"no problem ID is included in problem.open event\")\n\t}\n\n\treturn problemOpenEvent.PID, nil\n}", "func (c *client) FindIssues(query, sort string, asc bool) ([]Issue, error) {\n\treturn c.FindIssuesWithOrg(\"\", query, sort, asc)\n}", "func IssueCreate(project string, opts *gitlab.CreateIssueOptions) (string, error) {\n\tp, err := FindProject(project)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmr, _, err := lab.Issues.CreateIssue(p.ID, opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn mr.WebURL, nil\n}", "func APIProjectFetchIssueHandler(er *Errorly) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := er.Store.Get(r, sessionName)\n\t\tdefer er.SaveSession(session, r, rw)\n\n\t\tvars := mux.Vars(r)\n\n\t\t_issueID, ok := vars[\"issue_id\"]\n\t\tif !ok {\n\t\t\tpassResponse(rw, \"Missing Issue ID\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\t// Authenticate the user\n\t\tauth, user := er.AuthenticateSession(session)\n\n\t\tproject, viewable, _, ok := verifyProjectVisibility(er, rw, vars, user, auth, true)\n\t\tif !ok {\n\t\t\t// If ok is False, an error has already been provided to the ResponseWriter so we should just return\n\t\t\treturn\n\t\t}\n\n\t\tif !viewable {\n\t\t\t// No permission to view project. We will treat like the project\n\t\t\t// does not exist.\n\t\t\tpassResponse(rw, \"Could not find this project\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\t// If an ID is specified we will instead return just the issue\n\t\tissueID, err := strconv.ParseInt(_issueID, 10, 64)\n\t\tif err != nil {\n\t\t\tpassResponse(rw, \"ID argument is not valid\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tissue := &structs.IssueEntry{}\n\n\t\terr = er.Postgres.Model(issue).\n\t\t\tWhere(\"issue_entry.project_id = ?\", project.ID).\n\t\t\tWhere(\"issue_entry.id = ?\", issueID).\n\t\t\tSelect()\n\t\tif err != nil {\n\t\t\tif errors.Is(err, pg.ErrNoRows) {\n\t\t\t\t// Invalid issue ID\n\t\t\t\tpassResponse(rw, \"Could not find this issue\", false, http.StatusBadRequest)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tpassResponse(rw, err.Error(), false, http.StatusInternalServerError)\n\n\t\t\treturn\n\t\t}\n\n\t\tpassResponse(rw, structs.APIProjectIssues{\n\t\t\tIssue: issue,\n\t\t}, true, http.StatusOK)\n\t}\n}", "func issueNeedsTriage(issue *Issue) bool {\n\t// Only sig-network has opted in.\n\tif !issue.hasLabel(\"sig/network\") {\n\t\treturn false\n\t}\n\n\t// Don't double-comment.\n\tif issue.hasLabel(\"triage/unresolved\") {\n\t\treturn false\n\t}\n\n\t// Don't relabel resolved issues.\n\tif issue.hasCommentWithCommand(\"/remove-triage\", \"unresolved\") {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (fxt *TestFixture) WorkItemByTitle(title string, spaceID ...uuid.UUID) *workitem.WorkItem {\n\tfor _, wi := range fxt.WorkItems {\n\t\tv, ok := wi.Fields[workitem.SystemTitle]\n\t\tif !ok {\n\t\t\tpanic(errs.Errorf(\"failed to find work item with title '%s'\", title))\n\t\t}\n\t\tif v == title && len(spaceID) > 0 && wi.SpaceID == spaceID[0] {\n\t\t\treturn wi\n\t\t} else if v == title && len(spaceID) == 0 {\n\t\t\treturn wi\n\t\t}\n\t}\n\treturn nil\n}", "func getIssuesCommentInfo(p *api.IssueCommentPayload) (title, link, by, operator string) {\n\ttitle = fmt.Sprintf(\"[Comment-%s #%d]: %s\\n%s\", p.Repository.FullName, p.Issue.Index, p.Action, p.Issue.Title)\n\tlink = p.Issue.HTMLURL\n\tif p.IsPull {\n\t\tby = fmt.Sprintf(\"PullRequest by %s\", p.Issue.Poster.UserName)\n\t} else {\n\t\tby = fmt.Sprintf(\"Issue by %s\", p.Issue.Poster.UserName)\n\t}\n\toperator = fmt.Sprintf(\"Operator: %s\", p.Sender.UserName)\n\treturn title, link, by, operator\n}", "func (s *server) packIssue(name upspin.PathName, issue *maintner.GitHubIssue) (*upspin.DirEntry, error) {\n\tkey := issueKey{\n\t\tname: name,\n\t\tupdated: issue.Updated,\n\t}\n\ts.mu.Lock()\n\tpacked, ok := s.issue[key]\n\ts.mu.Unlock()\n\tif ok {\n\t\treturn packed.de, nil\n\t}\n\tde, data, err := s.pack(name, key.Ref(), formatIssue(issue))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.mu.Lock()\n\ts.issue[key] = packedIssue{\n\t\tde: de,\n\t\tdata: data,\n\t}\n\ts.mu.Unlock()\n\treturn de, nil\n}", "func (r *Rietveld) ExtractIssue(issueURL string) (string, bool) {\n\tif !strings.HasPrefix(issueURL, r.url) {\n\t\treturn \"\", false\n\t}\n\n\tmatch := extractReg.FindStringSubmatch(strings.TrimRight(issueURL[len(r.url):], \"/\"))\n\tif len(match) != 2 {\n\t\treturn \"\", false\n\t}\n\treturn match[1], true\n}", "func (a *UtilsApiService) GetFeatureTrackUsingGet(ctx context.Context, featureTrackId string) (FeatureTrack, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue FeatureTrack\n\t)\n\n\t// create path and map variables\n\ta.client = NewAPIClient(&Configuration{\n\t\tBasePath: ctx.Value(\"BasePath\").(string),\n\t\tDefaultHeader: make(map[string]string),\n\t\tUserAgent: \"Swagger-Codegen/1.0.0/go\",\n\t})\n\tlocalVarPath := a.client.cfg.BasePath + \"/nucleus/v1/feature_track/{feature_track_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"feature_track_id\"+\"}\", fmt.Sprintf(\"%v\", featureTrackId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v FeatureTrack\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (s StoryRepository) FindBySlug(slug string) (story chronicle.Story, err error) {\n\tdefer func() {\n\t\tif err != nil && err != sql.ErrNoRows {\n\t\t\terr = errors.Wrap(err, function.GetFunctionName(s.FindBySlug))\n\t\t}\n\t}()\n\n\tstory = chronicle.Story{}\n\tquery := `SELECT\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\tslug, \n\t\t\t\t\t\t\texcerpt, \n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\treporter,\n\t\t\t\t\t\t\teditor,\n\t\t\t\t\t\t\tauthor,\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\tmedia, \n\t\t\t\t\t\t\tlikes,\n\t\t\t\t\t\t\tshares,\n\t\t\t\t\t\t\tviews,\n\t\t\t\t\t\t\tcreatedAt, \n\t\t\t\t\t\t\tupdatedAt\n\t\t\t\t\t\tFROM stories \n\t\t\t\t\t\tWHERE slug=$1`\n\n\terr = s.db.Get(&story, query, slug)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\t// fill s.getTopicsForStory(story.ID)\n\tstory.Topics, err = s.getTopicsForStory(story.ID)\n\tif err != nil {\n\t\treturn chronicle.Story{}, err\n\t}\n\n\treturn story, err\n}", "func ptrFromHandle_cel_Issues(h CGoHandle) *cel.Issues {\n\tp := gopyh.VarFromHandle((gopyh.CGoHandle)(h), \"cel.Issues\")\n\tif p == nil {\n\t\treturn nil\n\t}\n\treturn gopyh.Embed(p, reflect.TypeOf(cel.Issues{})).(*cel.Issues)\n}", "func (repo *SingleStoryRepository) FindByID(ID uuid.UUID) *model.SingleStory {\n\tstory := &model.SingleStory{}\n\tif repo.Database.First(&story, \"id = ? and is_deleted = ?\", ID, false).RowsAffected == 0 {\n\t\treturn nil\n\t}\n\n\tif time.Now().After(story.CreationDate.Add(24 * time.Hour)){\n\t\t// PASSED TIME SHOULD SET STORY AS EXPIRED\n\t\t//stories[i].IsExpired = true\n\t\trepo.Database.Model(&model.SingleStory{}).Where(\"id = ?\", story.ID).Update(\"is_expired\", true)\n\t\trepo.Database.Model(&model.Story{}).Where(\"id = ?\", story.ID).Update(\"is_expired\", true)\n\t}\n\n\treturn story\n}", "func APIProjectIssueHandler(er *Errorly) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := er.Store.Get(r, sessionName)\n\t\tdefer er.SaveSession(session, r, rw)\n\n\t\tvars := mux.Vars(r)\n\n\t\turlQuery := r.URL.Query()\n\n\t\t// Authenticate the user\n\t\tauth, user := er.AuthenticateSession(session)\n\n\t\tproject, viewable, _, ok := verifyProjectVisibility(er, rw, vars, user, auth, true)\n\t\tif !ok {\n\t\t\t// If ok is False, an error has already been provided to the ResponseWriter so we should just return\n\t\t\treturn\n\t\t}\n\n\t\tif !viewable {\n\t\t\t// No permission to view project. We will treat like the project\n\t\t\t// does not exist.\n\t\t\tpassResponse(rw, \"Could not find this project\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\t_issueID := urlQuery.Get(\"id\")\n\t\tif _issueID != \"\" {\n\t\t\t// If an ID is specified we will instead return just the issue\n\t\t\tissueID, err := strconv.ParseInt(_issueID, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tpassResponse(rw, \"ID argument is not valid\", false, http.StatusBadRequest)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tissue := &structs.IssueEntry{}\n\n\t\t\terr = er.Postgres.Model(issue).\n\t\t\t\tWhere(\"issue_entry.project_id = ?\", project.ID).\n\t\t\t\tWhere(\"issue_entry.id = ?\", issueID).\n\t\t\t\tSelect()\n\t\t\tif err != nil {\n\t\t\t\tif errors.Is(err, pg.ErrNoRows) {\n\t\t\t\t\t// Invalid issue ID\n\t\t\t\t\tpassResponse(rw, \"Could not find this issue\", false, http.StatusBadRequest)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tpassResponse(rw, err.Error(), false, http.StatusInternalServerError)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tpassResponse(rw, structs.APIProjectIssues{\n\t\t\t\tIssue: issue,\n\t\t\t}, true, http.StatusOK)\n\n\t\t\treturn\n\t\t}\n\n\t\t// Get query from search\n\t\tquery := urlQuery.Get(\"q\")\n\t\tif query == \"\" {\n\t\t\tquery = \"\"\n\t\t}\n\n\t\t// We should get a limit argument here but at the moment\n\t\t// we will hardcode 25 per page.\n\t\t_pageLimit := pageLimit\n\n\t\t// Retrieve page argument from URL\n\t\t_page := r.FormValue(\"page\")\n\t\tif _page == \"\" {\n\t\t\tpassResponse(rw, \"Page argument is missing\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\t// Check page is a valid number. We will use the first page\n\t\t// argument provided as multiple could be passed.\n\t\tpage, err := strconv.Atoi(_page)\n\t\tif err != nil {\n\t\t\tpassResponse(rw, \"Page argument is not valid\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tvar issues []structs.IssueEntry\n\n\t\tvar totalissues int\n\n\t\tif auth {\n\t\t\tissues, totalissues, err = fetchProjectIssues(er, project.ID, _pageLimit, page, query, user.ID)\n\t\t} else {\n\t\t\tissues, totalissues, err = fetchProjectIssues(er, project.ID, _pageLimit, page, query, 0)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tpassResponse(rw, err.Error(), false, http.StatusInternalServerError)\n\n\t\t\treturn\n\t\t}\n\n\t\tpassResponse(rw, structs.APIProjectIssues{\n\t\t\tPage: page,\n\t\t\tTotalIssues: totalissues,\n\t\t\tIssues: issues,\n\t\t}, true, http.StatusOK)\n\t}\n}", "func (fic *FakeClient) CreateIssue(ctx context.Context, in *issuetracker.CreateIssueRequest) (*issuetracker.Issue, error) {\n\treturn fic.FakeStore.StoreIssue(ctx, in.Issue), nil\n}", "func generateIssueIndexMapping() (mapping.IndexMapping, error) {\n\tmapping := bleve.NewIndexMapping()\n\tdocMapping := bleve.NewDocumentMapping()\n\n\tnumericFieldMapping := bleve.NewNumericFieldMapping()\n\tnumericFieldMapping.IncludeInAll = false\n\tdocMapping.AddFieldMappingsAt(\"RepoID\", numericFieldMapping)\n\n\ttextFieldMapping := bleve.NewTextFieldMapping()\n\ttextFieldMapping.Store = false\n\ttextFieldMapping.IncludeInAll = false\n\tdocMapping.AddFieldMappingsAt(\"Title\", textFieldMapping)\n\tdocMapping.AddFieldMappingsAt(\"Content\", textFieldMapping)\n\tdocMapping.AddFieldMappingsAt(\"Comments\", textFieldMapping)\n\n\tif err := addUnicodeNormalizeTokenFilter(mapping); err != nil {\n\t\treturn nil, err\n\t} else if err = mapping.AddCustomAnalyzer(issueIndexerAnalyzer, map[string]interface{}{\n\t\t\"type\": custom.Name,\n\t\t\"char_filters\": []string{},\n\t\t\"tokenizer\": unicode.Name,\n\t\t\"token_filters\": []string{unicodeNormalizeName, camelcase.Name, lowercase.Name},\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapping.DefaultAnalyzer = issueIndexerAnalyzer\n\tmapping.AddDocumentMapping(issueIndexerDocType, docMapping)\n\tmapping.AddDocumentMapping(\"_all\", bleve.NewDocumentDisabledMapping())\n\n\treturn mapping, nil\n}", "func (am *ArtifactMap) LookupAppTitle(sessionState *State, title string) (*ArtifactEntry, error) {\n\treturn am.lookup(sessionState, title, false)\n}", "func (s *sqlReadTx) CreateIssue(issue *model.Issue) (*model.Issue, error) {\n\tinsertQuery := s.statementBuilder.Insert(\n\t\t\"issues\",\n\t).Columns(\n\t\t\"entity_id\",\n\t\t\"id\",\n\t\t\"title\",\n\t\t\"body\",\n\t).Values(\n\t\tissue.EntityID,\n\t\tissue.ID,\n\t\tissue.Title,\n\t\tissue.Body,\n\t)\n\tresult, err := insertQuery.ExecContext(s.ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif affected, err := result.RowsAffected(); err != nil || affected == 0 {\n\t\treturn nil, fmt.Errorf(\"expected exactly one row to be affected, but had %d affected\", affected)\n\t}\n\tselectQuery := s.statementBuilder.Select(\n\t\t\"*\",\n\t).From(\n\t\t\"issues\",\n\t).Where(\n\t\tsquirrel.Eq{\n\t\t\t\"id\": issue.ID,\n\t\t},\n\t)\n\treturn s.querySingleIssue(selectQuery)\n}", "func (a *RepoAPI) track(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\ta.mods.Repo.Track(m.Get(\"names\").Str(), cast.ToUint64(m.Get(\"height\").Inter()))\n\treturn rpc.StatusOK()\n}", "func (wl *Workload) gatherCompletedIssues(labelAllowList []string) (completedWork []CompletedWork) {\n\tfor _, issue := range wl.Issues {\n\t\tif !wl.issueVisible(issue) {\n\t\t\tcontinue\n\t\t}\n\t\tif !issue.Closed() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// This would be displayed nested in a tracking issue. Because the\n\t\t// parent is also complete we don't want to show this duplicate data.\n\t\tvisibleAncestors := wl.issuesVisibleAncestors(issue)\n\t\tif len(visibleAncestors) == 1 && visibleAncestors[0].Closed() {\n\t\t\tcontinue\n\t\t}\n\n\t\tcompletedWork = append(completedWork, CompletedWork{\n\t\t\tTitle: issue.Title,\n\t\t\tMarkdown: issue.Markdown(labelAllowList),\n\t\t\tClosedAt: issue.ClosedAt,\n\t\t})\n\t}\n\n\treturn completedWork\n}", "func (h *Handlers) ActionLookup(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tshort := r.FormValue(\"short\")\n\tfullURL := h.storage.URLFromAlias(short)\n\tif fullURL == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprint(w, \"Not Found\")\n\t\treturn\n\t}\n\tfmt.Fprint(w, *fullURL)\n}", "func getOneStory(id int, c hn.Client, channel chan item, counter int) {\r\n\t// defer wg.Done()\r\n\tvar i item\r\n\t// fmt.Printf(\"getting item %d inside getOneStory number %d\\n\", id, counter)\r\n\thnItem, err := c.GetItem(id)\r\n\tif err != nil {\r\n\t\tfmt.Println(err)\r\n\t\treturn\r\n\t}\r\n\tfmt.Printf(\"parsing item %d\\n\", id)\r\n\ti = parseHNItem(hnItem)\r\n\tif !isStoryLink(i) {\r\n\t\tgoroutine--\r\n\t\t// fmt.Printf(\"returning because item %d is not a story.\\n\", id)\r\n\t\treturn\r\n\t}\r\n\t// fmt.Printf(\"Adding item %d to channel.\\n\", id)\r\n\tchannel <- i\r\n}", "func (c *Client) GetSiemIssues(opts map[string]interface{}) ([]*Click, []*Message, error) {\n\treturn []*Click{}, []*Message{}, nil\n}", "func issueDepExists(e Engine, issueID int64, depID int64) (bool, error) {\n\treturn e.Where(\"(issue_id = ? AND dependency_id = ?)\", issueID, depID).Exist(&IssueDependency{})\n}", "func (m *ServiceAnnouncement) GetIssues()([]ServiceHealthIssueable) {\n return m.issues\n}", "func (pfGrid *PathfindingGrid) getTileById(sid int) (int, Tile) {\n\tvar fTile Tile\n\n\tfor i := range pfGrid.tiles {\n\t\tfor k := range pfGrid.tiles[i] {\n\t\t\tif pfGrid.tiles[i][k].id == sid {\n\t\t\t\treturn 0, pfGrid.tiles[i][k]\n\t\t\t}\n\t\t}\n\t}\n\n\tdebugPause(fmt.Sprintf(\"Cannot find tile in lookup: %v\", sid))\n\n\treturn -1, fTile\n}" ]
[ "0.561695", "0.52363765", "0.52218294", "0.5195161", "0.5128233", "0.50444764", "0.5009002", "0.5007996", "0.49681804", "0.4954405", "0.49352568", "0.49218416", "0.48953724", "0.48927662", "0.48885015", "0.48748094", "0.48424858", "0.48406437", "0.4828924", "0.4826085", "0.48255077", "0.47900897", "0.4756349", "0.47305644", "0.47019148", "0.4658546", "0.4653459", "0.46393976", "0.46295956", "0.46291077", "0.46206635", "0.46122384", "0.46099073", "0.46026674", "0.4597729", "0.45839527", "0.45799616", "0.45778903", "0.45708054", "0.45638496", "0.45322224", "0.4528064", "0.45133194", "0.45085993", "0.45020744", "0.4501357", "0.4492697", "0.44841436", "0.44807824", "0.44757187", "0.4461033", "0.4447913", "0.444053", "0.44367996", "0.44354245", "0.44189486", "0.44125554", "0.4411822", "0.44095016", "0.44058198", "0.44002727", "0.4398371", "0.43942368", "0.43922612", "0.43882847", "0.43809703", "0.4374247", "0.43705863", "0.4370547", "0.43691424", "0.4367758", "0.43667468", "0.4365893", "0.43517092", "0.4345584", "0.43401125", "0.4336979", "0.4336689", "0.43313378", "0.43301868", "0.43280622", "0.43230408", "0.43191442", "0.43135926", "0.43037656", "0.43008506", "0.4296682", "0.4295606", "0.4285852", "0.42836803", "0.4279689", "0.4279266", "0.42758176", "0.42739668", "0.4272492", "0.4271645", "0.4259897", "0.42591354", "0.42528683", "0.42486805" ]
0.58144397
0
Run the given function with the given timeout. Return any error returned by the function, or ErrTimedOut if the timeout took place. The function is not interrupted if the timeout takes place.
func Run(fn func() error, timeout time.Duration) error { c := make(chan error, 1) go func() { c <- fn() close(c) }() t := time.NewTimer(timeout) defer t.Stop() select { case err := <-c: return err case <-t.C: return ErrTimedOut } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func runWithTimeout(f func() error, timeout time.Duration) error {\n\terrChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(errChan)\n\t\terrChan <- f()\n\t}()\n\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tcase <-time.After(timeout):\n\t\treturn errTimeout\n\t}\n}", "func testWithTimeout(timeout time.Duration, run func() error) error {\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tif err := run(); err != nil {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\treturn err\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(time.Millisecond * 5)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (c *ConcurrentLimit) RunWithTimeout(f func(), d time.Duration) error {\n\t// we push to start, and pop to finish\n\tselect {\n\tcase c.c <- true:\n\t\tf()\n\t\t<-c.c\n\t\treturn nil\n\tcase <-time.After(d):\n\t\treturn errors.New(\"timed out\")\n\t}\n}", "func (q *quitTest) runWithTimeout(ctx context.Context, fn func(ctx context.Context)) {\n\tif err := contextutil.RunWithTimeout(ctx, \"do\", time.Minute, func(ctx context.Context) error {\n\t\tfn(ctx)\n\t\treturn nil\n\t}); err != nil {\n\t\tq.Fatal(err)\n\t}\n}", "func Timeout(t cbtest.T, after time.Duration, fn func()) {\n\tt.Helper()\n\n\tdone := make(chan struct{})\n\n\tgo func() {\n\t\tfn()\n\t\tdone <- struct{}{}\n\t}()\n\n\tselect {\n\tcase <-time.After(after):\n\t\tt.Error(\"Operation timed out\")\n\tcase <-done:\n\t}\n}", "func TimeoutFunc(stop chan struct{}, callback func() error, timeout time.Duration) error {\n\t//optional with ttl\n\tttl := make(<-chan time.Time, 1) // placeholder for timer, 0 run forever\n\tif timeout > 0 {\n\t\tttl = time.After(timeout)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn nil\n\t\tcase <-ttl:\n\t\t\treturn nil\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tif err := callback(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (s stdlib) Timeout(time.Duration) {}", "func retryFunc(timeout time.Duration, f func() error) error {\n\tfinish := time.After(timeout)\n\tfor {\n\t\terr := f()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tlog.Printf(\"Retryable error: %v\", err)\n\n\t\tselect {\n\t\tcase <-finish:\n\t\t\treturn err\n\t\tcase <-time.After(3 * time.Second):\n\t\t}\n\t}\n}", "func InputFunctionTimeout(t *testing.T) {\n\terr := WaitFor(twoMillisecond, oneMillisecond, func() (bool, error) {\n\t\ttime.Sleep(fiveMillisecond)\n\t\treturn true, nil\n\t})\n\tassert.NotEqual(t, err, nil)\n\tassert.Equal(t, 0, strings.Compare(err.Error(), timeoutErrMsg))\n}", "func SetTimeout(fn func(args ...interface{}), duration int, args ...interface{}) *Timer {\n\ttimer := &Timer{\n\t\trunning: false,\n\t\tinterval: time.Duration(duration) * time.Millisecond,\n\t\tfn: fn,\n\t\targs: args,\n\t\tmaxIntervals: 0,\n\t}\n\n\ttimer.Start()\n\n\treturn timer\n}", "func TimedCall(description string, d time.Duration, fn func() error) error {\n\tdone := make(chan error)\n\ttimer := time.NewTimer(d)\n\tdefer timer.Stop()\n\tgo func() { done <- fn() }()\n\tselect {\n\tcase err := <-done:\n\t\treturn err\n\tcase <-timer.C:\n\t\treturn NewErrTimeOut(d, description)\n\t}\n}", "func (k *OcRunner) RunCommandWithTimeout(command string, timeout string) (stdOut string, stdErr string, exitCode int, err error) {\n\tstdOut, stdErr, exitCode, err = runCommandWithTimeout(command, k.CommandPath, timeout)\n\treturn\n}", "func (a *Agent) CatchTimeout(ctx context.Context, payload json.RawMessage) {\n\tdeadline, _ := ctx.Deadline()\n\tif deadline.IsZero() {\n\t\treturn\n\t}\n\ttimeoutDuration := deadline.Add(-a.TimeoutMargin)\n\tif config.DebugEnabled {\n\t\tlog.Println(\"Timeout margin:\", a.TimeoutMargin)\n\t}\n\tif time.Now().After(timeoutDuration) {\n\t\treturn\n\t}\n\ttimer := time.NewTimer(time.Until(timeoutDuration))\n\ttimeoutChannel := timer.C\n\tselect {\n\tcase <-timeoutChannel:\n\t\tlog.Println(\"Function is timed out\")\n\t\ta.ExecutePostHooks(ctx, payload, nil, timeoutError{})\n\t\treturn\n\tcase <-ctx.Done():\n\t\t// close timeoutChannel\n\t\ttimer.Stop()\n\t\treturn\n\t}\n}", "func (c *authorizer) runSafely(ctx context.Context, e *otto.Otto, script string, timeout time.Duration) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif e == errTimeout {\n\t\t\t\terr = errTimeout\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\te.Interrupt = make(chan func(), 1)\n\n\t// @check for a timeout and if not there, set the default\n\tif timeout <= 0 {\n\t\ttimeout = NewDefaultConfig().Timeout\n\t}\n\n\t// @step: setup a timer and done channel\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif err := ctx.Err(); err != nil {\n\t\t\t\te.Interrupt <- func() {\n\t\t\t\t\tpanic(errTimeout)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t_, err = e.Run(script)\n\n\treturn err\n}", "func (db *DB) ExecuteTimeout(collection string, fn func(*mgo.Collection) error, timeout time.Duration) error {\n\tif db == nil || db.session == nil {\n\t\treturn errors.New(\"DB error: db == nil || db.session == nil\")\n\t}\n\n\tdb.session.SetSocketTimeout(timeout)\n\n\treturn fn(db.database.C(collection))\n}", "func DoRetryWithTimeout(t func() (interface{}, bool, error), timeout, timeBeforeRetry time.Duration) (interface{}, error) {\n\t// Use context.Context as a standard go way of timeout and cancellation propagation amount goroutines.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tresultChan := make(chan interface{})\n\terrChan := make(chan error)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\n\t\t\t\tif ctx.Err() != nil {\n\t\t\t\t\terrChan <- ctx.Err()\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tout, retry, err := t()\n\t\t\t\tif err == nil {\n\t\t\t\t\tresultChan <- out\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif err != nil && !retry {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Printf(\"%v Next retry in: %v\", err, timeBeforeRetry)\n\t\t\t\ttime.Sleep(timeBeforeRetry)\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase result := <-resultChan:\n\t\treturn result, nil\n\tcase err := <-errChan:\n\t\tif err == context.DeadlineExceeded {\n\t\t\treturn nil, &ErrTimedOut{\n\t\t\t\tReason: err.Error(),\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n}", "func timeout(f func() (*Info, error), t time.Duration) (*Info, error) {\n\ttimeoutCh := make(chan bool, 1)\n\tinfoCh := make(chan *Info, 1)\n\terrCh := make(chan error, 1)\n\t// Run the timeout function in a separate thread.\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\ttimeoutCh <- true\n\t\tclose(timeoutCh)\n\t}()\n\t// Run the updater function in a separate thread.\n\tgo func() {\n\t\tinfo, err := f()\n\t\tif err == nil {\n\t\t\tinfoCh <- info\n\t\t} else {\n\t\t\terrCh <- err\n\t\t}\n\t\tclose(infoCh)\n\t\tclose(errCh)\n\t}()\n\t// Wait until one of the threads produces data in one of the channels being\n\t// monitored. If the timeout comes first, report the timeout. If the update\n\t// info comes first, return that. If there was some other error, return that.\n\tselect {\n\tcase <-timeoutCh:\n\t\treturn nil, errors.New(\"timeout\")\n\tcase info := <-infoCh:\n\t\treturn info, nil\n\tcase err := <-errCh:\n\t\treturn nil, err\n\t}\n}", "func goTimeout(t *testing.T, d time.Duration, f func()) {\n\tch := make(chan bool, 2)\n\ttimer := time.AfterFunc(d, func() {\n\t\tt.Errorf(\"Timeout expired after %v\", d)\n\t\tch <- true\n\t})\n\tdefer timer.Stop()\n\tgo func() {\n\t\tdefer func() { ch <- true }()\n\t\tf()\n\t}()\n\t<-ch\n}", "func WrapWithTimeout(cause error, parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(cause, DefaultTimeout, wparams.NewParamStorer(parameters...))\n}", "func (t *TimeoutFlags) NewRunFunc(\n\tfn func(\n\t\tcontext.Context,\n\t\t*cli.ExecEnv,\n\t\t*zap.Logger,\n\t\t*bytepool.SegList,\n\t) error,\n) func(*cli.ExecEnv) error {\n\treturn func(execEnv *cli.ExecEnv) error {\n\t\tctx := context.Background()\n\t\tvar cancel context.CancelFunc\n\t\tif !t.flags.profile && t.timeout != 0 {\n\t\t\tctx, cancel = context.WithTimeout(context.Background(), t.timeout)\n\t\t\tdefer cancel()\n\t\t}\n\t\treturn doRun(\n\t\t\texecEnv,\n\t\t\tt.flags,\n\t\t\tfunc(\n\t\t\t\texecEnv *cli.ExecEnv,\n\t\t\t\tlogger *zap.Logger,\n\t\t\t\tsegList *bytepool.SegList,\n\t\t\t) error {\n\t\t\t\treturn fn(ctx, execEnv, logger, segList)\n\t\t\t},\n\t\t)\n\t}\n}", "func RetryUntil(timeout time.Duration, fn func() error) (err error) {\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\tticker := time.NewTicker(10 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tif err = fn(); err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\treturn err\n\t\tcase <-ticker.C:\n\t\t}\n\t}\n}", "func executeQuestionTestWithTimeout(t *testing.T, test questionTest) {\n\ttimeout := time.After(2 * time.Second)\n\tdone := make(chan bool)\n\n\tgo func() {\n\t\texecuteQuestionTest(t, test)\n\t\tdone <- true\n\t}()\n\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatal(\"Test timed-out\")\n\tcase <-done:\n\t}\n}", "func (s *Skeleton) CallWithTimeout(dst ServiceID, encType EncType, timeout int, cmd CmdType, data ...interface{}) ([]interface{}, error) {\n\treturn s.s.callWithTimeout(dst, encType, timeout, cmd, data...)\n}", "func timeout(c chan int, t int) {\n\tgo func() {\n\t\ttime.Sleep(time.Second * time.Duration(t))\n\t\tc <- 1\n\t}()\n}", "func (fhp *FastHTTPProvider) DoTimeout(ctx context.Context, request *fasthttp.Request, duration *time.Duration) (*fasthttp.Response, error) {\n\treturn fhp.request(ctx, request, duration)\n}", "func (p *Parallel) RunWithTimeOut(d time.Duration) {\n\tsuccess := make(chan struct{}, 1)\n\tgo func() {\n\t\tp.Run()\n\t\tsuccess <- struct{}{}\n\t}()\n\tselect {\n\tcase <-success:\n\tcase <-time.After(d):\n\t}\n}", "func Timeout(d time.Duration) func(*Server) {\n\treturn func(s *Server) {\n\t\ts.timeout = d\n\t}\n}", "func Timeout(expire int, debug bool) {\n\ttime.Sleep(time.Duration(expire) * time.Second)\n\tif debug {\n\t\tlog.Println(colorInfo + \" Time is over\")\n\t\tlog.Println(colorInfo + \" Exiting...\")\n\t}\n\tos.Exit(0)\n}", "func RemoteTimeout(s *scen.Scenario, stdout, stderr io.Writer, addr string, timeout time.Duration) (float64, error) {\n\tclient, err := cloudlus.Dial(addr)\n\tif err != nil {\n\t\treturn math.Inf(1), err\n\t}\n\tdefer client.Close()\n\n\texecfn := func(scn *scen.Scenario) (float64, error) {\n\t\tj, err := BuildRemoteJob(scn, objfile)\n\t\tif err != nil {\n\t\t\treturn math.Inf(1), fmt.Errorf(\"failed to build remote job: %v\", err)\n\t\t}\n\t\tj.Timeout = timeout\n\n\t\t// closing this channel might cause a send on a closed channel if the\n\t\t// timeout in the select below fires before the goroutine completes.\n\t\tdone := make(chan bool, 1)\n\t\tgo func() {\n\t\t\tj, err = client.Run(j)\n\t\t\tdone <- true\n\t\t}()\n\n\t\tselect {\n\t\tcase <-done:\n\t\t\tif err != nil {\n\t\t\t\treturn math.Inf(1), fmt.Errorf(\"job execution failed: %v\", err)\n\t\t\t}\n\t\tcase <-time.After(j.Timeout + 1*time.Hour):\n\t\t\treturn math.Inf(1), fmt.Errorf(\"job rpc timeout limit reached\")\n\t\t}\n\n\t\tif err := writeLogs(j, stdout, stderr); err != nil {\n\t\t\treturn math.Inf(1), fmt.Errorf(\"job logging failed: %v\", err)\n\t\t}\n\n\t\tdata, err := client.RetrieveOutfileData(j, objfile)\n\t\tif err != nil {\n\t\t\treturn math.Inf(1), fmt.Errorf(\"couldn't find objective result file: %v\", err)\n\t\t}\n\n\t\tval, err := strconv.ParseFloat(strings.TrimSpace(string(data)), 64)\n\t\tif err != nil {\n\t\t\treturn math.Inf(1), fmt.Errorf(\"invalid objective string '%s': %v\", data, err)\n\t\t}\n\t\treturn val, nil\n\t}\n\n\treturn s.CalcTotalObjective(execfn)\n}", "func (pm *Manager) ExecTimeout(timeout time.Duration, desc, cmdName string, args ...string) (string, string, error) {\n\treturn pm.ExecDir(timeout, \"\", desc, cmdName, args...)\n}", "func WithTimeout(d time.Duration, cancelFunc func(*Entry)) ExecOption {\n\treturn func(opt *Option) {\n\t\topt.timeout = d\n\t\topt.cancelFunc = cancelFunc\n\t}\n}", "func (r *Retrier) Retry(fn func() error) error {\n\tstart := time.Now()\n\tretries := 0\n\tvar err error\n\tfor retry := true; retry; retry = time.Since(start) < r.timeout {\n\t\terr = fn()\n\t\tretries += 1\n\t\tif err == nil {\n\t\t\tfmt.Printf(\"Retry execution successful with %d retries in duration %v\", retries, time.Since(start))\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Printf(\"Error happened during retry after %d retries: %v\", retries, err)\n\n\t\tretry, wait := r.retryPolicy(retries, err)\n\t\tif !retry {\n\t\t\tfmt.Println(\"Execution aborted by retry policy\")\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"Sleeping before next retry: duration - %v\", wait)\n\t\ttime.Sleep(wait)\n\t}\n\n\tfmt.Printf(\"Timeout reached after %d retries in duration %v. Returning error: %v\", retries, time.Since(start), err)\n\n\treturn err\n}", "func CloseWithTimeout(close func(ctx context.Context) error, timeout time.Duration) {\n\tClose(&timeoutCloser{close: close, timeout: timeout})\n}", "func execTimeout(d time.Duration, name string, args ...string) error {\n\tcmd := exec.Command(name, args...)\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tif d <= 0 {\n\t\treturn cmd.Wait()\n\t}\n\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- cmd.Wait()\n\t}()\n\n\tduration := time.Second * d\n\tafter := time.NewTimer(duration)\n\tselect {\n\tcase <-after.C:\n\t\tcmd.Process.Kill()\n\n\t\t//wait goroutine return\n\t\treturn <-done\n\tcase err := <-done:\n\t\treturn err\n\t}\n}", "func PingTimeout(addr string, timeout int) (PingResponse, error) {\n\treturn ping(addr, time.Millisecond * time.Duration(timeout))\n}", "func WithTimeout(t time.Duration) OptFunc {\n\treturn func(d *Downloader) {\n\t\td.timeout = t\n\t}\n}", "func (f MLFindFileStructure) WithTimeout(v time.Duration) func(*MLFindFileStructureRequest) {\n\treturn func(r *MLFindFileStructureRequest) {\n\t\tr.Timeout = v\n\t}\n}", "func (c *Client) ScheduleTimeout(timeout time.Duration, task func()) error {\n\treturn c.schedule(task, time.After(timeout))\n}", "func AddTimeout() {}", "func TestFileTimeout(t *testing.T) {\n\t// Check it this is short run\n\tif testing.Short() {\n\t\tt.Skip(\"skipping TestFileTimeout in short mode.\")\n\t}\n\n\tfmt.Println(\"Run with '-short' to skip this longer test\")\n\n\t// Create a temporary directory\n\tdir, err := ioutil.TempDir(\"\", \"gorilla_test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\t// Create a test server\n\tts := httptest.NewServer(router())\n\tdefer ts.Close()\n\n\t// Run the code\n\tfileErr := File(dir, ts.URL+\"/timeout\")\n\n\t// Check the error output to confirm we timedout\n\tif fileErr != nil {\n\t\tif !strings.Contains(fileErr.Error(), \"timeout\") {\n\t\t\tt.Errorf(\"Error received from File() did not include 'timeout':\\n%v\", fileErr)\n\t\t}\n\t} else {\n\t\tt.Errorf(\"File() did not return an error when running 'TestFileTimeout'\")\n\t}\n\n}", "func (p *Player) timeout() {\n\tp.Writef(\"You have timed out... good bye!\")\n\tp.exit(TimeoutError)\n}", "func Timeout(d time.Duration) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx, cancel := context.WithTimeout(r.Context(), d)\n\t\t\tdefer cancel()\n\t\t\th.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func Timeout(d time.Duration) func(*Attacker) {\n\treturn func(a *Attacker) {\n\t\ta.client.Timeout = d\n\t}\n}", "func InvokeWithTimer(m Callable, timer *time.Timer) (interface{}, error) {\n\tdone := make(chan interface{}, 1)\n\tgo m.DoCall(done)\n\tselect {\n\tcase hsResult := <-done:\n\t\treturn hsResult, nil\n\tcase <-timer.C:\n\t\tm.Cancel()\n\t\treturn nil, fmt.Errorf(\"timeout\")\n\t}\n}", "func dialWithTimeout(\n\tctx context.Context,\n\td Dialer,\n\ta string,\n\tto time.Duration,\n) (net.Conn, error) {\n\tech := make(chan error)\n\tworky := make(chan net.Conn)\n\t/* Dial the address */\n\tgo func() {\n\t\tc, err := d.Dial(\"tcp\", a)\n\t\t/* When it's done, send the result back */\n\t\tech <- err\n\t\tworky <- c\n\t}()\n\t/* Wait for something to happen */\n\tselect {\n\tcase <-time.After(to):\n\t\tgo killConnFromChannel(worky)\n\t\treturn nil, fmt.Errorf(\"timeout\")\n\tcase <-ctx.Done():\n\t\tgo killConnFromChannel(worky)\n\t\treturn nil, fmt.Errorf(\"interrupt\")\n\tcase err := <-ech:\n\t\t/* If there was no error, return it */\n\t\tif nil == err {\n\t\t\treturn <-worky, nil\n\t\t}\n\t\tgo killConnFromChannel(worky)\n\t\treturn nil, err\n\t}\n}", "func PingWithTimeout(addr string, timeout time.Duration) (PingResponse, error) {\n\treturn ping(addr, timeout)\n}", "func Timeout(timeout time.Duration) OptionFunc {\n\treturn func(tc *TracedClient) error {\n\t\tif timeout <= 0 {\n\t\t\treturn errors.New(\"timeout must be positive\")\n\t\t}\n\t\ttc.cl.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func TestSucceedsAfterTimeout(t *testing.T){\n breaker := NewBreaker(2 * time.Second, 2, 2)\n\n breaker.halfOpen()\n\n _, err := breaker.Run(alwaysSucceedsFunc)\n\n evaluateCondition(t, err == nil, \"TestSucceedsAfterTimeout\")\n}", "func timeoutDialer(timeout time.Duration) func(string, string) (net.Conn, error) {\n\treturn func(network, addr string) (c net.Conn, err error) {\n\t\tc, err = net.DialTimeout(network, addr, timeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn\n\t}\n}", "func (o *GetNodeHardwareFastParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (m *Machine) timedOut() error {\n\t// no max time specified, i.e. we can go on forever.\n\tif m.MaxRuntime == 0 {\n\t\treturn nil\n\t}\n\n\truntime := time.Now().Sub(m.StartedAt)\n\n\tif runtime > m.MaxRuntime {\n\t\treturn fmt.Errorf(\"Timed out after %f seconds\", runtime.Seconds())\n\t}\n\n\treturn nil\n}", "func Timeout(timeout time.Duration) func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// add timeout to context\n\t\t\tctx, cancel := context.WithTimeout(r.Context(), timeout)\n\t\t\tdefer cancel()\n\n\t\t\t// call next\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func SetTimeout(callback func(), delay time.Duration) (cancel func()) {\n\treturn SetTimeoutWithContext(context.Background(), callback, delay)\n}", "func stopTimeoutHandler(args []string) {\n\tvar exitCode = 0\n\ttimeout, _ := strconv.Atoi(args[0])\n\tif len(args) > 1 {\n\t\texitCode, _ = strconv.Atoi(args[1])\n\t}\n\n\tfmt.Printf(\"will finish in %dms\\n\", timeout)\n\t<-time.After(time.Millisecond * time.Duration(timeout))\n\n\tos.Exit(exitCode)\n}", "func (pid *Pid) RunAfter(f RunTimerFunc, timeoutMs uint32) *Timer {\n\ttimer := time.AfterFunc(\n\t\ttime.Duration(timeoutMs)*time.Millisecond,\n\t\tf,\n\t)\n\n\treturn &Timer{timer: timer}\n}", "func (o *GetV1FunctionalitiesParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (x Go) Go(f func()) error {\n\tvar started, funcDone chan struct{}\n\tif x.ensureStarted {\n\t\tstarted = make(chan struct{})\n\t}\n\tif x.timeout != 0 {\n\t\tfuncDone = make(chan struct{})\n\t}\n\tif x.wg != nil {\n\t\tx.wg.Add(1)\n\t}\n\n\tgo func() {\n\t\tif started != nil {\n\t\t\tclose(started)\n\t\t}\n\t\tif x.wg != nil {\n\t\t\tdefer x.wg.Done()\n\t\t}\n\t\tif funcDone != nil {\n\t\t\tdefer close(funcDone)\n\t\t}\n\t\tif x.recoverFunc != nil {\n\t\t\tdefer func() {\n\t\t\t\tif e := recover(); e != nil {\n\t\t\t\t\tx.recoverFunc(e)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tif x.before != nil {\n\t\t\tx.before()\n\t\t}\n\t\tif x.after != nil && x.deferAfter {\n\t\t\tdefer x.after()\n\t\t}\n\n\t\tf()\n\n\t\tif x.after != nil && !x.deferAfter {\n\t\t\tx.after()\n\t\t}\n\t}()\n\n\tif started != nil {\n\t\t<-started\n\t}\n\tif funcDone != nil {\n\t\tif x.timeout > 0 {\n\t\t\ttm := time.NewTimer(x.timeout)\n\t\t\tdefer func() {\n\t\t\t\tif !tm.Stop() {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-tm.C:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tselect {\n\t\t\tcase <-funcDone:\n\t\t\tcase <-tm.C:\n\t\t\t\treturn ErrTimeout\n\t\t\t}\n\t\t} else if x.timeout < 0 {\n\t\t\t<-funcDone\n\t\t}\n\t}\n\n\treturn nil\n}", "func WithTimeout(ctx context.Context) (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(ctx, RetryAttempts*RetryInterval)\n}", "func PingTimeout(addr string, timeout int) (PingResponse, error) {\n\tctx := context.Background()\n\tctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Millisecond)\n\tdefer cancel()\n\treturn PingContext(ctx, addr)\n}", "func RunFailedAtLeast(dur time.Duration, f func() error) func() error {\n\treturn func() (err error) {\n\t\tbegin := time.Now()\n\t\terr = f()\n\t\tif d := time.Now().Sub(begin); err != nil && d <= dur {\n\t\t\ttime.Sleep(dur - d)\n\t\t}\n\t\treturn\n\t}\n}", "func validateTimeout(timeout time.Duration) error {\n\tif timeout < time.Millisecond {\n\t\treturn nosqlerr.NewIllegalArgument(\"Timeout must be greater than or equal to 1 millisecond\")\n\t}\n\n\treturn nil\n}", "func IsTimeout(err error) bool", "func Retry(ctx context.Context, retryable func() error, backoffDuration time.Duration) error {\n\tfor {\n\t\tif err := retryable(); err != nil {\n\t\t\tlog.Errorf(\"Failed to execute the retryable function with: %v\", err)\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn fmt.Errorf(\"failed to complete retry function within the timeout\")\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(backoffDuration)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Infof(\"successfully completed the retry function\")\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func Timeout(timeout int64) Option {\n\treturn func(opts *options) {\n\t\topts.timeout = time.Duration(timeout) * time.Second\n\t}\n}", "func (client *Client) CallWithTimeout(topic string, serviceMethod string, args interface{}, reply interface{}, timeout time.Duration) error {\n\tcall := &Call{\n\t\tID: rand.Uint32(),\n\t\tTopic: topic,\n\t\tServiceMethod: serviceMethod,\n\t\tArgs: args,\n\t\tDone: make(chan *Call, 1),\n\t\tReply: reply,\n\t}\n\n\terr := client.send(call)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsentTime := simtime.Now()\n\n\tlog.Debugf(\"id:%d - Waiting for reply\", call.ID)\n\n\tselect {\n\tcase <-call.Done:\n\t\tlog.Debugf(\"id:%d - Returned after %s\", call.ID, time.Since(sentTime))\n\t\treturn call.Error\n\tcase <-time.After(timeout):\n\t\tdelete(client.pending, call.ID)\n\t\treturn fmt.Errorf(\"id:%d - Call to service %s - (method: %s) timed out after %d seconds\", call.ID, topic, serviceMethod, timeout/time.Second)\n\t}\n\n}", "func (c *Conn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) {\n\treturn c.do(timeout, commandName, args...)\n}", "func (t *Timer) Time(ctx context.Context, fn func() error, ts ...Tags) error {\n\tt1 := time.Now()\n\terr := fn()\n\tn := time.Since(t1)\n\n\tts = append(ts, Tags{\"success\": err == nil})\n\tt.Duration(ctx, n, ts...)\n\treturn err\n}", "func WithTimeout(timeout int) OptionPortScanner {\n\treturn timeoutOption(timeout)\n}", "func TestTimeout(t *testing.T) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttime.Sleep(5 * time.Second)\n\t}))\n\tclient := SearchClient{allowedAccessToken, server.URL}\n\tdefer server.Close()\n\n\t_, err := client.FindUsers(SearchRequest{})\n\n\tif err == nil {\n\t\tt.Errorf(\"empty error, must be timeout error\")\n\t} else if !strings.Contains(err.Error(), \"timeout for\") {\n\t\tt.Errorf(\"unexpected error: %v\", err.Error())\n\t}\n}", "func Timeout(check Check, timeout time.Duration) Check {\n\treturn func() error {\n\t\tc := make(chan error, 1)\n\t\tgo func() { c <- check() }()\n\t\tselect {\n\t\tcase err := <-c:\n\t\t\treturn err\n\t\tcase <-time.After(timeout):\n\t\t\treturn timeoutError(timeout)\n\t\t}\n\t}\n}", "func (c *HostClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {\n\treq.timeout = timeout\n\tif req.timeout < 0 {\n\t\treturn ErrTimeout\n\t}\n\treturn c.Do(req, resp)\n}", "func runGeneric(path, parameters string, seconds int) (string, bool) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(seconds)*time.Second)\n\tdefer cancel()\n\n\tcommand := exec.CommandContext(ctx, path, `-PARAMETERS=`+parameters)\n\toutputBytes, err := command.CombinedOutput()\n\toutput := strings.TrimSuffix(string(outputBytes), \"\\n\")\n\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\treturn errors.Render(errors.ExecutionTimeout, path), false\n\t}\n\n\tif err != nil {\n\t\treturn err.Error() + \"\\n\" + output, false\n\t}\n\n\treturn output, true\n}", "func (filterdev *NetworkTap) Timeout() (*syscall.Timeval, error) {\n\tvar tv syscall.Timeval\n\t_, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(filterdev.device.Fd()), syscall.BIOCGRTIMEOUT, uintptr(unsafe.Pointer(&tv)))\n\tif err != 0 {\n\t\treturn nil, syscall.Errno(err)\n\t}\n\treturn &tv, nil\n}", "func (o *DeleteFreeIpaByEnvironmentV1Params) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(o *options) {\n\t\to.timeout = timeout\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(o *options) {\n\t\to.timeout = timeout\n\t}\n}", "func shWithTimeout(howLong time.Duration, name string, args ...string) (string, error) {\n\t// duration can't be zero\n\tif howLong <= 0 {\n\t\treturn \"\", fmt.Errorf(\"Timeout duration needs to be positive\")\n\t}\n\t// set up the results channel\n\tresultsChan := make(chan ShResult, 1)\n\tif isDebugEnabled() {\n\t\tlog.Printf(\"DEBUG: shWithTimeout: %v, %s, %v\", howLong, name, args)\n\t}\n\n\t// fire up the goroutine for the actual shell command\n\tgo func() {\n\t\tout, err := sh(name, args...)\n\t\tresultsChan <- ShResult{Output: out, Err: err}\n\t}()\n\n\tselect {\n\tcase res := <-resultsChan:\n\t\treturn res.Output, res.Err\n\tcase <-time.After(howLong):\n\t\treturn \"\", ShTimeoutError{timeout: howLong}\n\t}\n\n\treturn \"\", nil\n}", "func Timeout(o *Options) func(http.Handler) http.Handler {\n\ttimeout := o.requestTimeout()\n\treturn func(delegate http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\t\tctx, cancel := context.WithTimeout(request.Context(), timeout)\n\t\t\tdefer cancel()\n\t\t\tdelegate.ServeHTTP(response, request.WithContext(ctx))\n\t\t})\n\t}\n}", "func (o *ResendFaxParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func Try(a func() error, max time.Duration, extra ...interface{}) {\n\tx, y := 0, 1\n\tfor {\n\t\terr := actual(a, extra...)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tt := time.Duration(x) * time.Second\n\t\tif t < max {\n\t\t\tx, y = y, x+y\n\t\t}\n\t\ttime.Sleep(t)\n\t}\n}", "func WaitFor(timeout time.Duration, period time.Duration, f func() (bool, error)) error {\n\ttimeoutChan := time.After(timeout)\n\tvar (\n\t\twait bool = true\n\t\terr error\n\t)\n\tfor wait {\n\t\tselect {\n\t\tcase <-timeoutChan:\n\t\t\treturn status.Errorf(codes.DeadlineExceeded, \"Timed out\")\n\t\tdefault:\n\t\t\twait, err = f()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttime.Sleep(period)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestErrorTimeout(t *testing.T) {\n\ttimeout = true\n\tgo createServer()\n\tcreateUser()\n\tloginClient()\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(opts *Opts) error {\n\t\topts.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func (l *LedisConn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (interface{}, error) {\n\tif l.conn == nil {\n\t\treturn nil, ErrConnClosed\n\t}\n\n\tconnWithTimeout, ok := l.conn.(redis.ConnWithTimeout)\n\tif !ok {\n\t\treturn nil, ErrTimeoutNotSupported\n\t}\n\n\tvar err error\n\tvar slot Slot\n\n\tif len(commandName) > 0 {\n\t\tslot, err = l.rewriteAndSend(commandName, args...)\n\t\tif err != nil {\n\t\t\t// could be not-fataled if fatal is pushed into rewriteAndSend\n\t\t\treturn nil, l.fatal(err)\n\t\t}\n\t}\n\n\terr = l.conn.Flush()\n\tif err != nil {\n\t\t// error is captured by underlying conn\n\t\treturn nil, err\n\t}\n\n\terr = l.consumeSlots()\n\tif err != nil {\n\t\t// error is captured by underlying conn\n\t\treturn nil, err\n\t}\n\n\tif len(commandName) > 0 {\n\t\tvar repliesArray [8]interface{}\n\t\treplies, err := l.receiveRepliesWithTimeoutAppend(connWithTimeout, slot.RepliesCount, timeout, repliesArray[:0])\n\t\tif err != nil {\n\t\t\t// error is captured by underlying conn\n\t\t\treturn nil, err\n\t\t}\n\n\t\treply, err := slot.ProcessFunc(replies)\n\t\tif err != nil {\n\t\t\treturn nil, l.fatal(err)\n\t\t}\n\n\t\tif err, ok := reply.(redis.Error); ok {\n\t\t\treturn reply, err\n\t\t}\n\n\t\treturn reply, nil\n\t}\n\n\treturn nil, nil\n}", "func (o *HandleReturnParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetItemByAppIDParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *VectorThumbnailParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (c *Client) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {\n\treq.timeout = timeout\n\tif req.timeout < 0 {\n\t\treturn ErrTimeout\n\t}\n\treturn c.Do(req, resp)\n}", "func TimelimitCapture(routine func(), timeout time.Duration) bool {\n\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\troutine()\n\t}()\n\n\tc := make(chan struct{})\n\tgo func() {\n\t\tdefer close(c)\n\t\twg.Wait()\n\t}()\n\tselect {\n\tcase <-c:\n\t\treturn true\n\tcase <-time.After(timeout):\n\t\tlogrus.Warnf(\"Routine exceed timelimit of %d sec\", timeout/1000000000)\n\t\treturn false\n\t}\n\n}", "func DoTimeout(req *Request, resp *Response, timeout time.Duration) error {\n\treturn defaultClient.DoTimeout(req, resp, timeout)\n}", "func TestTimeout(t *testing.T) {\n\tstderr := &bytes.Buffer{}\n\tstdout := &bytes.Buffer{}\n\tinv := Invocation{\n\t\tDir: \"testdata/context\",\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tArgs: []string{\"timeout\"},\n\t\tTimeout: time.Duration(100 * time.Millisecond),\n\t}\n\tcode := Invoke(inv)\n\tif code != 1 {\n\t\tt.Fatalf(\"expected 1, but got %v, stderr: %q, stdout: %q\", code, stderr, stdout)\n\t}\n\tactual := stdout.String()\n\texpected := regexp.QuoteMeta(\"E | context deadline exceeded\\n\")\n\n\tif matched, _ := regexp.MatchString(expected, actual); !matched {\n\t\tt.Fatalf(\"expected %q, but got %q\", expected, actual)\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(opts *Options) {\n\t\topts.Timeout = timeout\n\t}\n}", "func (o *DeleteCwfNetworkIDParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetWorkItemParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func TestRetryDoInteralFunc(t *testing.T) {\n\texec := func() (error, interface{}){\n\t\tr := number.Random(0, 100000000)\n\t\tfmt.Println(\"r is\", r)\n\t\tif r < 100000000 / 2{\n\t\t\treturn errors.New(\"xx\"), nil\n\t\t}\n\t\treturn nil, map[string]string{\"abc\":\"wocao\"}\n\t}\n\terr, res, count := RetryDoInteralTime(exec, 5, 100)\n\tfmt.Printf(\"TestRetryDoInteralFunc error is %s res is %v count is %d\", err, res, count)\n}", "func (tm *TimerManager) SetTimeout(td time.Duration, arg interface{}, cb TimerCallback) int {\n\n\treturn tm.setTimer(td, false, arg, cb)\n}", "func (o *GetCustomRuleParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func Timeout(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif config.V.BasicTimeout.Duration > 0 {\n\t\t\tc, cancel := context.WithTimeout(r.Context(), config.V.BasicTimeout.Duration)\n\t\t\tdefer cancel()\n\t\t\tr = r.WithContext(c)\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func Run(ctx context.Context, f Runner, cycle time.Duration, maxErrs int, c clock.Clock) (ret *Results) {\n\t// TODO: ts_mon stuff.\n\tret = &Results{Success: true}\n\n\ttmr := c.NewTimer(ctx)\n\tdefer tmr.Stop()\n\n\tnextCycle := cycle\n\tconsecErrs := 0\n\tlog := logging.Get(ctx)\n\n\trun := func() {\n\t\texpvars.Add(\"Running\", 1)\n\t\tdefer expvars.Add(\"Running\", -1)\n\t\tdefer expvars.Add(\"Runs\", 1)\n\n\t\tt0 := c.Now()\n\t\t// TODO(seanmccullough) Optionally cancel overruns via context.WithTimeout.\n\t\terr := f(ctx)\n\t\tdur := c.Now().Sub(t0)\n\t\tif dur > cycle {\n\t\t\tlog.Errorf(\"Task overran by %v (%v - %v)\", (dur - cycle), dur, cycle)\n\t\t\tret.Overruns++\n\t\t\texpvars.Add(\"Overruns\", 1)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Got an error: %v\", err)\n\t\t\tret.Errs++\n\t\t\texpvars.Add(\"Errors\", 1)\n\t\t\tif consecErrs++; consecErrs >= maxErrs {\n\t\t\t\tret.Success = false\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tconsecErrs = 0\n\t\t}\n\n\t\tnextCycle = cycle - dur\n\t\ttmr.Reset(nextCycle)\n\t}\n\n\t// Run f at least once.\n\trun()\n\n\t// Keep running f until ctx is done.\n\tfor {\n\t\tif ar := <-tmr.GetC(); ar.Incomplete() {\n\t\t\treturn ret\n\t\t}\n\t\trun()\n\t\tif !ret.Success {\n\t\t\treturn ret\n\t\t}\n\t}\n}", "func timeoutDialer(secs int) func(net, addr string) (c net.Conn, err error) {\n\treturn func(netw, addr string) (net.Conn, error) {\n\t\tc, err := net.Dial(netw, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.SetDeadline(time.Now().Add(time.Duration(secs) * time.Second))\n\t\treturn c, nil\n\t}\n}" ]
[ "0.7547683", "0.6645868", "0.6638336", "0.63903975", "0.6242012", "0.615414", "0.5971405", "0.5897637", "0.58117443", "0.54398227", "0.54026496", "0.53546005", "0.5248926", "0.5226934", "0.52143896", "0.51938206", "0.5145747", "0.5139251", "0.511258", "0.507757", "0.50604653", "0.496986", "0.4966789", "0.4963066", "0.49447712", "0.49387813", "0.49238366", "0.49133003", "0.49079314", "0.48907822", "0.48693427", "0.4868034", "0.48423567", "0.47939268", "0.47932503", "0.47916958", "0.4790521", "0.4790117", "0.4786006", "0.47708568", "0.4765234", "0.47514558", "0.4748713", "0.4738333", "0.47376555", "0.47237363", "0.47146606", "0.4709653", "0.47016007", "0.46875468", "0.46738395", "0.46704876", "0.46622312", "0.46561825", "0.46377778", "0.46290475", "0.46206918", "0.46202737", "0.45936254", "0.45883083", "0.45827878", "0.45706898", "0.45686686", "0.45647034", "0.4561685", "0.4547357", "0.45418078", "0.4541271", "0.4527846", "0.45238677", "0.45112666", "0.4509026", "0.45054275", "0.4494701", "0.4487118", "0.4487118", "0.4472725", "0.44640443", "0.44570443", "0.4455049", "0.44537547", "0.44529095", "0.44438145", "0.4431994", "0.44298956", "0.44279554", "0.44250312", "0.44150046", "0.44140318", "0.4405448", "0.44013977", "0.44009358", "0.43964097", "0.4392568", "0.43901166", "0.4382889", "0.4379003", "0.43761697", "0.4374143", "0.43718666" ]
0.7212188
1
Generate generates FHIR resources from PatientInfo.
func (b *Bundler) Generate(p *ir.PatientInfo) (*r4pb.Bundle, error) { if p == nil { return nil, errors.New("cannot generate resources from nil PatientInfo") } return b.createBundle(p), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pc PatientController) Patients(w http.ResponseWriter, r *http.Request) {\n\tpatients := db.GetAll()\n\tjson.NewEncoder(w).Encode(patients)\n}", "func (s *Server) generateResources() error {\n\tvar allMethods []method\n\n\tfor _, resource := range s.Resources {\n\t\tfilename := path.Join(s.TargetDir, fmt.Sprintf(\"%v_api\", strings.ToLower(resource.Name))+\".lua\")\n\n\t\tif err := commons.GenerateFile(resource, \"./templates/tarantool/server_resource_api.tmpl\",\n\t\t\t\"server_resource_api\", filename, true); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, method := range resource.Methods {\n\t\t\tallMethods = append(allMethods, *method)\n\t\t\tfilename := path.Join(s.TargetDir, handlersDir, method.Handler()+\".lua\")\n\n\t\t\t// generate method handler file\n\t\t\tif err := commons.GenerateFile(method, \"./templates/tarantool/server_method_handler.tmpl\",\n\t\t\t\t\"server_method_handler\", filename, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tmethods := map[string]interface{}{\n\t\t\"Methods\": allMethods,\n\t}\n\n\t// Generate handlers file\n\tfilename := path.Join(s.TargetDir, handlersDir, \"handlers.lua\")\n\treturn commons.GenerateFile(methods, \"./templates/tarantool/server_handlers.tmpl\", \"server_handlers\", filename, true)\n}", "func (g Generator) NewPatient(person *ir.Person, doctor *ir.Doctor) *state.Patient {\n\tp := &state.Patient{\n\t\tPatientInfo: &ir.PatientInfo{\n\t\t\tClass: g.messageConfig.PatientClass.Outpatient,\n\t\t\tPerson: person,\n\t\t\t// The Hospital Service might be overridden later with the doctor's specialty.\n\t\t\tHospitalService: g.messageConfig.HospitalService,\n\t\t\tAttendingDoctor: doctor,\n\t\t},\n\t\t// The code downstream assumes that Orders exists.\n\t\tOrders: make(map[string]*ir.Order),\n\t\tDocuments: make(map[string]*ir.Document),\n\t}\n\t// If none of the g.messageConfig.PrimaryFacility fields is set, we want the resulting HL7 message to have the entire\n\t// PD1.3 Patient Primary Facility field empty. This is achieved by leaving p.PatientInfo.PrimaryFacility nil.\n\tif g.messageConfig.PrimaryFacility != nil {\n\t\tp.PatientInfo.PrimaryFacility = &ir.PrimaryFacility{\n\t\t\tOrganization: g.messageConfig.PrimaryFacility.OrganizationName,\n\t\t\tID: g.messageConfig.PrimaryFacility.IDNumber,\n\t\t}\n\t}\n\tif doctor != nil {\n\t\tdocWithSpecialty := g.doctors.GetByID(doctor.ID)\n\t\tif docWithSpecialty != nil && docWithSpecialty.Specialty != \"\" {\n\t\t\tp.PatientInfo.HospitalService = docWithSpecialty.Specialty\n\t\t}\n\t}\n\treturn p\n}", "func CreateChaosResource(testsDetails *types.TestDetails, fileData []byte, namespace string, clients environment.ClientSets) error {\n\n\tdecoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(fileData), 100)\n\n\t// for loop to install all the resouces\n\tfor {\n\t\t//runtime defines conversions between generic types and structs to map query strings to struct objects.\n\t\tvar rawObj runtime.RawExtension\n\t\tif err = decoder.Decode(&rawObj); err != nil {\n\t\t\t// if the object is null, successfully installed all manifest\n\t\t\tif rawObj.Raw == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// NewDecodingSerializer adds YAML decoding support to a serializer that supports JSON.\n\t\tobj, gvk, _ := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme).Decode(rawObj.Raw, nil, nil)\n\t\tunstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tunstructuredObj := &unstructured.Unstructured{Object: unstructuredMap}\n\n\t\t// GetAPIGroupResources uses the provided discovery client to gather\n\t\t// discovery information and populate a slice of APIGroupResources.\n\t\tgr, err := restmapper.GetAPIGroupResources(clients.KubeClient.DiscoveryClient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmapper := restmapper.NewDiscoveryRESTMapper(gr)\n\n\t\t// RESTMapping returns a struct representing the resource path and conversion interfaces a\n\t\t// RESTClient should use to operate on the provided group/kind in order of versions.\n\t\tmapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t//ResourceInterface is an API interface to a specific resource under a dynamic client\n\t\tvar dri dynamic.ResourceInterface\n\t\tif mapping.Scope.Name() == meta.RESTScopeNameNamespace {\n\t\t\tunstructuredObj.SetNamespace(namespace)\n\t\t\tdri = clients.DynamicClient.Resource(mapping.Resource).Namespace(unstructuredObj.GetNamespace())\n\t\t} else {\n\t\t\tdri = clients.DynamicClient.Resource(mapping.Resource)\n\t\t}\n\n\t\t// Create Chaos Resource using dynamic resource interface\n\t\tif _, err := dri.Create(unstructuredObj, v1.CreateOptions{}); err != nil {\n\t\t\tif !k8serrors.IsAlreadyExists(err) {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tif unstructuredObj.GetKind() == \"ChaosEngine\" {\n\t\t\t\t\treturn UpdateEngine(testsDetails, clients)\n\t\t\t\t} else if unstructuredObj.GetKind() == \"ChaosExperiment\" {\n\t\t\t\t\treturn UpdateExperiment(testsDetails, clients)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (resource *Patient) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"Patient\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to Patient), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\n}", "func NewPatientInfoController(router gin.IRouter, client *ent.Client) *PatientInfoController {\n\tpi := &PatientInfoController{\n\t\tclient: client,\n\t\trouter: router,\n\t}\n\tpi.register()\n\treturn pi\n}", "func (api *API) GetPatients() (*models.PatientBundle, error) {\n\tcontents, getErr := api.getResource(\"patient\", nil)\n\tif getErr != nil {\n\t\tlog.Print(\"Error making api call for patients\")\n\t\treturn nil, getErr\n\t}\n\n\tdata := &models.PatientBundle{}\n\tif err := json.Unmarshal(contents, data); err != nil {\n\t\tlog.Print(\"Error unmarshalling patients\")\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func NewPatientInfoClient(c config) *PatientInfoClient {\n\treturn &PatientInfoClient{config: c}\n}", "func (t *MedChain) getAllHospitalToPatient(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\t\t// ==== Input sanitation ====\n\t\tfmt.Println(\"- start getAllHospitalToPatient\")\n\n\t\tAssetType := \"HospitalToPatient\"\n\n\t\tqueryString := fmt.Sprintf(\"SELECT valueJson FROM <STATE> WHERE json_extract(valueJson, '$.AssetType') = '%s'\", AssetType)\n\t\t\n\t\tqueryResults, err := getQueryResultForQueryString(stub, queryString)\n\t\t\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\t\n\t\treturn shim.Success(queryResults)\n\t}", "func Generate(meta *data.Meta, base io.Reader,\n values map[string]string) (io.Reader, error) {\n\n filterMap, err := BuildFilterMap(meta, values)\n if err != nil {\n return nil, err\n }\n\n return template.NewFilter(base, filterMap), nil\n}", "func PatientID() string {\n\t// number between 30-100\n\treturn fmt.Sprintf(\"patient-%d\", rand.Intn(15)+1)\n}", "func createResource(path string, data Generater) (err error) {\n\n\tbuf, err := data.Generate()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.WriteFile(path, buf, 0644)\n\n}", "func (a *ClinicalMetadataServiceApiService) GetPatient(ctx _context.Context, patientId string) (Ga4ghPatient, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Ga4ghPatient\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/patients/{patient_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"patient_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", patientId)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v Ga4ghPatient\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func PuppetInfoGenerate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) {\n\tvar results []map[string]string\n\trunData, err := GetPuppetYaml()\n\tif err != nil {\n\t\t// fmt.Print(runData)\n\t\t// fmt.Println(err)\n\t\treturn results, err\n\t}\n\n\t// fmt.Println(runData)\n\tresults = append(results, map[string]string{\n\t\t\"cached_catalog_status\": runData.CachedCatalogStatus,\n\t\t\"catalog_uuid\": runData.CatalogUUID,\n\t\t\"code_id\": runData.CodeID,\n\t\t\"configuration_version\": runData.ConfigurationVersion,\n\t\t\"corrective_change\": runData.CorrectiveChange,\n\t\t\"environment\": runData.Environment,\n\t\t\"host\": runData.Host,\n\t\t\"kind\": runData.Kind,\n\t\t\"master_used\": runData.MasterUsed,\n\t\t\"noop\": runData.Noop,\n\t\t\"noop_pending\": runData.NoopPending,\n\t\t\"puppet_version\": runData.PuppetVersion,\n\t\t\"report_format\": runData.ReportFormat,\n\t\t\"status\": runData.Status,\n\t\t\"time\": runData.Time,\n\t\t\"transaction_completed\": runData.TransactionCompleted,\n\t\t\"transaction_uuid\": runData.TransactionUUID,\n\t})\n\n\treturn results, nil\n}", "func (b *Bundler) createBundle(p *ir.PatientInfo) *r4pb.Bundle {\n\tbundle := &r4pb.Bundle{\n\t\tType: &r4pb.Bundle_TypeCode{\n\t\t\tValue: cpb.BundleTypeCode_BATCH,\n\t\t},\n\t}\n\n\tbundle.Type = &r4pb.Bundle_TypeCode{Value: b.bundleTypeCode}\n\n\tpatient, patientRef := b.patient(p.Person)\n\taddEntry(bundle, patient)\n\n\tallergies := b.allergies(p.Allergies, patientRef)\n\taddEntry(bundle, allergies...)\n\n\tfor _, ec := range p.Encounters {\n\t\tencounter, encounterRef := b.encounter(ec, p.Class)\n\n\t\te := encounter.GetResource().GetEncounter()\n\t\tfor _, lh := range ec.LocationHistory {\n\t\t\tlocation, locationRef := b.location(lh.Location)\n\t\t\taddEntry(bundle, location)\n\t\t\te.Location = append(e.Location, encounterLocation(locationRef, lh.Start, lh.End))\n\t\t}\n\n\t\tfor _, pr := range ec.Procedures {\n\t\t\tpractitioner, practitionerRef := b.practitioner(pr.Clinician)\n\t\t\taddEntry(bundle, practitioner)\n\n\t\t\tprocedure, procedureRef := b.procedure(pr, patientRef, practitionerRef, encounterRef)\n\t\t\taddEntry(bundle, procedure)\n\t\t\te.Diagnosis = append(e.Diagnosis, encounterDiagnosis(procedureRef))\n\t\t}\n\n\t\tfor _, d := range ec.Diagnoses {\n\t\t\tpractitioner, practitionerRef := b.practitioner(d.Clinician)\n\t\t\taddEntry(bundle, practitioner)\n\n\t\t\tcondition, conditionRef := b.condition(d, patientRef, practitionerRef, encounterRef)\n\t\t\taddEntry(bundle, condition)\n\t\t\te.Diagnosis = append(e.Diagnosis, encounterDiagnosis(conditionRef))\n\t\t}\n\t\taddEntry(bundle, encounter)\n\n\t\tfor _, o := range ec.Orders {\n\t\t\tobservations := b.observations(encounterRef, patientRef, o)\n\t\t\taddEntry(bundle, observations...)\n\t\t}\n\t}\n\treturn bundle\n}", "func (t *HeathCare_Chaincode) createDrugInformation(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tfmt.Println(\"\\n=============== start createDrugInformation function ===============\")\n\tstart := time.Now()\n\ttime.Sleep(time.Second)\n\n\tif len(args) != 6 {\n\t\treturn shim.Error(\"expecting 6 argument\")\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif len(args[i]) == 0 {\n\t\t\treturn shim.Error(\"argument \" + strconv.Itoa(i+1) + \" must be declare\")\n\t\t}\n\t}\n\n\t//define argument\n\tpatientId := args[0]\n\tpatientName := args[1]\n\tdrugName := args[2]\n\texpirationDate := args[3]\n\tquantity := args[4]\n\tprescribedBy := args[5]\n\n\t//convert to json\n\tobjectType := \"DrugInformation\"\n\tdrugInformation := &DrugInformation{objectType, patientId, patientName, drugName,\n\t\texpirationDate, quantity, prescribedBy}\n\tdrugInformationAsByte, errDrugInformationAsByte := json.Marshal(drugInformation)\n\tif errDrugInformationAsByte != nil {\n\t\treturn shim.Error(errDrugInformationAsByte.Error())\n\t}\n\n\t//save to ledger\n\terrDrugInformationAsByte = stub.PutPrivateData(\"DrugInformationCollection\", patientId, drugInformationAsByte)\n\tif errDrugInformationAsByte != nil {\n\t\treturn shim.Error(errDrugInformationAsByte.Error())\n\t}\n\n\t//create and save key\n\tindexName := \"id~patient_name\"\n\tDrugInformationIndexKey, errDrugInformationIndexKey := stub.CreateCompositeKey(indexName, []string{drugInformation.ID, drugInformation.PatientName, drugInformation.DrugName, drugInformation.ExpirationDate, drugInformation.Quantity, drugInformation.ExpirationDate})\n\tif errDrugInformationIndexKey != nil {\n\t\treturn shim.Error(errDrugInformationIndexKey.Error())\n\t}\n\tvalue := []byte{0x00}\n\tstub.PutPrivateData(\"DrugInformationCollection\", DrugInformationIndexKey, value)\n\n\tend := time.Now()\n\telapsed := time.Since(start)\n\n\tfmt.Println(\"\\nfunction createDrugInformation\")\n\tfmt.Println(\"time start: \", start.String())\n\tfmt.Println(\"time end: \", end.String())\n\tfmt.Println(\"time execute: \", elapsed.String())\n\tfmt.Println(\"=============== end createDrugInformation function ===============\")\n\n\treturn shim.Success(nil)\n}", "func Generate() error {\n\tlogCategories, err := getDefinitions()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttemp, err := getTemplates()\n\tif err != nil {\n\t\treturn err\n\t}\n\toutputPath := os.Getenv(\"GENERATOR_OUTPUT_PATH\")\n\tavailable := make([]string, 0)\n\tif len(outputPath) == 0 {\n\t\toutputPath = \"./templates\"\n\t}\n\tfor k, content := range logCategories {\n\t\tavailable = append(available, content.ResourceType)\n\t\tos.MkdirAll(fmt.Sprintf(\"%s/%s/\", outputPath, k), os.ModePerm)\n\t\tfr, err := os.Create(fmt.Sprintf(\"%s/%s/rule.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fr, ruleTemplate, content)\n\t\tfp, err := os.Create(fmt.Sprintf(\"%s/%s/parameters.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fp, paramTemplate, nil)\n\t}\n\tos.MkdirAll(outputPath, os.ModePerm)\n\tfa, err := os.Create(fmt.Sprintf(\"%s/available_resources.json\", outputPath))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = temp.ExecuteTemplate(fa, generatedTemplate, available)\n\treturn nil\n}", "func (aip *ActiveIPs) GenerateMetaData() {\n\taip.Type = &ActiveIPsType\n\ty, m, d := aip.Date.Date()\n\taip.Link = fmt.Sprintf(\"/research/active_ips/%04d-%02d-%02d\", y, m, d)\n}", "func CreateNewPatient(c *gin.Context) {\n\tvar patientRequest PatientRequest\n\tc.ShouldBind(&patientRequest)\n\tpatientResponse := PatientResponse{\n\t\tPatientID: \"2018-0001\",\n\t\tName: patientRequest.Name,\n\t\tLastname: patientRequest.Lastname,\n\t\tAge: patientRequest.Age,\n\t}\n\tc.JSON(201, patientResponse)\n\n}", "func ReportSingleApp(appName, infoFlag string) {\n\tif err := common.VerifyAppName(appName); err != nil {\n\t\tcommon.LogFail(err.Error())\n\t}\n\n\tresources, err := common.PropertyGetAll(\"resource\", appName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tflags := []string{}\n\tinfoFlags := map[string]string{}\n\tfor key, value := range resources {\n\t\tflag := fmt.Sprintf(\"--resource-%v\", key)\n\t\tflags = append(flags, flag)\n\t\tinfoFlags[flag] = value\n\t}\n\tsort.Strings(flags)\n\n\tif len(infoFlag) == 0 {\n\t\tcommon.LogInfo2Quiet(fmt.Sprintf(\"%s resource information\", appName))\n\t\tfor _, k := range flags {\n\t\t\tv := infoFlags[k]\n\t\t\tkey := strings.Replace(strings.Replace(strings.TrimPrefix(k, \"--resource-\"), \"-\", \" \", -1), \".\", \" \", -1)\n\t\t\tcommon.LogVerbose(fmt.Sprintf(\"%s%s\", Right(fmt.Sprintf(\"%s:\", key), 31, \" \"), v))\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, k := range flags {\n\t\tv := infoFlags[k]\n\t\tif infoFlag == k {\n\t\t\tfmt.Fprintln(os.Stdout, v)\n\t\t\treturn\n\t\t}\n\t}\n\n\tkeys := reflect.ValueOf(infoFlags).MapKeys()\n\tstrkeys := make([]string, len(keys))\n\tfor i := 0; i < len(keys); i++ {\n\t\tstrkeys[i] = keys[i].String()\n\t}\n\tcommon.LogFail(fmt.Sprintf(\"Invalid flag passed, valid flags: %s\", strings.Join(strkeys, \", \")))\n}", "func (c *DrugAllergyClient) QueryPatient(da *DrugAllergy) *PatientInfoQuery {\n\tquery := &PatientInfoQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := da.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(drugallergy.Table, drugallergy.FieldID, id),\n\t\t\tsqlgraph.To(patientinfo.Table, patientinfo.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, drugallergy.PatientTable, drugallergy.PatientColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(da.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (i *Info) generateInfoSite() error {\n\tbuf := new(bytes.Buffer)\n\tif err := i.template.Execute(buf, i.Info); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"Created template: \\n%s\", buf.String())\n\ti.result = buf.String()\n\treturn nil\n\n}", "func (daq *DrugAllergyQuery) QueryPatient() *PatientInfoQuery {\n\tquery := &PatientInfoQuery{config: daq.config}\n\tquery.path = func(ctx context.Context) (fromU *sql.Selector, err error) {\n\t\tif err := daq.prepareQuery(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(drugallergy.Table, drugallergy.FieldID, daq.sqlQuery()),\n\t\t\tsqlgraph.To(patientinfo.Table, patientinfo.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, drugallergy.PatientTable, drugallergy.PatientColumn),\n\t\t)\n\t\tfromU = sqlgraph.SetNeighbors(daq.driver.Dialect(), step)\n\t\treturn fromU, nil\n\t}\n\treturn query\n}", "func (pa *Patient) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Patient(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", pa.ID))\n\tbuilder.WriteString(\", patient_ID=\")\n\tbuilder.WriteString(pa.PatientID)\n\tbuilder.WriteString(\", patient_name=\")\n\tbuilder.WriteString(pa.PatientName)\n\tbuilder.WriteString(\", patient_cardID=\")\n\tbuilder.WriteString(pa.PatientCardID)\n\tbuilder.WriteString(\", patient_address=\")\n\tbuilder.WriteString(pa.PatientAddress)\n\tbuilder.WriteString(\", patient_tel=\")\n\tbuilder.WriteString(pa.PatientTel)\n\tbuilder.WriteString(\", patient_age=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", pa.PatientAge))\n\tbuilder.WriteString(\", patient_birthday=\")\n\tbuilder.WriteString(pa.PatientBirthday.Format(time.ANSIC))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (*Patient) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r5_core_resources_patient_proto_rawDescGZIP(), []int{0}\n}", "func GeneratorForFlags(f *flag.FlagSet) *crdgenerator.Generator {\n\tg := &crdgenerator.Generator{}\n\tf.StringVar(&g.RootPath, \"root-path\", \"\", \"working dir, must have PROJECT file under the path or parent path if domain not set\")\n\tf.StringVar(&g.OutputDir, \"output-dir\", \"\", \"output directory, default to 'config/crds' under root path\")\n\tf.StringVar(&g.Domain, \"domain\", \"\", \"domain of the resources, will try to fetch it from PROJECT file if not specified\")\n\t// TODO: Do we need this? Is there a possibility that a crd is namespace scoped?\n\tf.StringVar(&g.Namespace, \"namespace\", \"\", \"CRD namespace, treat it as root scoped if not set\")\n\tf.BoolVar(&g.SkipMapValidation, \"skip-map-validation\", true, \"if set to true, skip generating validation schema for map type in CRD.\")\n\tf.StringVar(&g.APIsPath, \"apis-path\", \"pkg/apis\", \"the path to search for apis relative to the current directory\")\n\tf.StringVar(&g.APIsPkg, \"apis-pkg\", \"\", \"the absolute Go pkg name for current project's api pkg.\")\n\treturn g\n}", "func (s *BBRequestTestSuite) TestGetPatient() {\n\tp, err := s.bbClient.GetPatient(\"012345\", \"543210\", \"A0000\", \"\", now)\n\tassert.Nil(s.T(), err)\n\tassert.Equal(s.T(), 1, len(p.Entries))\n\tassert.Equal(s.T(), \"20000000000001\", p.Entries[0][\"resource\"].(map[string]interface{})[\"id\"])\n}", "func generate(copyrights string, collector *collector, templateBuilder templateBuilder) {\n\tfor _, pkg := range collector.Packages {\n\t\tfileTemplate := fileTpl{\n\t\t\tCopyright: copyrights,\n\n\t\t\tStandardImports: []string{\n\t\t\t\t\"fmt\",\n\t\t\t\t\"unicode\",\n\t\t\t\t\"unicode/utf8\",\n\t\t\t},\n\n\t\t\tCustomImports: []string{\n\t\t\t\t\"github.com/google/uuid\",\n\t\t\t},\n\t\t}\n\t\tfor _, f := range pkg.Files {\n\t\t\tfor _, d := range f.Decls {\n\t\t\t\tg, ok := d.(*ast.GenDecl)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tstructs := structSearch(g)\n\t\t\t\tif len(structs) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, s := range structs {\n\t\t\t\t\tatLeastOneField := false\n\n\t\t\t\t\tfor _, field := range s.Type.Fields.List {\n\n\t\t\t\t\t\tpos := collector.FileSet.Position(field.Type.Pos())\n\t\t\t\t\t\ttyp := collector.Info.TypeOf(field.Type)\n\n\t\t\t\t\t\tcomposedType := \"\"\n\t\t\t\t\t\tbaseName := getType(typ, &composedType)\n\t\t\t\t\t\tfmt.Println(\"Add validation: \", pos, \": \", baseName, \"/\", composedType)\n\n\t\t\t\t\t\tif err := templateBuilder.generateCheck(field, s.Name, baseName, composedType); err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"struct %s: %s\\n\", s.Name, err)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tatLeastOneField = true\n\t\t\t\t\t}\n\n\t\t\t\t\tif !atLeastOneField {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\terr := templateBuilder.generateMethod(s.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"struct gen %s: %s\\n\", s.Name, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfileTemplate.Package = pkg.Name\n\t\terr := templateBuilder.generateFile(pkg.Path, fileTemplate)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Generation error\", err)\n\t\t}\n\t}\n}", "func (f Factory) NewPatient(properties types.PatientProperties) (*types.Patient, error) {\n\tif properties.Gender == \"\" {\n\t\tproperties.Gender = types.Unknown\n\t}\n\treturn &types.Patient{\n\t\tObjectID: uuid.NewString(),\n\t\tFirstName: properties.FirstName,\n\t\tSurname: properties.Surname,\n\t\tSsn: properties.Ssn,\n\t\tDob: properties.Dob,\n\t\tZipcode: properties.Zipcode,\n\t\tGender: properties.Gender,\n\t\tEmail: properties.Email,\n\t\tAvatarUrl: properties.AvatarUrl,\n\t}, nil\n}", "func (pc PatientController) CreatePatient(w http.ResponseWriter, r *http.Request) {\n\t//parse the request to get data\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t//initialize a patient model to populate with the json request\n\tpatient := model.Patient{}\n\t//populate the patient decoding the json\n\terr = json.NewDecoder(r.Body).Decode(&patient)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\t//create the patient using the populated model\n\tdb.CreateOne(patient)\n}", "func (pc PatientController) GetPatient(w http.ResponseWriter, r *http.Request) {\n\t//parse the request to get data\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t//separate the request user id from url\n\turlID := strings.SplitAfter(r.URL.String(), \"/patients/\")\n\t//convert the id to ObjectID\n\tid, _ := primitive.ObjectIDFromHex(urlID[1])\n\t//get the patient relate to the url id\n\tpatient := db.GetOne(id)\n\t//respond with the patient data by json\n\tjson.NewEncoder(w).Encode(patient)\n}", "func IntoResourceFile(p *Params, in io.Reader, out io.Writer) error {\n\treader := yamlDecoder.NewYAMLReader(bufio.NewReaderSize(in, 4096))\n\tfor {\n\t\traw, err := reader.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkinds := map[string]struct {\n\t\t\ttyp interface{}\n\t\t\tinject func(typ interface{}) error\n\t\t}{\n\t\t\t\"Job\": {\n\t\t\t\ttyp: &batch.Job{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, &((typ.(*batch.Job)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"DaemonSet\": {\n\t\t\t\ttyp: &v1beta1.DaemonSet{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, &((typ.(*v1beta1.DaemonSet)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"ReplicaSet\": {\n\t\t\t\ttyp: &v1beta1.ReplicaSet{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, &((typ.(*v1beta1.ReplicaSet)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"Deployment\": {\n\t\t\t\ttyp: &v1beta1.Deployment{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, &((typ.(*v1beta1.Deployment)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"ReplicationController\": {\n\t\t\t\ttyp: &v1.ReplicationController{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, ((typ.(*v1.ReplicationController)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"StatefulSet\": {\n\t\t\t\ttyp: &appsv1beta1.StatefulSet{},\n\t\t\t\tinject: func(typ interface{}) error {\n\t\t\t\t\treturn injectIntoPodTemplateSpec(p, &((typ.(*appsv1beta1.StatefulSet)).Spec.Template))\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tvar updated []byte\n\t\tvar meta metav1.TypeMeta\n\t\tif err = yaml.Unmarshal(raw, &meta); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif kind, ok := kinds[meta.Kind]; ok {\n\t\t\tif err = yaml.Unmarshal(raw, kind.typ); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = kind.inject(kind.typ); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif updated, err = yaml.Marshal(kind.typ); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tupdated = raw // unchanged\n\t\t}\n\n\t\tif _, err = out.Write(updated); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err = fmt.Fprint(out, \"---\\n\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Generate(swagger *openapi3.Swagger, packageName string, opts Options) (string, error) {\n\timportMapping = constructImportMapping(opts.ImportMapping)\n\n\tfilterOperationsByTag(swagger, opts)\n\tif !opts.SkipPrune {\n\t\tpruneUnusedComponents(swagger)\n\t}\n\n\t// This creates the golang templates text package\n\tTemplateFunctions[\"opts\"] = func() Options { return opts }\n\tt := template.New(\"oapi-codegen\").Funcs(TemplateFunctions)\n\t// This parses all of our own template files into the template object\n\t// above\n\tt, err := templates.Parse(t)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error parsing oapi-codegen templates\")\n\t}\n\n\t// Override built-in templates with user-provided versions\n\tfor _, tpl := range t.Templates() {\n\t\tif _, ok := opts.UserTemplates[tpl.Name()]; ok {\n\t\t\tutpl := t.New(tpl.Name())\n\t\t\tif _, err := utpl.Parse(opts.UserTemplates[tpl.Name()]); err != nil {\n\t\t\t\treturn \"\", errors.Wrapf(err, \"error parsing user-provided template %q\", tpl.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\tops, err := OperationDefinitions(swagger)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error creating operation definitions\")\n\t}\n\n\tvar typeDefinitions, constantDefinitions string\n\tif opts.GenerateTypes {\n\t\ttypeDefinitions, err = GenerateTypeDefinitions(t, swagger, ops, opts.ExcludeSchemas)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating type definitions\")\n\t\t}\n\n\t\tconstantDefinitions, err = GenerateConstants(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating constants\")\n\t\t}\n\n\t}\n\n\tvar echoServerOut string\n\tif opts.GenerateEchoServer {\n\t\techoServerOut, err = GenerateEchoServer(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar chiServerOut string\n\tif opts.GenerateChiServer {\n\t\tchiServerOut, err = GenerateChiServer(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar clientOut string\n\tif opts.GenerateClient {\n\t\tclientOut, err = GenerateClient(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating client\")\n\t\t}\n\t}\n\n\tvar clientWithResponsesOut string\n\tif opts.GenerateClient {\n\t\tclientWithResponsesOut, err = GenerateClientWithResponses(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating client with responses\")\n\t\t}\n\t}\n\n\tvar inlinedSpec string\n\tif opts.EmbedSpec {\n\t\tinlinedSpec, err = GenerateInlinedSpec(t, swagger)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\tw := bufio.NewWriter(&buf)\n\n\texternalImports := importMapping.GoImports()\n\timportsOut, err := GenerateImports(t, externalImports, packageName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error generating imports\")\n\t}\n\n\t_, err = w.WriteString(importsOut)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing imports\")\n\t}\n\n\t_, err = w.WriteString(constantDefinitions)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing constants\")\n\t}\n\n\t_, err = w.WriteString(typeDefinitions)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing type definitions\")\n\n\t}\n\n\tif opts.GenerateClient {\n\t\t_, err = w.WriteString(clientOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing client\")\n\t\t}\n\t\t_, err = w.WriteString(clientWithResponsesOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing client\")\n\t\t}\n\t}\n\n\tif opts.GenerateEchoServer {\n\t\t_, err = w.WriteString(echoServerOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing server path handlers\")\n\t\t}\n\t}\n\n\tif opts.GenerateChiServer {\n\t\t_, err = w.WriteString(chiServerOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing server path handlers\")\n\t\t}\n\t}\n\n\tif opts.EmbedSpec {\n\t\t_, err = w.WriteString(inlinedSpec)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing inlined spec\")\n\t\t}\n\t}\n\n\terr = w.Flush()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error flushing output buffer\")\n\t}\n\n\t// remove any byte-order-marks which break Go-Code\n\tgoCode := SanitizeCode(buf.String())\n\n\t// The generation code produces unindented horrors. Use the Go Imports\n\t// to make it all pretty.\n\tif opts.SkipFmt {\n\t\treturn goCode, nil\n\t}\n\n\toutBytes, err := imports.Process(packageName+\".go\", []byte(goCode), nil)\n\tif err != nil {\n\t\tfmt.Println(goCode)\n\t\treturn \"\", errors.Wrap(err, \"error formatting Go code\")\n\t}\n\treturn string(outBytes), nil\n}", "func generateResponseFile(templFP string, data *gengokit.Data, prevFile io.Reader) (io.Reader, error) {\n\tvar genCode io.Reader\n\tvar err error\n\n\t// Get the actual path to the file rather than the template file path\n\tactualFP := templatePathToActual(templFP, data.Service.Name)\n\n\tswitch templFP {\n\tcase service.ServicePath:\n\t\th, err := service.NewService(data.Service, prevFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot parse previous handler: %q\", actualFP)\n\t\t}\n\n\t\tif genCode, err = h.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render service template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(h, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServiceWrapperPath:\n\t\tw := service.NewServiceWrapper(prevFile)\n\t\tif genCode, err = w.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render middleware template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(w, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdServerPath:\n\t\tr := service.NewCmdServer(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdClientPath:\n\t\tif data.Config.GenClient {\n\t\t\tr := service.NewCmdClient(prevFile)\n\t\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd client template: %s\", templFP)\n\t\t\t}\n\t\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\t\t} else {\n\t\t\treturn nil, ErrGenIgnored\n\t\t}\n\tcase service.ServerPath:\n\t\tr := service.NewServer(nil) // override server.go\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(nil, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerEndpointsPath:\n\t\tedp := service.NewServerEndpoints(prevFile)\n\t\tif genCode, err = edp.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render endpoints template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(edp, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerInterruptPath:\n\t\tintrpt := service.NewServerInterrupt(prevFile)\n\t\tif genCode, err = intrpt.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render interrupt template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(intrpt, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerWrapperPath:\n\t\tr := service.NewServerWrapper(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.BaronPath:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render baron template: %s\", templFP)\n\t\t}\n\t\tactualFP = strings.TrimPrefix(actualFP, \"baron\")\n\t\tactualFP = filepath.Join(data.Config.PBPath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\tdefault:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render template: %s\", templFP)\n\t\t}\n\t\tactualFP = filepath.Join(data.Config.ServicePath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\t}\n\n\tcodeBytes, err := ioutil.ReadAll(genCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ignore error as we want to write the code either way to inspect after\n\t// writing to disk\n\tformattedCode := formatCode(codeBytes)\n\n\treturn bytes.NewReader(formattedCode), nil\n}", "func Generate(env environ.Values, cfg *Config) error {\n\tinfo, err := cfg.Driver.Parse(env.Log, cfg.ConnStr, cfg.Schemas, makeFilter(cfg.IncludeTables, cfg.ExcludeTables))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb, err := makeData(env.Log, info, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(cfg.SchemaPaths) == 0 {\n\t\tenv.Log.Println(\"No SchemaPaths specified, skipping schemas.\")\n\t} else {\n\t\tif err := generateSchemas(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg.EnumPaths) == 0 {\n\t\tenv.Log.Println(\"No EnumPath specified, skipping enums.\")\n\t} else {\n\t\tif err := generateEnums(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg.TablePaths) == 0 {\n\t\tenv.Log.Println(\"No table path specified, skipping tables.\")\n\t} else {\n\t\tif err := generateTables(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn copyStaticFiles(env, cfg.StaticDir, cfg.OutputDir)\n}", "func (mpc *MedicalProcedureCreate) SetPatient(p *Patient) *MedicalProcedureCreate {\n\treturn mpc.SetPatientID(p.ID)\n}", "func (api *API) FindPatient(firstName string, lastName string, birthDate string) (*models.PatientResource, error) {\n\tqueryParams := make(map[string]string)\n\tqueryParams[\"family\"] = lastName\n\tqueryParams[\"given\"] = firstName\n\tqueryParams[\"birthDate\"] = birthDate\n\tcontents, getErr := api.getResource(\"patient\", queryParams)\n\tif getErr != nil {\n\t\tlog.Print(\"Error making api call to find patients\")\n\t\treturn nil, getErr\n\t}\n\n\tdata := &models.PatientBundle{}\n\tif err := json.Unmarshal(contents, data); err != nil {\n\t\tlog.Print(\"Error unmarshalling patients\")\n\t\treturn nil, err\n\t}\n\n\tif len(data.Entry) != 1 {\n\t\treturn nil, nil\n\t}\n\n\treturn &data.Entry[0].Resource, nil\n}", "func (t *HeathCare_Chaincode) modifyPatientInformation(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tfmt.Println(\"\\n=============== start modifyPatientInformation function ===============\")\n\tstart := time.Now()\n\ttime.Sleep(time.Second)\n\n\tvar jsonResp string\n\n\tif len(args) != 8 {\n\t\treturn shim.Error(\"expecting 8 argument\")\n\t}\n\n\tuserid := args[0]\n\tpatientid := args[1]\n\tlocation := args[2]\n\tcollection := args[3]\n\n\tnewInsuranceCard := args[4]\n\tnewCurrentMedicationInformation := args[5]\n\tnewRelatedMedicalRecords := args[6]\n\tnewmakeNoteOfAppointmentDate := args[7]\n\ttimeQuery := time.Now().String()\n\n\t//get user identity before query\n\tuserIdentityAsBytes, errUserIdentityAsByte := stub.GetPrivateData(collection, userid)\n\tif errUserIdentityAsByte != nil {\n\t\treturn shim.Error(\"cannot get user identity\")\n\t} else if userIdentityAsBytes == nil {\n\t\treturn shim.Error(\"user does not exist\")\n\t}\n\n\tobjectType := \"Query\"\n\tquery := &Query{objectType, userid, patientid, location, timeQuery, \"modify\"}\n\tqueryAsByte, errQueryAsByte := json.Marshal(query)\n\tif errQueryAsByte != nil {\n\t\treturn shim.Error(errQueryAsByte.Error())\n\t}\n\n\t//save to database\n\terrQueryAsByte = stub.PutPrivateData(\"modifyCollection\", userid, queryAsByte)\n\tif errQueryAsByte != nil {\n\t\treturn shim.Error(errQueryAsByte.Error())\n\t}\n\n\t//create index key\n\tindexName := \"userid~patientid\"\n\tqueryIndexKey, errQueryIndexKey := stub.CreateCompositeKey(indexName, []string{query.UserID, query.PatientID, query.Location, query.Purpose})\n\tif errQueryIndexKey != nil {\n\t\treturn shim.Error(errQueryIndexKey.Error())\n\t}\n\n\t//save index\n\tvalue := []byte{0x00}\n\tstub.PutPrivateData(\"modifyCollection\", queryIndexKey, value)\n\n\t//get data\n\tpatientAsBytes, errPatientAsByte := stub.GetPrivateData(\"PatientInformationCollection\", patientid)\n\tif errPatientAsByte != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + patientid + \": \" + errPatientAsByte.Error() + \"\\\"}\"\n\t\treturn shim.Error(jsonResp)\n\t} else if errPatientAsByte == nil {\n\t\treturn shim.Error(\"patient's data does not exist\")\n\t}\n\n\t//convert data of patient to json\n\tpatient := &PatientInformation{}\n\terrPatientAsByte = json.Unmarshal(patientAsBytes, patient)\n\n\t//change data\n\tpatient.InsuranceCard = newInsuranceCard\n\tpatient.CurrentMedicationInformation = newCurrentMedicationInformation\n\tpatient.RelatedMedicalRecords = newRelatedMedicalRecords\n\tpatient.MakeNoteOfAppointmentDate = newmakeNoteOfAppointmentDate\n\n\tpatientAsByte, errPatientAsByte := json.Marshal(patient)\n\n\terrPatientAsByte = stub.PutPrivateData(\"PatientInformationCollection\", patientid, patientAsByte)\n\tif errPatientAsByte != nil {\n\t\treturn shim.Error(\"cannot patient's data\")\n\t}\n\n\tend := time.Now()\n\telapsed := time.Since(start)\n\tfmt.Println(\"function modifyPatientInformation\")\n\tfmt.Println(\"time start: \", start.String())\n\tfmt.Println(\"time end: \", end.String())\n\tfmt.Println(\"time execute: \", elapsed.String())\n\tfmt.Println(\"=============== end modifyPatientInformation function ===============\")\n\n\treturn shim.Success(nil)\n}", "func DnsresolverSubResourceGenerator() gopter.Gen {\n\tif dnsresolverSubResourceGenerator != nil {\n\t\treturn dnsresolverSubResourceGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tdnsresolverSubResourceGenerator = gen.Struct(reflect.TypeOf(DnsresolverSubResource{}), generators)\n\n\treturn dnsresolverSubResourceGenerator\n}", "func SubResourceGenerator() gopter.Gen {\n\tif subResourceGenerator != nil {\n\t\treturn subResourceGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tsubResourceGenerator = gen.Struct(reflect.TypeOf(SubResource{}), generators)\n\n\treturn subResourceGenerator\n}", "func ReportSingleApp(appName, format, infoFlag string) error {\n\tif err := common.VerifyAppName(appName); err != nil {\n\t\treturn err\n\t}\n\n\tresources, err := common.PropertyGetAll(\"resource\", appName)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tflags := map[string]string{}\n\tfor key, value := range resources {\n\t\tflag := fmt.Sprintf(\"--resource-%v\", key)\n\t\tflags[flag] = value\n\t}\n\n\tflagKeys := []string{}\n\tfor flagKey := range flags {\n\t\tflagKeys = append(flagKeys, flagKey)\n\t}\n\n\ttrimPrefix := true\n\tuppercaseFirstCharacter := false\n\treturn common.ReportSingleApp(\"resource\", appName, infoFlag, flags, flagKeys, format, trimPrefix, uppercaseFirstCharacter)\n}", "func (s *SimpleChaincode) pat_create(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) < 3 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\tvar newPat Pat\n\tjson.Unmarshal([]byte(args[2]), &newPat)\n\tvar pat = Pat{Name: newPat.Name, Id: newPat.Id, Quality: newPat.Quality, Owner: newPat.Owner}\n\tpatAsBytes, _ := json.Marshal(pat)\n\tstub.PutState(args[1], patAsBytes)\n\n\t// Notify listeners that an event \"eventInvoke\" have been executed (check line 19 in the file invoke.go)\n\terr := stub.SetEvent(\"eventCreatePat\", []byte{})\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\treturn shim.Success(nil)\n}", "func HasPatient() predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(Table, FieldID),\n\t\t\tsqlgraph.To(PatientTable, FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, PatientTable, PatientColumn),\n\t\t)\n\t\tsqlgraph.HasNeighbors(s, step)\n\t})\n}", "func GenerateQuestionnaireTemplates(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\ts := qst.NewSurvey(\"placeholder\") // type is modified later\n\terrStr := \"\"\n\tif r.Method == \"POST\" {\n\t\t// myfmt.Fprint(w, \"is POST<br>\\n\")\n\t\tfrm := frmT{}\n\t\tdec := form.NewDecoder()\n\t\tdec.SetTagName(\"json\") // recognizes and ignores ,omitempty\n\t\terr := dec.Decode(&frm, r.Form)\n\t\tif err != nil {\n\t\t\terrStr += myfmt.Sprint(err.Error() + \"<br>\\n\")\n\t\t}\n\n\t\ts.Type = frm.Type\n\t\ts.Year = frm.Year\n\t\ts.Month = time.Month(frm.Month)\n\n\t\tt, err := time.ParseInLocation(\"02.01.2006 15:04 CEST\", frm.Deadline, cfg.Get().Loc)\n\t\tif err != nil {\n\t\t\terrStr += myfmt.Sprint(err.Error() + \"<br>\\n\")\n\t\t}\n\t\twavePeriod := time.Date(s.Year, s.Month, 1, 0, 0, 0, 0, cfg.Get().Loc)\n\t\tif t.Sub(wavePeriod) > (30*24)*time.Hour ||\n\t\t\tt.Sub(wavePeriod) < -(10*24)*time.Hour {\n\t\t\terrStr += myfmt.Sprint(\"Should the deadline not be close to the Year-Month?<br>\\n\")\n\t\t}\n\t\ts.Deadline = t\n\n\t\tnewParams := []qst.ParamT{}\n\t\tfor i := 0; i < len(frm.ParamKeys); i++ {\n\t\t\tp := qst.ParamT{}\n\t\t\tp.Name = frm.ParamKeys[i]\n\t\t\tp.Val = frm.ParamVals[i]\n\t\t\tnewParams = append(newParams, p)\n\t\t}\n\t\ts.Params = newParams\n\n\t}\n\n\thtml := s.HTMLForm(sortedKeys(), errStr)\n\tmyfmt.Fprint(w, html) // not Fprintf\n\tmyfmt.Fprintf(w, \"<br>\")\n\t//\n\n\tif r.Method != \"POST\" {\n\t\tmyfmt.Fprintf(w, \"Not a POST request. Won't generate any questionnaire<br>\\n\")\n\t\treturn\n\t}\n\n\t// previously generating all questionnaires\n\tfor _, key := range sortedKeys() {\n\t\tif key != s.Type {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tfnc := gens[s.Type]\n\tq, err := fnc(s)\n\tif err != nil {\n\t\tmyfmt.Fprintf(w, \"Error creating %v: %v<br>\\n\", s.Type, err)\n\t\treturn\n\t}\n\n\tfn := path.Join(qst.BasePath(), s.Filename()+\".json\")\n\terr = q.Save1(fn)\n\tif err != nil {\n\t\tmyfmt.Fprintf(w, \"Error saving %v: %v<br>\\n\", fn, err)\n\t\treturn\n\t}\n\tmyfmt.Fprintf(w, \"%v generated<br>\\n\", fn)\n\n\tif cfg.Get().AnonymousSurveyID == s.Type {\n\t\tmyfmt.Fprint(\n\t\t\tw,\n\t\t\t`<a \n\t\t\t\taccesskey='c' \n\t\t\t\ttarget='_check'\n\t\t\t\ttabindex=2 \n\t\t\t\thref='https://localhost:8083/survey/a' \n\t\t\t><b>c</b>heck </a><br>`)\n\t}\n\n\t//\n\t// create empty styles-quest-[surveytype].css\"\n\t// if it does not yet exist\n\tfcCreate := func(desktopOrMobile string) (bool, error) {\n\t\tsiteCore, _ := tpl.SiteCore(q.Survey.Type)\n\t\tfileNameBody := desktopOrMobile + siteCore\n\t\tpth := path.Join(\".\", \"templates\", fileNameBody+\".css\")\n\t\t_, err := cloudio.ReadFile(pth)\n\t\tif err != nil {\n\t\t\tif cloudio.IsNotExist(err) {\n\t\t\t\trdr := &bytes.Buffer{}\n\t\t\t\terr := cloudio.WriteFile(pth, rdr, 0755)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, myfmt.Errorf(\"could not create %v: %v <br>\\n\", pth, err)\n\t\t\t\t}\n\t\t\t\tmyfmt.Fprintf(w, \"Done creating template %v<br>\\n\", pth)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, myfmt.Errorf(\"other error while checking for %v: %v <br>\\n\", pth, err)\n\t\t}\n\t\treturn false, nil\n\t}\n\n\t// add to parsed templates\n\tfor _, bt := range []string{\"styles-quest-\"} {\n\t\tok, err := fcCreate(bt)\n\t\tif err != nil {\n\t\t\tmyfmt.Fprintf(w, \"Could not generate template %v for %v<br>\\n\", bt, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ok {\n\t\t\t// parse new and previous templates\n\t\t\tdummyReq, err := http.NewRequest(\"GET\", \"\", nil)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to create request for pre-loading assets %v\", err)\n\t\t\t}\n\t\t\trespRec := httptest.NewRecorder()\n\t\t\ttpl.TemplatesPreparse(respRec, dummyReq)\n\t\t\tlog.Printf(\"\\n%v\", respRec.Body.String())\n\t\t}\n\t}\n\n\t//\n}", "func CreateResources(f *os.File, cfg *rest.Config, dynamicClient dynamic.Interface) error {\n\tvar err error\n\tdata, err := os.ReadFile(f.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdecoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(data), 100)\n\tmapper, err := apiutil.NewDiscoveryRESTMapper(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tresource, unstructuredObj, err := getResource(decoder, mapper, dynamicClient)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t_, err = resource.Create(context.Background(), unstructuredObj, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Controller) GetPatient(pq *PatientQuery) (*store.Patient, error) {\n\tid := pq.ID\n\tpnt, err := c.store.GetPatient(id, pq.BirthDate)\n\tif err != nil && err == store.ErrSearch {\n\t\tlog.Println(err)\n\t\treturn nil, ErrSearchInput\n\t} else if err != nil && err != store.ErrNotFound {\n\t\t// avoid leaking sensitive info\n\t\tlog.Println(err)\n\t\treturn nil, ErrLookingUpInfo\n\t}\n\n\t// patient found nothing to do\n\tif pnt != nil && err != store.ErrNotFound {\n\t\treturn pnt, nil\n\t}\n\n\tif c.FeatureIsEnabled(\"disable-yakeen\") {\n\t\treturn nil, store.ErrNotFound\n\t}\n\n\t// prepare birthDate based on patient type\n\t// hijri for citizens, gregorian for expats\n\tswitch pq.Kind() {\n\tcase KindCitizen:\n\t\tif pnt.DateH != nil {\n\t\t\tpq.BirthDate = *pnt.DateH\n\t\t}\n\t\tfmt.Println(pq)\n\tcase KindExpat:\n\t\tif pnt.DateG != nil {\n\t\t\tpq.BirthDate = *pnt.DateG\n\t\t}\n\t\tfmt.Println(pq)\n\t}\n\n\terr = c.getPnt(pq, pnt)\n\tif err != nil && (err == yakeen.ErrBadDOB || err == yakeen.ErrBadID) {\n\t\tlog.Println(err)\n\t\treturn nil, ErrSearchInput\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\t// avoid leaking sensitive info\n\t\treturn nil, ErrFetchingInfo\n\t}\n\n\t// compute patient age\n\tpnt.Age = c.calcAge(pnt.DateG)\n\n\t// get nationality iso code\n\tcountry, _ := c.store.GetCountryIsoCode(pnt.Nationality)\n\tif country != nil {\n\t\tpnt.NationalityCode = country.Code\n\t\tpnt.Nationality = country.CountryNameEn\n\t}\n\n\t// add to db\n\tgo c.addPatient(pnt)\n\n\treturn pnt, nil\n}", "func (c *client) ListPatient(filter map[string]interface{}, limit int64, offset int64) ([]*models.Patient, error) {\n\tvar pat []*models.Patient\n\n\tif err := c.db.Select(&pat, fmt.Sprintf(\"SELECT * FROM %s %s LIMIT %b, %b\", patientTableName, mkFilter(filter), offset, limit)); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn pat, domainErr.NewAPIError(domainErr.NotFound, err)\n\t\t}\n\t\treturn pat, err\n\t}\n\n\treturn pat, nil\n}", "func (s *Server) Generate() error {\n\tif err := s.generateSchemas(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.generateMain(); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.generateResources()\n}", "func TestGenerator_Generate(t *testing.T) {\n\timportmap := map[string]string{\n\t\t\"policy/v1beta1/value_type.proto\": \"istio.io/api/policy/v1beta1\",\n\t\t\"mixer/adapter/model/v1beta1/extensions.proto\": \"istio.io/api/mixer/adapter/model/v1beta1\",\n\t\t\"gogoproto/gogo.proto\": \"github.com/gogo/protobuf/gogoproto\",\n\t\t\"google/protobuf/duration.proto\": \"github.com/gogo/protobuf/types\",\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfdsFiles map[string]string // FDS and their package import paths\n\t\twant string\n\t}{\n\t\t{\"AllTemplates\", map[string]string{\n\t\t\t\"testdata/check/template.descriptor\": \"istio.io/istio/mixer/template/list\",\n\t\t\t\"testdata/report2/template.descriptor\": \"istio.io/istio/mixer/template/metric\",\n\t\t\t\"testdata/quota/template.descriptor\": \"istio.io/istio/mixer/template/quota\",\n\t\t\t\"testdata/apa/template.descriptor\": \"istio.io/istio/mixer/template/apa\",\n\t\t\t\"testdata/report1/template.descriptor\": \"istio.io/istio/mixer/template/log\"},\n\t\t\t\"testdata/template.gen.go.golden\"},\n\t}\n\tfor _, v := range tests {\n\t\tt.Run(v.name, func(t *testing.T) {\n\t\t\ttestTmpDir := path.Join(os.TempDir(), \"bootstrapTemplateTest\")\n\t\t\t_ = os.MkdirAll(testTmpDir, os.ModeDir|os.ModePerm)\n\t\t\toutFile, err := os.Create(path.Join(testTmpDir, path.Base(v.want)))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif !t.Failed() {\n\t\t\t\t\tif removeErr := os.RemoveAll(testTmpDir); removeErr != nil {\n\t\t\t\t\t\tt.Logf(\"Could not remove temporary folder %s: %v\", testTmpDir, removeErr)\n\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tt.Logf(\"Generated data is located at '%s'\", testTmpDir)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tg := Generator{OutFilePath: outFile.Name(), ImportMapping: importmap}\n\t\t\tif err := g.Generate(v.fdsFiles); err != nil {\n\t\t\t\tt.Fatalf(\"Generate(%s) produced an error: %v\", v.fdsFiles, err)\n\t\t\t}\n\n\t\t\tif same := fileCompare(outFile.Name(), v.want, t.Errorf); !same {\n\t\t\t\tt.Errorf(\"Files %v and %v were not the same.\", outFile.Name(), v.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (s *Service) ListPatient(filter map[string]interface{}, limit int64, offset int64) ([]*models.Patient, error) {\n\treturn s.db.ListPatient(filter, offset, limit)\n}", "func generateChartResource(versions repo.ChartVersions, name string, cr *v1beta1.ChartRepo) *v1beta1.Chart {\n\n\tlabels := map[string]string{\n\t\t\"repo\": cr.GetName(),\n\t}\n\tif cr.GetLabels() != nil {\n\t\tproject := cr.GetLabels()[util.ProjectKey]\n\t\tif project != \"\" {\n\t\t\tlabels[util.ProjectKey] = project\n\t\t}\n\t}\n\n\tvar vs []*v1beta1.ChartVersion\n\tfor _, v := range versions {\n\t\tvs = append(vs, &v1beta1.ChartVersion{ChartVersion: *v})\n\t}\n\n\tspec := v1beta1.ChartSpec{\n\t\tVersions: vs,\n\t}\n\n\tchart := v1beta1.Chart{\n\t\tTypeMeta: v1.TypeMeta{\n\t\t\tKind: \"Chart\",\n\t\t\tAPIVersion: \"app.alauda.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: v1.ObjectMeta{\n\t\t\tName: getChartName(cr.GetName(), name),\n\t\t\tNamespace: cr.GetNamespace(),\n\t\t\tLabels: labels,\n\t\t\tOwnerReferences: []v1.OwnerReference{\n\t\t\t\t*util.NewOwnerRef(cr, schema.GroupVersionKind{\n\t\t\t\t\tGroup: \"app.alauda.io\",\n\t\t\t\t\tVersion: \"v1alpha1\",\n\t\t\t\t\tKind: \"ChartRepo\",\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\tSpec: spec,\n\t}\n\n\treturn &chart\n\n}", "func generateGoSampleFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var samples = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar samples = `\\n\"\r\n\r\n var filename = config.Samples.GoSampleFilename\r\n var elementNames = config.Samples.GoSampleElements\r\n\r\n fmt.Printf(\"Generate Go SAMPLE file %s for: \\n %s\\n\", filename, elementNames)\r\n\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n if elementName == \"schema\" {\r\n // sample of the entire schema, can it even work?\r\n obj = schema\r\n } else {\r\n // use the schema subset\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n }\r\n samples[elementName] = sampleType(obj, elementName) \r\n }\r\n samplesOut, err := json.MarshalIndent(&samples, \"\", \" \")\r\n if err != nil {\r\n fmt.Println(\"** ERR ** cannot marshal sample file output for writing\")\r\n return\r\n }\r\n outString += string(samplesOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func (info ResourceInfo) Resources(opts options.Get) [][]string {\n\tincludedHeaders := info.Headers(opts)\n\tresult := make([][]string, len(info.data))\n\n\t// for each resource\n\tfor i, fieldMap := range info.data {\n\n\t\t// for each of the columns that we want to display\n\t\tline := make([]string, len(includedHeaders))\n\t\tfor j, h := range includedHeaders {\n\t\t\tval, ok := fieldMap[h]\n\t\t\tif !ok {\n\t\t\t\tval = \"\"\n\t\t\t}\n\t\t\tline[j] = val\n\t\t}\n\t\tresult[i] = line\n\t}\n\treturn result\n}", "func NewPatientClient(c config) *PatientClient {\n\treturn &PatientClient{config: c}\n}", "func NewPatientClient(c config) *PatientClient {\n\treturn &PatientClient{config: c}\n}", "func NewPatientClient(c config) *PatientClient {\n\treturn &PatientClient{config: c}\n}", "func (g *Generator) generate() (*apimanifests.PackageManifest, error) {\n\tif g.getBase == nil {\n\t\treturn nil, errNoGetBase\n\t}\n\tif g.Version == \"\" {\n\t\treturn nil, errNoVersion\n\t}\n\n\tbase, err := g.getBase()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting PackageManifest base: %v\", err)\n\t}\n\n\tcsvName := genutil.MakeCSVName(g.OperatorName, g.Version)\n\tif g.ChannelName != \"\" {\n\t\tsetChannels(base, g.ChannelName, csvName)\n\t\tsortChannelsByName(base)\n\t\tif g.IsDefaultChannel || len(base.Channels) == 1 {\n\t\t\tbase.DefaultChannelName = g.ChannelName\n\t\t}\n\t} else if len(base.Channels) == 0 {\n\t\tsetChannels(base, \"alpha\", csvName)\n\t\tbase.DefaultChannelName = \"alpha\"\n\t}\n\n\tif err = validatePackageManifest(base); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn base, nil\n}", "func NewPatientChaincode(ctx context.Context, opt *Options) (patient.PatientAPIServer, error) {\n\t// Validation\n\tswitch {\n\tcase ctx == nil:\n\t\treturn nil, errs.NilObject(\"Context\")\n\tcase strings.TrimSpace(opt.ContractID) == \"\":\n\t\treturn nil, errs.MissingCredential(\"ContractId\")\n\tcase opt.SQLDB == nil:\n\t\treturn nil, errs.NilObject(\"SqlDB\")\n\tcase opt.ledgerClient == nil:\n\t\treturn nil, errs.NilObject(\"ledgerClient\")\n\t}\n\n\tpas := &patientAPIServer{\n\t\tctx: ctx,\n\t\tsqlDB: opt.SQLDB,\n\t\tledgerClient: opt.ledgerClient,\n\t}\n\n\t// Auto migration\n\terr := pas.sqlDB.AutoMigrate(&patientMedicalData{}).Error\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to auto migrate patients medical records table: %w\", err)\n\t}\n\n\t// Register the chaincode to ledger server\n\tctxReg := auth.AddSuperAdminMD(ctx)\n\tp, err := auth.AuthenticateSuperAdmin(ctxReg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to authenticate super admin: %v\", err)\n\t}\n\n\tregRes, err := pas.ledgerClient.RegisterContract(ctxReg, &ledger.RegisterContractRequest{\n\t\tSuperAdminId: p.ID, ContractId: opt.ContractID,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to register contract with the ledger server: %v\", err)\n\t}\n\n\tpas.contractID = regRes.ContractId\n\n\treturn pas, nil\n}", "func PartnerInfoGenerator() gopter.Gen {\n\tif partnerInfoGenerator != nil {\n\t\treturn partnerInfoGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tpartnerInfoGenerator = gen.Struct(reflect.TypeOf(PartnerInfo{}), generators)\n\n\treturn partnerInfoGenerator\n}", "func (g *generator) Generate() error {\n\terr := g.Prepare()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// temporary template variable\n\tvar templ string\n\tswitch g.repositoryType {\n\tcase Mongo:\n\t\ttempl = repositorytmpl.MongoRepositoryTemplate\n\t}\n\n\t// compile mongo repository\n\trepoTmpl, err := template.New(\"repository\").Parse(templ)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, resource := range *g.Resources {\n\t\tif entity, ok := resource.(*model.Model); ok {\n\t\t\tgenlog.Info(\"Generating repository for model %s\", entity.Name)\n\t\t\tcontent := bytes.Buffer{}\n\t\t\terr = repoTmpl.Execute(&content,\n\t\t\t\tstruct {\n\t\t\t\t\tModel *model.Model\n\t\t\t\t\tPackageName string\n\t\t\t\t}{\n\t\t\t\t\tModel: entity,\n\t\t\t\t\tPackageName: g.PackageName(),\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.SaveFile(entity.Name+\"Repository\", content)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *RelationAssembler) GenerateJSON() bytes.Buffer {\n\n\t// buffer to store the json data\n\tvar buffer bytes.Buffer\n\n\t// keep track of sub-relations\n\tvar current int\n\tvar relations = make([]*gosmparse.Relation, 1)\n\trelations[0] = a.Relation\n\n\t// synchronize goroutines\n\tvar wg = &sync.WaitGroup{}\n\twg.Add(1)\n\n\t// write all members and sub members to buffer\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor current < len(relations) {\n\n\t\t\t// contains too many child relations\n\t\t\tif len(relations) >= MAX_MEMBER_RELATIONS {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\twriteRelation(&buffer, a, &relations, relations[current])\n\t\t\tcurrent++\n\t\t}\n\t}()\n\n\t// done\n\twg.Wait()\n\n\t// debug max sub relations for this entity\n\t// fmt.Printf(\"%d: %d\\n\", a.Relation.ID, len(relations))\n\n\treturn buffer\n}", "func makeOutputResourcesFromDetailedResponse(schemaID string, response map[string]interface{}) (Resources, error) {\n\tr := Resources{}\n\tfor _, rawList := range response {\n\t\tlist, ok := rawList.([]interface{})\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"detailed response should contain list of resources: %v\", rawList)\n\t\t}\n\n\t\tfor _, rawWrappedObject := range list {\n\t\t\twrappedObject, ok := rawWrappedObject.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, errors.Errorf(\"detailed response contains invalid data: %v\", rawWrappedObject)\n\t\t\t}\n\n\t\t\tfor _, object := range wrappedObject {\n\t\t\t\tr[ResourcesKey] = append(r[ResourcesKey], map[string]interface{}{\n\t\t\t\t\tKindKey: schemaID,\n\t\t\t\t\tDataKey: object,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\treturn r, nil\n}", "func generateResponse(ps []params) *plugin.CodeGeneratorResponse {\n\tvar resp plugin.CodeGeneratorResponse\n\n\tfor _, p := range ps {\n\t\tw := &bytes.Buffer{}\n\t\tif err := tmpl.Execute(w, p); err != nil {\n\t\t\tlog.Fatal(\"unable to execute template: \" + err.Error())\n\t\t}\n\n\t\tfmted, err := format.Source([]byte(w.String()))\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"unable to go-fmt output: \" + err.Error())\n\t\t}\n\n\t\tfileName := \"service.go\"\n\t\tfileContent := string(fmted)\n\t\tresp.File = append(resp.File, &plugin.CodeGeneratorResponse_File{\n\t\t\tName: &fileName,\n\t\t\tContent: &fileContent,\n\t\t})\n\t}\n\n\treturn &resp\n}", "func (c *ClientWithResponses) GetPatientWithResponse(ctx context.Context, clinicId ClinicId, patientId PatientId, reqEditors ...RequestEditorFn) (*GetPatientResponse, error) {\n\trsp, err := c.GetPatient(ctx, clinicId, patientId, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseGetPatientResponse(rsp)\n}", "func CreateResourceFromFile(config *rest.Config, filename string) error {\n\t// Create a restmapper to determine the resource type.\n\tdiscoveryClient, err := discovery.NewDiscoveryClientForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcacheClient := ksUtil.NewMemcachedDiscoveryClient(discoveryClient)\n\tmapper := discovery.NewDeferredDiscoveryRESTMapper(cacheClient, dynamic.VersionInterfaces)\n\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tobjects := bytes.Split(data, []byte(yamlSeparator))\n\tvar o map[string]interface{}\n\tfor _, object := range objects {\n\t\tif err = yaml.Unmarshal(object, &o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta := o[\"apiVersion\"]\n\t\tif a == nil {\n\t\t\tlog.Warnf(\"Unknown resource: %v\", object)\n\t\t\tcontinue\n\t\t}\n\t\tapiVersion := strings.Split(a.(string), \"/\")\n\t\tvar group, version string\n\t\tif len(apiVersion) == 1 {\n\t\t\t// core v1, no group. e.g. namespace\n\t\t\tgroup, version = \"\", apiVersion[0]\n\t\t} else {\n\t\t\tgroup, version = apiVersion[0], apiVersion[1]\n\t\t}\n\t\tkind := o[\"kind\"].(string)\n\t\tgk := schema.GroupKind{\n\t\t\tGroup: group,\n\t\t\tKind: kind,\n\t\t}\n\t\tresult, err := mapper.RESTMapping(gk, version)\n\t\t// result.resource is the resource we need (e.g. pods, services)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// build config for restClient\n\t\tc := rest.CopyConfig(config)\n\t\tc.GroupVersion = &schema.GroupVersion{\n\t\t\tGroup: group,\n\t\t\tVersion: version,\n\t\t}\n\t\tc.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}\n\t\tif group == \"\" {\n\t\t\tc.APIPath = \"/api\"\n\t\t} else {\n\t\t\tc.APIPath = \"/apis\"\n\t\t}\n\t\trestClient, err := rest.RESTClientFor(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// build the request\n\t\tmetadata := o[\"metadata\"].(map[string]interface{})\n\t\tname := metadata[\"name\"].(string)\n\t\tlog.Infof(\"creating %v\\n\", name)\n\n\t\tvar namespace string\n\t\tif metadata[\"namespace\"] != nil {\n\t\t\tnamespace = metadata[\"namespace\"].(string)\n\t\t} else {\n\t\t\tnamespace = \"default\"\n\t\t}\n\n\t\t// Get first to see if object already exists\n\t\tgetRequest := restClient.Get().Resource(result.Resource).Name(name)\n\t\tif result.Scope.Name() == \"namespace\" {\n\t\t\tgetRequest = getRequest.Namespace(namespace)\n\t\t}\n\t\t_, err = getRequest.DoRaw()\n\t\tif err == nil {\n\t\t\tlog.Infof(\"object already exists...\\n\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Post to create the resource.\n\t\tbody, err := json.Marshal(o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trequest := restClient.Post().Resource(result.Resource).Body(body)\n\t\tif result.Scope.Name() == \"namespace\" {\n\t\t\trequest = request.Namespace(namespace)\n\t\t}\n\t\t_, err = request.DoRaw()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func generateResourceList(mgr manager.Manager, s *releasev1.HelmRelease) (kube.ResourceList, error) {\n\tchartDir, err := downloadChart(mgr.GetClient(), s)\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to download the chart\")\n\t\treturn nil, err\n\t}\n\n\tvar values map[string]interface{}\n\n\treqBodyBytes := new(bytes.Buffer)\n\n\terr = json.NewEncoder(reqBodyBytes).Encode(s.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(reqBodyBytes.Bytes(), &values)\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to Unmarshal the spec \", s.Spec)\n\t\treturn nil, err\n\t}\n\n\tklog.V(3).Info(\"ChartDir: \", chartDir)\n\n\tchart, err := loader.LoadDir(chartDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load chart dir: %w\", err)\n\t}\n\n\trcg, err := newRESTClientGetter(mgr, s.Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get REST client getter from manager: %w\", err)\n\t}\n\n\tkubeClient := kube.New(rcg)\n\n\tactionConfig := &action.Configuration{}\n\tif err := actionConfig.Init(rcg, s.GetNamespace(), \"secret\", func(_ string, _ ...interface{}) {}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialized actionConfig: %w\", err)\n\t}\n\n\tinstall := action.NewInstall(actionConfig)\n\tinstall.ReleaseName = s.Name\n\tinstall.Namespace = s.Namespace\n\tinstall.DryRun = true\n\tinstall.ClientOnly = true\n\tinstall.Replace = true\n\n\trelease, err := install.Run(chart, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := kubeClient.Build(bytes.NewBufferString(release.Manifest), false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build kubernetes objects from release manifest: %w\", err)\n\t}\n\n\treturn resources, nil\n}", "func (auo *AntenatalinformationUpdateOne) SetPatient(p *Patient) *AntenatalinformationUpdateOne {\n\treturn auo.SetPatientID(p.ID)\n}", "func (r ResourceCreation) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"id\", r.ID)\n\tpopulate(objectMap, \"location\", r.Location)\n\tpopulate(objectMap, \"name\", r.Name)\n\tpopulate(objectMap, \"properties\", r.Properties)\n\tpopulate(objectMap, \"tags\", r.Tags)\n\tpopulate(objectMap, \"type\", r.Type)\n\treturn json.Marshal(objectMap)\n}", "func (e *effigy) generate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) {\n\t// create an API request which is populated from existing osquery tables.\n\treq, err := e.buildRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// call the API with a JSON encoded request.\n\tresp, err := e.callAPI(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// use the API response to create the osquery result row.\n\tresult := []map[string]string{\n\t\tmap[string]string{\n\t\t\t\"latest_efi_version\": resp.LatestEFIVersion.Msg,\n\t\t\t\"efi_version\": req.ROMVersion,\n\t\t\t\"efi_version_status\": \"success\",\n\t\t\t\"latest_os_version\": resp.LatestOSVersion.Msg,\n\t\t\t\"os_version\": req.OSVersion,\n\t\t\t\"os_version_status\": \"success\",\n\t\t\t\"latest_build_number\": resp.LatestBuildNumber.Msg,\n\t\t\t\"build_number\": req.BuildNumber,\n\t\t\t\"build_number_status\": \"success\",\n\t\t},\n\t}\n\treturn result, nil\n}", "func (da *DrugAllergy) QueryPatient() *PatientQuery {\n\treturn (&DrugAllergyClient{config: da.config}).QueryPatient(da)\n}", "func (g Generator) ResetPatient(p *state.Patient) *state.Patient {\n\tnewP := g.NewPatient(p.PatientInfo.Person, p.PatientInfo.AttendingDoctor)\n\tnewP.Orders = p.Orders\n\tnewP.PatientInfo.HospitalService = p.PatientInfo.HospitalService\n\tnewP.PatientInfo.Encounters = p.PatientInfo.Encounters\n\tnewP.PastVisits = p.PastVisits\n\tnewP.PatientInfo.PrimaryFacility = p.PatientInfo.PrimaryFacility\n\tnewP.PatientInfo.Allergies = p.PatientInfo.Allergies\n\treturn newP\n}", "func (c *PatientClient) QueryPatient(pa *Patient) *PatientofphysicianQuery {\n\tquery := &PatientofphysicianQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := pa.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(patient.Table, patient.FieldID, id),\n\t\t\tsqlgraph.To(patientofphysician.Table, patientofphysician.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, patient.PatientTable, patient.PatientColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(pa.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (d *Dentalappointment) QueryPatient() *PatientQuery {\n\treturn (&DentalappointmentClient{config: d.config}).QueryPatient(d)\n}", "func main() {\n\tgodotenv.Load(os.Getenv(\"PWD\") + \"/.env\")\n\tuser := os.Getenv(\"DB_USERNAME\")\n\tpass := os.Getenv(\"DB_PASSWORD\")\n\thost := os.Getenv(\"DB_HOSTNAME\")\n\tport := os.Getenv(\"DB_PORT\")\n\tdatabase := os.Getenv(\"DB_DATABASE\")\n\n\tmode := flag.String(\"mode\", \"code\", \"Generate Mode\")\n\ttemplatePath := flag.String(\"template\", os.Getenv(\"PWD\")+\"/template\", \"Template Path\")\n\toutputPath := flag.String(\"project\", os.Getenv(\"PWD\")+\"/src\", \"Project Path\")\n\trelationMode := flag.Bool(\"relation\", false, \"Relation Mode\")\n\tflag.Parse()\n\n\tfmt.Println(\"Generate Mode: \" + *mode)\n\tfmt.Println(\"Template Path: \" + *templatePath)\n\tfmt.Println(\"Project Path: \" + *outputPath)\n\n\tif *mode == \"json\" || *mode == \"all\" {\n\t\tfmt.Println(\"Generate:\", \"goapigen.json\")\n\t\tfmt.Println(\"hostdb:\", host)\n\t\tfmt.Println(\"Connecting to mysql server \" + host + \":\" + port)\n\t\tgenjson.GenJson(user, pass, host, port, database, *relationMode)\n\t}\n\n\tif *mode == \"code\" || *mode == \"all\" {\n\t\tgenstruct.GenStruct(*templatePath, *outputPath)\n\t}\n\n\treturn\n}", "func (m *ManagedAppRegistrationItemRequestBuilder) CreateGetRequestInformation(ctx context.Context, requestConfiguration *ManagedAppRegistrationItemRequestBuilderGetRequestConfiguration)(*i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestInformation, error) {\n requestInfo := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.NewRequestInformation()\n requestInfo.UrlTemplate = m.urlTemplate\n requestInfo.PathParameters = m.pathParameters\n requestInfo.Method = i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.GET\n requestInfo.Headers[\"Accept\"] = \"application/json\"\n if requestConfiguration != nil {\n if requestConfiguration.QueryParameters != nil {\n requestInfo.AddQueryParameters(*(requestConfiguration.QueryParameters))\n }\n requestInfo.AddRequestHeaders(requestConfiguration.Headers)\n requestInfo.AddRequestOptions(requestConfiguration.Options)\n }\n return requestInfo, nil\n}", "func Generate(opts GenerateOptions, queryFiles []codegen.QueryFile) error {\n\tpkgName := opts.GoPkg\n\tif pkgName == \"\" {\n\t\tpkgName = filepath.Base(opts.OutputDir)\n\t}\n\tcaser := casing.NewCaser()\n\tcaser.AddAcronyms(opts.Acronyms)\n\ttemplater := NewTemplater(TemplaterOpts{\n\t\tCaser: caser,\n\t\tResolver: NewTypeResolver(caser, opts.TypeOverrides),\n\t\tPkg: pkgName,\n\t})\n\ttemplatedFiles, err := templater.TemplateAll(queryFiles)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"template all: %w\", err)\n\t}\n\n\t// Order for reproducible results.\n\tsort.Slice(templatedFiles, func(i, j int) bool {\n\t\treturn templatedFiles[i].SourcePath < templatedFiles[j].SourcePath\n\t})\n\n\t// Link each child to the package. Necessary so the leader can define all\n\t// Querier methods.\n\tpkg := TemplatedPackage{Files: templatedFiles}\n\tfor i := range templatedFiles {\n\t\ttemplatedFiles[i].Pkg = pkg\n\t}\n\n\ttmpl, err := parseQueryTemplate()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parse generated Go code template: %w\", err)\n\t}\n\temitter := NewEmitter(opts.OutputDir, tmpl)\n\tif err := emitter.EmitAllQueryFiles(templatedFiles); err != nil {\n\t\treturn fmt.Errorf(\"emit generated Go code: %w\", err)\n\t}\n\treturn nil\n}", "func (meta *BundleMetaData) GenerateMetadata() error {\n\t// Create output directory\n\tif err := os.MkdirAll(meta.BundleDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\t// Create annotation values for both bundle.Dockerfile and annotations.yaml, which should\n\t// hold the same set of values always.\n\tvalues := annotationsValues{\n\t\tBundleDir: meta.BundleDir,\n\t\tPackageName: meta.PackageName,\n\t\tChannels: meta.Channels,\n\t\tDefaultChannel: meta.DefaultChannel,\n\t\tIsScorecardConfigPresent: meta.IsScoreConfigPresent,\n\t}\n\n\tfor k, v := range meta.OtherLabels {\n\t\tvalues.OtherLabels = append(values.OtherLabels, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(values.OtherLabels)\n\n\t// Write each file\n\tmetadataDir := filepath.Join(meta.BundleDir, defaultMetadataDir)\n\tif err := os.MkdirAll(metadataDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\tdockerfilePath := defaultBundleDockerfilePath\n\t// If migrating from packagemanifests to bundle, bundle.Dockerfile is present\n\t// inside bundleDir, else it's in the project directory. Hence, dockerfile\n\t// should have the path specified with respect to output directory of resulting bundles.\n\t// Remove this, when pkgman-to-bundle migrate command is removed.\n\tif len(meta.PkgmanifestPath) != 0 {\n\t\tdockerfilePath = filepath.Join(filepath.Dir(meta.BundleDir), \"bundle.Dockerfile\")\n\t\tvalues.BundleDir = filepath.Base(meta.BundleDir)\n\t}\n\n\ttemplateMap := map[string]*template.Template{\n\t\tdockerfilePath: dockerfileTemplate,\n\t\tfilepath.Join(metadataDir, \"annotations.yaml\"): annotationsTemplate,\n\t}\n\n\tfor path, tmpl := range templateMap {\n\t\tlog.Info(fmt.Sprintf(\"Creating %s\", path))\n\t\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err := f.Close(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}()\n\t\tif err = tmpl.Execute(f, values); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Infof(\"Bundle metadata generated successfully\")\n\treturn nil\n}", "func (b *HybridBotanist) generateAdmissionControlsChart() (*chartrenderer.RenderedChart, error) {\n\tconfig, err := b.ShootCloudBotanist.GenerateAdmissionControlConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.ChartShootRenderer.Render(filepath.Join(common.ChartPath, \"shoot-admission-controls\"), \"admission-controls\", metav1.NamespaceSystem, config)\n}", "func createSearchGenreInfo(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n result := createSearchGenreInfoDA()\n fmt.Fprintf(w, result)\n}", "func AddIndependentPropertyGeneratorsForSubResource_STATUS(gens map[string]gopter.Gen) {\n\tgens[\"Id\"] = gen.PtrOf(gen.AlphaString())\n}", "func (c crd) Process(appMeta helmify.AppMetadata, obj *unstructured.Unstructured) (bool, helmify.Template, error) {\n\tif obj.GroupVersionKind() != crdGVC {\n\t\treturn false, nil, nil\n\t}\n\tspecUnstr, ok, err := unstructured.NestedMap(obj.Object, \"spec\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\tversions, _ := yaml.Marshal(specUnstr)\n\tversions = yamlformat.Indent(versions, 2)\n\tversions = bytes.TrimRight(versions, \"\\n \")\n\n\tres := fmt.Sprintf(crdTeml, obj.GetName(), appMeta.ChartName(), string(versions))\n\tname, _, err := unstructured.NestedString(obj.Object, \"spec\", \"names\", \"singular\")\n\tif err != nil || !ok {\n\t\treturn true, nil, errors.Wrap(err, \"unable to create crd template\")\n\t}\n\treturn true, &result{\n\t\tname: name + \"-crd.yaml\",\n\t\tdata: []byte(res),\n\t}, nil\n}", "func (au *AntenatalinformationUpdate) SetPatient(p *Patient) *AntenatalinformationUpdate {\n\treturn au.SetPatientID(p.ID)\n}", "func (c *PatientInfoClient) Create() *PatientInfoCreate {\n\tmutation := newPatientInfoMutation(c.config, OpCreate)\n\treturn &PatientInfoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func HasPatientWith(preds ...predicate.Patient) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(Table, FieldID),\n\t\t\tsqlgraph.To(PatientInverseTable, FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, PatientTable, PatientColumn),\n\t\t)\n\t\tsqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {\n\t\t\tfor _, p := range preds {\n\t\t\t\tp(s)\n\t\t\t}\n\t\t})\n\t})\n}", "func GeneratePlantUMLFiles(master *assembly.MasterTypeCollection, outputFolder string, verbose bool) {\r\n\tif verbose {\r\n\t\tfmt.Println(\"------------------------------------------------------------------------------------------------------------------------------------\")\r\n\t\tfmt.Println(\"------------------------------------------------------------------------------------------------------------------------------------\")\r\n\t}\r\n\r\n\tif verbose {\r\n\t\tfor _, k := range master.GetDataTypeKeys() {\r\n\t\t\tv, _ := master.GetDataType(k)\r\n\t\t\tfmt.Printf(\"%s\\n\", *v)\r\n\t\t}\r\n\r\n\t\tfor _, k := range master.GetScopeKeys() {\r\n\t\t\tv, _ := master.GetScope(k)\r\n\t\t\tfmt.Printf(\"%s\\n\", v)\r\n\t\t}\r\n\t}\r\n\r\n\tscopeUMLBuilderMap := make(map[string]*strings.Builder)\r\n\tscopeNotesBuilderMap := make(map[string]*strings.Builder)\r\n\r\n\t//\r\n\t// generate the scope classes\r\n\t//\r\n\tfor _, scopeName := range master.GetScopeKeys() {\r\n\t\tscope, _ := master.GetScope(scopeName)\r\n\r\n\t\tumlSb := &strings.Builder{}\r\n\t\tscopeUMLBuilderMap[scopeName] = umlSb\r\n\t\tnotesSb := &strings.Builder{}\r\n\t\tscopeNotesBuilderMap[scopeName] = notesSb\r\n\r\n\t\tumlSb.WriteString(\"@startuml\\n\")\r\n\t\tumlSb.WriteString(\"skinparam classAttributeIconSize 0\\n\")\r\n\r\n\t\tumlSb.WriteString(fmt.Sprintf(\"class %s {\\n\", scope.Name))\r\n\r\n\t\tfor _, scopeMethod := range scope.Methods {\r\n\t\t\twriteMethodToStringBuilder(umlSb, scopeMethod, scopeName, \"static\")\r\n\t\t}\r\n\r\n\t\tumlSb.WriteString(\"}\\n\")\r\n\t}\r\n\r\n\t//\r\n\t// generate the data types for each scope\r\n\t//\r\n\r\n\tfor _, k := range master.GetDataTypeKeys() {\r\n\t\tv, _ := master.GetDataType(k)\r\n\r\n\t\tswitch vActual := (*v).(type) {\r\n\t\tcase *types.InterfaceDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\t\t\tumlSb, existing := scopeUMLBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for interface, no scope tracked for '%s\\n\", vActual.GetCannonicalName())\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"interface \\\"%s\\\" {\\n\", vActual.Name))\r\n\t\t\tfor _, method := range vActual.Methods {\r\n\t\t\t\twriteMethodToStringBuilder(umlSb, method, scopeName, \"abstract\")\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(\"}\\n\")\r\n\r\n\t\t\tfor _, promoted := range vActual.PromotedTypes {\r\n\t\t\t\tpromotedName := (*promoted).GetCannonicalName()\r\n\r\n\t\t\t\tif strings.HasPrefix(promotedName, scopeName) {\r\n\t\t\t\t\tpromotedName = (*promoted).GetSimpleName()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" <|-- %s\\n\", promotedName, vActual.Name))\r\n\t\t\t}\r\n\t\tcase *types.StructDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\r\n\t\t\tif vActual.IsBuiltin() {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for builtin type '%s'\\n\", vActual.Name)\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb, existing := scopeUMLBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for struct, no scope tracked for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"class \\\"%s\\\" {\\n\", vActual.Name))\r\n\r\n\t\t\tfor _, attribute := range vActual.Attributes {\r\n\t\t\t\twriteAttributeToStringBuilder(umlSb, attribute, scopeName)\r\n\t\t\t}\r\n\r\n\t\t\tfor _, method := range vActual.Methods {\r\n\t\t\t\twriteMethodToStringBuilder(umlSb, method, scopeName, \"\")\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(\"}\\n\")\r\n\t\t\tfor _, promoted := range vActual.PromotedTypes {\r\n\t\t\t\tpromotedName := (*promoted).GetCannonicalName()\r\n\r\n\t\t\t\tif _, _, isLocal := types.IsNameLocalToScope(promotedName, scopeName); isLocal {\r\n\t\t\t\t\tpromotedName = (*promoted).GetSimpleName()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" <|-- %s\\n\", promotedName, vActual.Name))\r\n\t\t\t}\r\n\r\n\t\t\tfor _, attribute := range vActual.Attributes {\r\n\t\t\t\tattributeTypeName := attribute.CannonicalTypeName\r\n\r\n\t\t\t\tif resolvedName, extractedPrefix, isLocal := types.IsNameLocalToScope(attributeTypeName, scopeName); isLocal {\r\n\t\t\t\t\tattributeTypeName = resolvedName\r\n\t\t\t\t\tif extractedPrefix == types.ArrayDescriptorMarker {\r\n\t\t\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" --* %s\\n\", attributeTypeName, vActual.Name))\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" -- %s\\n\", attributeTypeName, vActual.Name))\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tcase *types.PointerDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.ArrayDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.MapDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.ChannelDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.FunctionDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.EllipsisDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.AliasedTypeDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\t\t\tnotesSb, existing := scopeNotesBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for alias, no scope tracked for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tnotesSb.WriteString(vActual.String())\r\n\t\t\tnotesSb.WriteString(\"\\n\")\r\n\r\n\t\tdefault:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"skipping UML generation for '%s'\\n\", *v)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//\r\n\t// end the scopes and write the files\r\n\t//\r\n\tfor _, k := range master.GetScopeKeys() {\r\n\t\tumlSb := scopeUMLBuilderMap[k]\r\n\t\tnoteSb := scopeNotesBuilderMap[k]\r\n\r\n\t\tif noteSb.Len() > 0 {\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"note as Note%s\\n\", k))\r\n\t\t\tumlSb.WriteString(noteSb.String())\r\n\t\t\tumlSb.WriteString(\"end note\\n\")\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"%s .. Note%s\\n\", k, k))\r\n\t\t}\r\n\r\n\t\tumlSb.WriteString(\"@enduml\\n\")\r\n\r\n\t\tfileName := outputFolder + k + \".uml.txt\"\r\n\t\tuml := umlSb.String()\r\n\t\tumlBytes := []byte(uml)\r\n\t\terr := ioutil.WriteFile(fileName, umlBytes, 0644)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"ERROR: err while writing to %s\\n\", fileName)\r\n\t\t\tfmt.Println(err)\r\n\t\t} else {\r\n\t\t\tfmt.Printf(\"wrote out %s\\n\", fileName)\r\n\t\t}\r\n\t}\r\n\r\n}", "func NewPatientController(router gin.IRouter, client *ent.Client) *PatientController {\n\tpic := &PatientController{\n\t\tclient: client,\n\t\trouter: router,\n\t}\n\n\tpic.register()\n\n\treturn pic\n\n}", "func makeOutputResources(schemaID string, response map[string]interface{}) (Resources, error) {\n\tr := Resources{}\n\tfor _, rawList := range response {\n\t\tlist, ok := rawList.([]interface{})\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"response should contain list of resources: %v\", rawList)\n\t\t}\n\n\t\tfor _, object := range list {\n\t\t\tr[ResourcesKey] = append(r[ResourcesKey], map[string]interface{}{\n\t\t\t\tKindKey: schemaID,\n\t\t\t\tDataKey: object,\n\t\t\t})\n\t\t}\n\t}\n\treturn r, nil\n}", "func (pc *PatientofphysicianCreate) SetIdpatient(p *Patient) *PatientofphysicianCreate {\n\treturn pc.SetIdpatientID(p.ID)\n}", "func Generate(filePath string, info os.FileInfo) (*FileStat, error) {\n\tfs := &FileStat{\n\t\tpath: filePath,\n\t\tname: info.Name(),\n\t\tsize: info.Size(),\n\t\tmode: info.Mode(),\n\t\tmodTime: info.ModTime(),\n\t\tisDir: info.IsDir(),\n\t}\n\n\tif !fs.isDir {\n\t\tfile, err := os.Open(filePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfs.Reader = *bytes.NewReader(buf)\n\t}\n\n\treturn fs, nil\n}", "func genPackage(types map[string]pschema.ComplexTypeSpec, resourceTokens []string, includeObjectMetaType bool) (*pschema.Package, error) {\n\tif includeObjectMetaType {\n\t\ttypes[objectMetaToken] = pschema.ComplexTypeSpec{\n\t\t\tObjectTypeSpec: pschema.ObjectTypeSpec{\n\t\t\t\tType: \"object\",\n\t\t\t},\n\t\t}\n\t}\n\n\tresources := map[string]pschema.ResourceSpec{}\n\tfor _, baseRef := range resourceTokens {\n\t\tcomplexTypeSpec := types[baseRef]\n\t\tresources[baseRef] = pschema.ResourceSpec{\n\t\t\tObjectTypeSpec: complexTypeSpec.ObjectTypeSpec,\n\t\t\tInputProperties: complexTypeSpec.Properties,\n\t\t}\n\t}\n\n\tpkgSpec := pschema.PackageSpec{\n\t\tName: DefaultName,\n\t\tVersion: Version,\n\t\tTypes: types,\n\t\tResources: resources,\n\t}\n\n\tpkg, err := pschema.ImportSpec(pkgSpec, nil)\n\tif err != nil {\n\t\treturn &pschema.Package{}, errors.Wrapf(err, \"could not import spec\")\n\t}\n\n\tif includeObjectMetaType {\n\t\tdelete(types, objectMetaToken)\n\t}\n\n\treturn pkg, nil\n}", "func (p *templateDecoder) prepareResource(obj runtime.Object) error {\n\tmeta.AddLabel(obj, meta.LabelChartName, p.config.Name)\n\n\tif meta.HasGroupKind(obj, statefulSetGK) {\n\t\treturn statefulset.AddOwnerLabels(obj)\n\t}\n\n\treturn nil\n}", "func (muo *MedicalfileUpdateOne) SetPatient(p *Patient) *MedicalfileUpdateOne {\n\treturn muo.SetPatientID(p.ID)\n}", "func (g *AutoRegistryGenerator) Generate(file string, dirPath string, ignoreDirs ...string) {\n\tdirPaths := findDirPathsRecursively(dirPath, ignoreDirs)\n\n\tvar packageDataList []packageData\n\n\tfor _, dirPath := range dirPaths {\n\t\tfor _, pckData := range g.retrievePackageInformation(dirPath) {\n\t\t\tpackageDataList = append(packageDataList, pckData)\n\t\t}\n\t}\n\n\tg.registryWriter.WriteAutoGeneratedDataToFile(packageDataList, file)\n}", "func emitPackage(targetSdkFolder, version string) error {\n\tspec, metadata, err := gen.Schema()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"generating schema\")\n\t}\n\n\toutdir := path.Join(\".\", \"cmd\", \"pulumi-resource-xyz\")\n\terr = emitSchema(spec, version, outdir, \"main\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"writing schema\")\n\t}\n\terr = emitMetadata(metadata, outdir, \"main\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"writing schema\")\n\t}\n\n\tppkg, err := pschema.ImportSpec(*spec, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"importing schema\")\n\t}\n\n\ttoolDescription := \"the Pulumi SDK Generator\"\n\textraFiles := map[string][]byte{}\n\n\tsdkGenerators := map[string]func() (map[string][]byte, error){\n\t\t\"python\": func() (map[string][]byte, error) {\n\t\t\treturn pygen.GeneratePackage(toolDescription, ppkg, extraFiles)\n\t\t},\n\t\t\"nodejs\": func() (map[string][]byte, error) {\n\t\t\treturn nodejsgen.GeneratePackage(toolDescription, ppkg, extraFiles)\n\t\t},\n\t\t\"go\": func() (map[string][]byte, error) {\n\t\t\treturn gogen.GeneratePackage(toolDescription, ppkg)\n\t\t},\n\t\t\"dotnet\": func() (map[string][]byte, error) {\n\t\t\treturn dotnetgen.GeneratePackage(toolDescription, ppkg, extraFiles)\n\t\t},\n\t}\n\n\tfor sdkName, generator := range sdkGenerators {\n\t\tfiles, err := generator()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"generating %s package\", sdkName)\n\t\t}\n\n\t\tfor f, contents := range files {\n\t\t\tif err := emitFile(path.Join(targetSdkFolder, sdkName), f, contents); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"emitting file %v\", f)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (g *Generator) Generate(context *common.Context, schema *schema.Schema) ([]common.Output, error) {\n\tmoduleName := strings.ToLower(schema.Title)\n\tvar outputs []common.Output\n\n\tfor _, def := range schema.Definitions {\n\t\t// create models only for objects\n\t\tif def.Type != nil {\n\t\t\tif t, ok := def.Type.(string); ok {\n\t\t\t\tif t != \"object\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tf, err := generateMainFile(context, schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpath := fmt.Sprintf(\n\t\t\t\"%s%s/main.go\",\n\t\t\tcontext.Config.Target,\n\t\t\tmoduleName,\n\t\t)\n\n\t\toutputs = append(outputs, common.Output{\n\t\t\tContent: f,\n\t\t\tPath: path,\n\t\t})\n\n\t}\n\n\treturn outputs, nil\n\n}", "func (a *APIGen) Info(ctx context.Context) (Info, error) {\n\tpanic(\"Should Not Be Called from Gen Pattern.\")\n}", "func generatorDeployment(c *configuration.Config, a *api.Apicurito) (dep client.Object) {\n\t// Define a new deployment\n\tname := DefineGeneratorName(a)\n\tdeployLabels := map[string]string{\n\t\t\"app\": \"apicurito\",\n\t\t\"component\": name,\n\t\t\"com.company\": \"Red_Hat\",\n\t\t\"rht.prod_name\": \"Red_Hat_Integration\",\n\t\t\"rht.prod_ver\": version.ShortVersion(),\n\t\t\"rht.comp\": \"Fuse\",\n\t\t\"rht.comp_ver\": version.ShortVersion(),\n\t\t\"rht.subcomp\": name,\n\t\t\"rht.subcomp_t\": \"infrastructure\",\n\t}\n\tdep = &appsv1.Deployment{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"Deployment\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: a.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(a, schema.GroupVersionKind{\n\t\t\t\t\tGroup: api.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: api.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: a.Kind,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &a.Spec.Size,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labelComponent(name),\n\t\t\t},\n\t\t\tStrategy: appsv1.DeploymentStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDeploymentStrategyType,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: deployLabels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: c.GeneratorImage,\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\t\t\tName: \"http\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8181,\n\t\t\t\t\t\t\t\tName: \"health\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 9779,\n\t\t\t\t\t\t\t\tName: \"prometheus\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tContainerPort: 8778,\n\t\t\t\t\t\t\t\tName: \"jolokia\",\n\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tFailureThreshold: 3,\n\t\t\t\t\t\t\tInitialDelaySeconds: 180,\n\t\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\t\tTimeoutSeconds: 1,\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"http\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tReadinessProbe: &corev1.Probe{\n\t\t\t\t\t\t\tFailureThreshold: 3,\n\t\t\t\t\t\t\tInitialDelaySeconds: 10,\n\t\t\t\t\t\t\tPeriodSeconds: 10,\n\t\t\t\t\t\t\tSuccessThreshold: 1,\n\t\t\t\t\t\t\tTimeoutSeconds: 1,\n\t\t\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\t\t\tPort: intstr.FromString(\"http\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}", "func Gen(c *cli.Context) error {\n\targs := domain.GenArgs{\n\t\tTargets: []string(c.Args()),\n\t\tFileWriter: registry.NewFileWriter(),\n\t}\n\terr := usecase.Gen(args)\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn cli.NewExitError(err.Error(), 1)\n}", "func (g Generator) NewRegistrationPatientClassAndType() *config.PatientClassAndType {\n\treturn g.patientClassGenerator.Random()\n}", "func NewGetPatientRequest(server string, clinicId ClinicId, patientId PatientId) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParamWithLocation(\"simple\", false, \"clinicId\", runtime.ParamLocationPath, clinicId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pathParam1 string\n\n\tpathParam1, err = runtime.StyleParamWithLocation(\"simple\", false, \"patientId\", runtime.ParamLocationPath, patientId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/v1/clinics/%s/patients/%s\", pathParam0, pathParam1)\n\tif operationPath[0] == '/' {\n\t\toperationPath = \".\" + operationPath\n\t}\n\n\tqueryURL, err := serverURL.Parse(operationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}" ]
[ "0.51413953", "0.5087454", "0.5072285", "0.49409828", "0.49110705", "0.48960957", "0.48723802", "0.48078808", "0.47864226", "0.47639203", "0.47622183", "0.469203", "0.46756795", "0.46626052", "0.46405765", "0.4633882", "0.46261448", "0.46215713", "0.46088475", "0.46037403", "0.45997906", "0.45690635", "0.45667768", "0.4560513", "0.45560545", "0.45429838", "0.4533847", "0.45254144", "0.45226973", "0.4504981", "0.44996276", "0.44905975", "0.44720465", "0.4460026", "0.44502413", "0.44072014", "0.44056392", "0.4389487", "0.43852356", "0.43742144", "0.43714744", "0.4365908", "0.43614224", "0.43493477", "0.43412206", "0.43357217", "0.43089134", "0.429493", "0.429344", "0.42925462", "0.42842123", "0.4282992", "0.42774627", "0.42585212", "0.42585212", "0.42585212", "0.42534006", "0.42431435", "0.42414758", "0.42399922", "0.42351985", "0.42338383", "0.4230747", "0.42212275", "0.4216248", "0.42133075", "0.42067307", "0.42028853", "0.41959447", "0.4194863", "0.41900575", "0.418649", "0.41763958", "0.41670883", "0.41662702", "0.41656998", "0.41559935", "0.4152333", "0.41522336", "0.4151282", "0.41512796", "0.41506663", "0.4149098", "0.41447636", "0.4136264", "0.41311383", "0.41306055", "0.41286343", "0.41241005", "0.41198832", "0.41165164", "0.41156992", "0.41090864", "0.41060367", "0.4105643", "0.41020736", "0.4095158", "0.40940154", "0.40930235", "0.40926284" ]
0.6198387
0
createBundle converts PatientInfo into FHIR and returns an R4 Bundle. Bundle is the toplevel record encapsulating a patient's medical history.
func (b *Bundler) createBundle(p *ir.PatientInfo) *r4pb.Bundle { bundle := &r4pb.Bundle{ Type: &r4pb.Bundle_TypeCode{ Value: cpb.BundleTypeCode_BATCH, }, } bundle.Type = &r4pb.Bundle_TypeCode{Value: b.bundleTypeCode} patient, patientRef := b.patient(p.Person) addEntry(bundle, patient) allergies := b.allergies(p.Allergies, patientRef) addEntry(bundle, allergies...) for _, ec := range p.Encounters { encounter, encounterRef := b.encounter(ec, p.Class) e := encounter.GetResource().GetEncounter() for _, lh := range ec.LocationHistory { location, locationRef := b.location(lh.Location) addEntry(bundle, location) e.Location = append(e.Location, encounterLocation(locationRef, lh.Start, lh.End)) } for _, pr := range ec.Procedures { practitioner, practitionerRef := b.practitioner(pr.Clinician) addEntry(bundle, practitioner) procedure, procedureRef := b.procedure(pr, patientRef, practitionerRef, encounterRef) addEntry(bundle, procedure) e.Diagnosis = append(e.Diagnosis, encounterDiagnosis(procedureRef)) } for _, d := range ec.Diagnoses { practitioner, practitionerRef := b.practitioner(d.Clinician) addEntry(bundle, practitioner) condition, conditionRef := b.condition(d, patientRef, practitionerRef, encounterRef) addEntry(bundle, condition) e.Diagnosis = append(e.Diagnosis, encounterDiagnosis(conditionRef)) } addEntry(bundle, encounter) for _, o := range ec.Orders { observations := b.observations(encounterRef, patientRef, o) addEntry(bundle, observations...) } } return bundle }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Bundler) Generate(p *ir.PatientInfo) (*r4pb.Bundle, error) {\n\tif p == nil {\n\t\treturn nil, errors.New(\"cannot generate resources from nil PatientInfo\")\n\t}\n\treturn b.createBundle(p), nil\n}", "func NewBundle() *Bundle {\n\treturn &Bundle{\n\t\tdecoded: make(map[string]*Package),\n\t}\n}", "func NewBundle() *Bundle {\n\treturn &Bundle{\n\t\tdecoded: make(map[string]*Package),\n\t}\n}", "func Bundle() *i18n.Bundle {\n\tif bundle == nil {\n\t\tbundle = i18n.NewBundle(language.AmericanEnglish)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t}\n\treturn bundle\n}", "func NewBundle() *Bundle {\n\treturn new(Bundle)\n}", "func NewBundle(p map[string]Probe) *Bundle {\n\treturn &Bundle{\n\t\tprobes: p,\n\t}\n}", "func NewBundle() *Bundle {\n\treturn &Bundle{\n\t\tHandlers: make(map[string]Handler),\n\t}\n}", "func (b BundlePlan) Bundle(registry *PieceRegistry, pieceRange PieceRange) (MediaPart, error) {\n\tpiece := new(bytes.Buffer)\n\n\tfor pieceIdx := pieceRange.Start(); pieceIdx <= pieceRange.End(); pieceIdx++ {\n\t\tp, found := registry.GetPiece(pieceIdx)\n\t\tif !found {\n\t\t\treturn MediaPart{}, errors.New(\"piece not found in the registry. could be ignored but kept to further investigate\")\n\t\t}\n\t\tstart := pieceRange.StartOffset(pieceIdx)\n\t\tend := pieceRange.EndOffset(pieceIdx)\n\t\tif start > end {\n\t\t\treturn MediaPart{}, fmt.Errorf(\"start offset %v bigger than end offset %v\", start, end)\n\t\t}\n\t\tif start > len(p.data) {\n\t\t\treturn MediaPart{}, fmt.Errorf(\"start offset %v is bigger than length of slice %v\", start, len(p.data))\n\t\t}\n\t\tif end > len(p.data) {\n\t\t\treturn MediaPart{}, fmt.Errorf(\"end offset %v is bigger than length of slice %v\", start, len(p.data))\n\t\t}\n\n\t\trawData := p.data[start:end]\n\t\t_, err := piece.Write(rawData)\n\t\tif err != nil {\n\t\t\treturn MediaPart{}, err\n\t\t}\n\t}\n\n\treturn NewMediaPart(pieceRange.Torrent().ID(), pieceRange, piece.Bytes()), nil\n}", "func (wc *WerfChart) CreateNewBundle(ctx context.Context, destDir string, inputVals map[string]interface{}) (*Bundle, error) {\n\tif err := os.RemoveAll(destDir); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to remove %q: %s\", destDir, err)\n\t}\n\tif err := os.MkdirAll(destDir, os.ModePerm); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create dir %q: %s\", destDir, err)\n\t}\n\n\tif vals, err := wc.MakeValues(inputVals); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to coalesce input values: %s\", err)\n\t} else if valsData, err := json.Marshal(vals); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to prepare values: %s\", err)\n\t} else {\n\t\tvaluesFile := filepath.Join(destDir, \"values.yaml\")\n\t\tif err := ioutil.WriteFile(valuesFile, append(valsData, []byte(\"\\n\")...), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to write %q: %s\", valuesFile, err)\n\t\t}\n\t}\n\n\tif wc.HelmChart.Metadata != nil {\n\t\tbundleMetadata := *wc.HelmChart.Metadata\n\t\t// Force api v2\n\t\tbundleMetadata.APIVersion = chart.APIVersionV2\n\n\t\tchartYamlFile := filepath.Join(destDir, \"Chart.yaml\")\n\t\tif data, err := json.Marshal(bundleMetadata); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to prepare Chart.yaml data: %s\", err)\n\t\t} else if err := ioutil.WriteFile(chartYamlFile, append(data, []byte(\"\\n\")...), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to write %q: %s\", chartYamlFile, err)\n\t\t}\n\t}\n\n\tif wc.HelmChart.Lock != nil {\n\t\tchartLockFile := filepath.Join(destDir, \"Chart.lock\")\n\t\tif data, err := json.Marshal(wc.HelmChart.Lock); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to prepare Chart.lock data: %s\", err)\n\t\t} else if err := ioutil.WriteFile(chartLockFile, append(data, []byte(\"\\n\")...), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to write %q: %s\", chartLockFile, err)\n\t\t}\n\t}\n\n\ttemplatesDir := filepath.Join(destDir, \"templates\")\n\tif err := os.MkdirAll(templatesDir, os.ModePerm); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create dir %q: %s\", templatesDir, err)\n\t}\n\n\tfor _, f := range wc.HelmChart.Templates {\n\t\tp := filepath.Join(destDir, f.Name)\n\t\tif err := ioutil.WriteFile(p, append(f.Data, []byte(\"\\n\")...), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to write %q: %s\", p, err)\n\t\t}\n\t}\n\n\tif wc.HelmChart.Schema != nil {\n\t\tschemaFile := filepath.Join(destDir, \"values.schema.json\")\n\t\tif data, err := json.Marshal(wc.HelmChart.Schema); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to prepare values.schema.json data: %s\", err)\n\t\t} else if err := ioutil.WriteFile(schemaFile, append(data, []byte(\"\\n\")...), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to write %q: %s\", schemaFile, err)\n\t\t}\n\t}\n\n\tif wc.ExtraAnnotationsAndLabelsPostRenderer.ExtraAnnotations != nil {\n\t\tif err := writeBundleJsonMap(wc.ExtraAnnotationsAndLabelsPostRenderer.ExtraAnnotations, filepath.Join(destDir, \"extra_annotations.json\")); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif wc.ExtraAnnotationsAndLabelsPostRenderer.ExtraLabels != nil {\n\t\tif err := writeBundleJsonMap(wc.ExtraAnnotationsAndLabelsPostRenderer.ExtraLabels, filepath.Join(destDir, \"extra_labels.json\")); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn NewBundle(destDir, wc.LockManager), nil\n}", "func NewBundle(parent context.Context) *Bundle {\n\tb := &Bundle{}\n\tb.context, b.cancel = context.WithCancel(parent)\n\n\treturn b\n}", "func (f *CreateBundleRequest) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tbuffer = f.Bundle.Deserialize(buffer, err)\n\treturn buffer\n}", "func (f *CreateBundleRequest) Serialize(buffer []byte) []byte {\n\tbuffer = f.Bundle.Serialize(buffer)\n\treturn buffer\n}", "func (b *BundleIdent) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tb.App, buffer = deserializeString(buffer, err)\n\tbuffer = b.User.Deserialize(buffer, err)\n\tb.Name, buffer = deserializeString(buffer, err)\n\tb.Incarnation, buffer = deserializeString(buffer, err)\n\treturn buffer\n}", "func (l *Localizer) createLocaleBundleByTag(tag language.Tag) *i18n.Bundle {\n\tbundle := i18n.NewBundle(tag)\n\tbundle.RegisterUnmarshalFunc(\"yml\", yaml.Unmarshal)\n\tl.loadTranslationsToBundle(bundle)\n\n\treturn bundle\n}", "func NewBundle(config *cb.Config) (*Bundle, error) {\n\tmspConfigHandler := oldmspconfig.NewMSPConfigHandler()\n\trootConfig := oldchannelconfig.NewRoot(mspConfigHandler)\n\n\tpolicyProviderMap := make(map[int32]policies.Provider)\n\tfor pType := range cb.Policy_PolicyType_name {\n\t\trtype := cb.Policy_PolicyType(pType)\n\t\tswitch rtype {\n\t\tcase cb.Policy_UNKNOWN:\n\t\t\t// Do not register a handler\n\t\tcase cb.Policy_SIGNATURE:\n\t\t\tpolicyProviderMap[pType] = cauthdsl.NewPolicyProvider(mspConfigHandler)\n\t\tcase cb.Policy_MSP:\n\t\t\t// Add hook for MSP Handler here\n\t\t}\n\t}\n\n\terr := InitializeConfigValues(rootConfig, config.ChannelGroup)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"initializing config values failed\")\n\t}\n\n\tpolicyManager := policies.NewManagerImpl(RootGroupKey, policyProviderMap)\n\terr = InitializePolicyManager(policyManager, config.ChannelGroup)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"initializing policymanager failed\")\n\t}\n\n\treturn &Bundle{\n\t\tmspManager: mspConfigHandler,\n\t\tpolicyManager: policyManager,\n\t\trootConfig: rootConfig,\n\t}, nil\n}", "func (*ProblemBundleFactory) Create(bundle FileTreeNode, relativePath string) error {\n\tfileSvc := file.NewService(nil)\n\n\tif err := bundle.Write(\".\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := fileSvc.Compress(\"./bundle\", filepath.Clean(relativePath)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := bundle.Remove(\".\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Bundle() error {\n\tdir, err := internal.ModRootDir()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get current working directory: %w\", err)\n\t}\n\tfmt.Println(dir)\n\tgen := newGoGenerator(dir)\n\terr = gen.Scan()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot scan module: %w\", err)\n\t}\n\n\terr = gen.Emit()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to generate source code: %w\", err)\n\t}\n\treturn nil\n}", "func BundleFrom(filename string) (*Bundle, error) {\n\tr, err := zip.OpenReader(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Bundle{\n\t\treader: r,\n\t\tdecoded: make(map[string]*Package),\n\t}, nil\n}", "func BundleFrom(filename string) (*Bundle, error) {\n\tr, err := zip.OpenReader(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Bundle{\n\t\treader: r,\n\t\tdecoded: make(map[string]*Package),\n\t}, nil\n}", "func NewBundle(dir, urlPath string) core.Bundle {\n\treturn &bundle{\n\t\tdir: dir,\n\t\turlPath: urlPath,\n\t}\n}", "func (o *ControllerServiceAPI) GetBundle() Bundle {\n\tif o == nil || o.Bundle == nil {\n\t\tvar ret Bundle\n\t\treturn ret\n\t}\n\treturn *o.Bundle\n}", "func LoadBundle(r io.Reader) (data.Bundle, error) {\n\tdat, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn data.Bundle{}, gerrs.Wrap(gerrs.ErrIO, err)\n\t}\n\n\treturn unmarshal(dat)\n}", "func (b *Bundler) BundleFromFile(bundleFile, keyFile string, flavor BundleFlavor, password string) (*Bundle, error) {\n\tlog.Debug(\"Loading Certificate: \", bundleFile)\n\tcertsRaw, err := os.ReadFile(bundleFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(errors.CertificateError, errors.ReadFailed, err)\n\t}\n\n\tvar keyPEM []byte\n\t// Load private key PEM only if a file is given\n\tif keyFile != \"\" {\n\t\tlog.Debug(\"Loading private key: \", keyFile)\n\t\tkeyPEM, err = os.ReadFile(keyFile)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"failed to read private key: \", err)\n\t\t\treturn nil, errors.Wrap(errors.PrivateKeyError, errors.ReadFailed, err)\n\t\t}\n\t\tif len(keyPEM) == 0 {\n\t\t\tlog.Debug(\"key is empty\")\n\t\t\treturn nil, errors.Wrap(errors.PrivateKeyError, errors.DecodeFailed, err)\n\t\t}\n\t}\n\n\treturn b.BundleFromPEMorDER(certsRaw, keyPEM, flavor, password)\n}", "func (re *stubRegistrationService) CreateFederatedBundle(ctx context.Context, request pb.CreateFederatedBundleRequest) (reply common.Empty, err error) {\n\treturn reply, err\n}", "func (token Token) ToBundle(masterToken string) TokenBundle {\n\treturn TokenBundle{\n\t\tAuth: token,\n\t\tMaster: masterToken,\n\t}\n}", "func GenerateBundle(t *testing.T, controller *gomock.Controller, options ...BundleGeneratorOption) *mocks.MockBundle {\n\tbg := BundleGenerator{\n\t\tconfig: BundleConfig,\n\t\tmanifests: []sheaf.BundleManifest{\n\t\t\t{\n\t\t\t\tID: \"deploy.yaml\",\n\t\t\t\tData: SlurpData(t, filepath.Join(\"testdata\", \"manifests\", \"deploy.yaml\")),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\tbg = option(bg)\n\t}\n\n\tbundle := mocks.NewMockBundle(controller)\n\tbundle.EXPECT().Config().Return(bg.config).AnyTimes()\n\n\tm := mocks.NewMockManifestService(controller)\n\tm.EXPECT().List().Return(bg.manifests, nil).AnyTimes()\n\n\tbundle.EXPECT().Manifests().Return(m, nil).AnyTimes()\n\n\timageList, err := images.New([]string{\"image\"})\n\trequire.NoError(t, err)\n\tbundle.EXPECT().Images().Return(imageList, nil).AnyTimes()\n\n\treturn bundle\n}", "func (o *ControllerServiceAPI) SetBundle(v Bundle) {\n\to.Bundle = &v\n}", "func NewBundlePlan() BundlePlan {\n\treturn BundlePlan{}\n}", "func NewBundler(caBundleFile, intBundleFile string, opt ...Option) (*Bundler, error) {\n\tvar caBundle, intBundle []byte\n\tvar err error\n\n\tif caBundleFile != \"\" {\n\t\tlog.Debug(\"Loading CA bundle: \", caBundleFile)\n\t\tcaBundle, err = os.ReadFile(caBundleFile)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"root bundle failed to load: %v\", err)\n\t\t\treturn nil, errors.Wrap(errors.RootError, errors.ReadFailed, err)\n\t\t}\n\t}\n\n\tif intBundleFile != \"\" {\n\t\tlog.Debug(\"Loading Intermediate bundle: \", intBundleFile)\n\t\tintBundle, err = os.ReadFile(intBundleFile)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"intermediate bundle failed to load: %v\", err)\n\t\t\treturn nil, errors.Wrap(errors.IntermediatesError, errors.ReadFailed, err)\n\t\t}\n\t}\n\n\tif IntermediateStash != \"\" {\n\t\tif _, err = os.Stat(IntermediateStash); err != nil && os.IsNotExist(err) {\n\t\t\tlog.Infof(\"intermediate stash directory %s doesn't exist, creating\", IntermediateStash)\n\t\t\terr = os.MkdirAll(IntermediateStash, 0755)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"failed to create intermediate stash directory %s: %v\",\n\t\t\t\t\tIntermediateStash, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlog.Infof(\"intermediate stash directory %s created\", IntermediateStash)\n\t\t}\n\t}\n\n\treturn NewBundlerFromPEM(caBundle, intBundle, opt...)\n\n}", "func (b *BundleIdent) Serialize(buffer []byte) []byte {\n\tbuffer = serializeString(b.App, buffer)\n\tbuffer = b.User.Serialize(buffer)\n\tbuffer = serializeString(b.Name, buffer)\n\tbuffer = serializeString(b.Incarnation, buffer)\n\treturn buffer\n}", "func (r *pgRepository) GetForBundle(ctx context.Context, tenant string, id string, bundleID string) (*model.APIDefinition, error) {\n\treturn r.GetByID(ctx, tenant, id)\n}", "func LocalizerBundle(tag language.Tag) *i18n.Bundle {\n\treturn i18n.NewBundle(tag)\n}", "func (mr *MockRuncClientMockRecorder) CreateBundle(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateBundle\", reflect.TypeOf((*MockRuncClient)(nil).CreateBundle), arg0, arg1, arg2)\n}", "func (f *CreateBundleReply) Deserialize(buffer []byte, err *error) []byte {\n\tif *err != nil {\n\t\treturn nil\n\t}\n\tif len(buffer) != 4 {\n\t\t*err = errDeserialize\n\t\treturn nil\n\t}\n\treturn buffer\n}", "func Bundle(box *packr.Box, output string, language string, fn string, deps ...string) error {\n\tif err := Restore(box, output); err != nil {\n\t\treturn err\n\t}\n\n\tif err := utils.Merge(output, deps...); err != nil {\n\t\treturn err\n\t}\n\n\t// Replace the default handler source file with given function source file\n\tif err := filepath.Walk(output, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif IsHandler(path, language) {\n\t\t\tif err := utils.CopyFile(fn, path); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o IosAppOutput) BundleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IosApp) pulumi.StringOutput { return v.BundleId }).(pulumi.StringOutput)\n}", "func (s *PricingPlan) SetBundleInformation(v *BundleInformation) *PricingPlan {\n\ts.BundleInformation = v\n\treturn s\n}", "func StartCreateFedBundleCall(m telemetry.Metrics) *telemetry.CallCounter {\n\treturn telemetry.StartCall(m, telemetry.RegistrationAPI, telemetry.FederatedBundle, telemetry.Create)\n}", "func (o *VersionedControllerService) SetBundle(v Bundle) {\n\to.Bundle = &v\n}", "func CreateTrustedBundle(certificates ...CertificateInterface) TrustedBundle {\n\tbundle := &trustedBundle{\n\t\tcertificates: make(map[string]CertificateInterface),\n\t}\n\tbundle.AddCertificates(certificates...)\n\treturn bundle\n}", "func (*Bundle) Descriptor() ([]byte, []int) {\n\treturn file_spire_api_registration_registration_proto_rawDescGZIP(), []int{12}\n}", "func createBundleID(projectName string) string {\n\treturn \"com.elko.\" + projectName\n}", "func (o *VersionedControllerService) GetBundle() Bundle {\n\tif o == nil || o.Bundle == nil {\n\t\tvar ret Bundle\n\t\treturn ret\n\t}\n\treturn *o.Bundle\n}", "func (t *MedChain) addHospitalToPatient(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\t\t// ==== Input sanitation ====\n\t\tfmt.Println(\"- start addHospitalToPatient\")\n\n\t\t// check if all the args are send\n\t\tif len(args) != 4 {\n\t\t\tfmt.Println(\"Incorrect number of arguments, Required 4 arguments\")\n\t\t\treturn shim.Error(\"Incorrect number of arguments, Required 4 arguments\")\n\t\t}\n\n\t\t// check if the args are empty\n\t\tfor i := 0; i < len(args); i++ {\n\t\t\tif len(args[i]) <= 0 {\n\t\t\t\tfmt.Println(\"argument \"+ string(i+1) + \" must be a non-empty string\")\n\t\t\t\treturn shim.Error(\"argument \"+ string(i+1) + \" must be a non-empty string\")\n\t\t\t}\n\t\t}\n\n\t\t// get timestamp\n\t\ttxTimeAsPtr, errTx := t.GetTxTimestampChannel(stub)\n\t\tif errTx != nil {\n\t\t\treturn shim.Error(\"Returning time error\")\n\t\t}\n\n\t\t// create the object\n\t\tvar obj = HospitalToPatient{}\n\n\t\tobj.HospitalToPatient_ID = ComputeHashKey(args[0]+(txTimeAsPtr.String()))\n\t\tobj.PatientID = args[0]\n\t\tobj.PatientName = args[1]\n\t\tobj.HospitalID = args[2]\n\t\tobj.HospitalName = args[3]\n\t\tobj.AssetType = \"HospitalToPatient\"\n\n\t\t// convert to bytes\n\t\tassetAsBytes, errMarshal := json.Marshal(obj)\n\t\t\n\t\t// show error if failed\n\t\tif errMarshal != nil {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Marshal Error: %s\", errMarshal))\n\t\t}\n\n\t\t// save data in blockchain\n\t\terrPut := stub.PutState(obj.HospitalToPatient_ID, assetAsBytes)\n\n\t\tif errPut != nil {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Failed to save file data : %s\", obj.HospitalToPatient_ID))\n\t\t}\n\n\t\tfmt.Println(\"Success in saving file data %v\", obj)\n\n\n\t\treturn shim.Success(assetAsBytes)\n\t}", "func (b *Bundler) Bundle(certs []*x509.Certificate, key crypto.Signer, flavor BundleFlavor) (*Bundle, error) {\n\tlog.Infof(\"bundling certificate for %+v\", certs[0].Subject)\n\tif len(certs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Detect reverse ordering of the cert chain.\n\tif len(certs) > 1 && !partialVerify(certs) {\n\t\trcerts := reverse(certs)\n\t\tif partialVerify(rcerts) {\n\t\t\tcerts = rcerts\n\t\t}\n\t}\n\n\tvar ok bool\n\tcert := certs[0]\n\tif key != nil {\n\t\tswitch {\n\t\tcase cert.PublicKeyAlgorithm == x509.RSA:\n\t\t\tvar rsaPublicKey *rsa.PublicKey\n\t\t\tif rsaPublicKey, ok = key.Public().(*rsa.PublicKey); !ok {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\t\tif cert.PublicKey.(*rsa.PublicKey).N.Cmp(rsaPublicKey.N) != 0 {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\tcase cert.PublicKeyAlgorithm == x509.ECDSA:\n\t\t\tvar ecdsaPublicKey *ecdsa.PublicKey\n\t\t\tif ecdsaPublicKey, ok = key.Public().(*ecdsa.PublicKey); !ok {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\t\tif cert.PublicKey.(*ecdsa.PublicKey).X.Cmp(ecdsaPublicKey.X) != 0 {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\tcase cert.PublicKeyAlgorithm == x509.Ed25519:\n\t\t\tvar ed25519PublicKey ed25519.PublicKey\n\t\t\tif ed25519PublicKey, ok = key.Public().(ed25519.PublicKey); !ok {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\t\tif !(bytes.Equal(cert.PublicKey.(ed25519.PublicKey), ed25519PublicKey)) {\n\t\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.KeyMismatch)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.NotRSAOrECCOrEd25519)\n\t\t}\n\t} else {\n\t\tswitch {\n\t\tcase cert.PublicKeyAlgorithm == x509.RSA:\n\t\tcase cert.PublicKeyAlgorithm == x509.ECDSA:\n\t\tcase cert.PublicKeyAlgorithm == x509.Ed25519:\n\t\tdefault:\n\t\t\treturn nil, errors.New(errors.PrivateKeyError, errors.NotRSAOrECCOrEd25519)\n\t\t}\n\t}\n\n\tbundle := new(Bundle)\n\tbundle.Cert = cert\n\tbundle.Key = key\n\tbundle.Issuer = &cert.Issuer\n\tbundle.Subject = &cert.Subject\n\n\tbundle.buildHostnames()\n\n\tif flavor == Force {\n\t\t// force bundle checks the certificates\n\t\t// forms a verification chain.\n\t\tif !partialVerify(certs) {\n\t\t\treturn nil,\n\t\t\t\terrors.Wrap(errors.CertificateError, errors.VerifyFailed,\n\t\t\t\t\tgoerr.New(\"Unable to verify the certificate chain\"))\n\t\t}\n\t\tbundle.Chain = certs\n\t} else {\n\t\t// disallow self-signed cert\n\t\tif cert.CheckSignatureFrom(cert) == nil {\n\t\t\treturn nil, errors.New(errors.CertificateError, errors.SelfSigned)\n\t\t}\n\n\t\tchains, err := cert.Verify(b.VerifyOptions())\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"verification failed: %v\", err)\n\t\t\t// If the error was an unknown authority, try to fetch\n\t\t\t// the intermediate specified in the AIA and add it to\n\t\t\t// the intermediates bundle.\n\t\t\tif _, ok := err.(x509.UnknownAuthorityError); !ok {\n\t\t\t\treturn nil, errors.Wrap(errors.CertificateError, errors.VerifyFailed, err)\n\t\t\t}\n\n\t\t\tlog.Debugf(\"searching for intermediates via AIA issuer\")\n\t\t\tsearchErr := b.fetchIntermediates(certs)\n\t\t\tif searchErr != nil {\n\t\t\t\tlog.Debugf(\"search failed: %v\", searchErr)\n\t\t\t\treturn nil, errors.Wrap(errors.CertificateError, errors.VerifyFailed, err)\n\t\t\t}\n\n\t\t\tlog.Debugf(\"verifying new chain\")\n\t\t\tchains, err = cert.Verify(b.VerifyOptions())\n\t\t\tif err != nil {\n\t\t\t\tlog.Debugf(\"failed to verify chain: %v\", err)\n\t\t\t\treturn nil, errors.Wrap(errors.CertificateError, errors.VerifyFailed, err)\n\t\t\t}\n\t\t\tlog.Debugf(\"verify ok\")\n\t\t}\n\t\tvar matchingChains [][]*x509.Certificate\n\t\tswitch flavor {\n\t\tcase Optimal:\n\t\t\tmatchingChains = optimalChains(chains)\n\t\tcase Ubiquitous:\n\t\t\tif len(ubiquity.Platforms) == 0 {\n\t\t\t\tlog.Warning(\"No metadata, Ubiquitous falls back to Optimal.\")\n\t\t\t}\n\t\t\tmatchingChains = ubiquitousChains(chains)\n\t\tdefault:\n\t\t\tmatchingChains = ubiquitousChains(chains)\n\t\t}\n\n\t\tbundle.Chain = matchingChains[0]\n\t}\n\n\tstatusCode := int(errors.Success)\n\tvar messages []string\n\t// Check if bundle is expiring.\n\texpiringCerts := checkExpiringCerts(bundle.Chain)\n\tif len(expiringCerts) > 0 {\n\t\tstatusCode |= errors.BundleExpiringBit\n\t\tmessages = append(messages, expirationWarning(expiringCerts))\n\t}\n\t// Check if bundle contains SHA2 certs.\n\tif ubiquity.ChainHashUbiquity(bundle.Chain) <= ubiquity.SHA2Ubiquity {\n\t\tstatusCode |= errors.BundleNotUbiquitousBit\n\t\tmessages = append(messages, sha2Warning)\n\t}\n\t// Check if bundle contains ECDSA signatures.\n\tif ubiquity.ChainKeyAlgoUbiquity(bundle.Chain) <= ubiquity.ECDSA256Ubiquity {\n\t\tstatusCode |= errors.BundleNotUbiquitousBit\n\t\tmessages = append(messages, ecdsaWarning)\n\t}\n\n\t// when forcing a bundle, bundle ubiquity doesn't matter\n\t// also we don't retrieve the anchoring root of the bundle\n\tvar untrusted []string\n\tif flavor != Force {\n\t\t// Add root store presence info\n\t\troot := bundle.Chain[len(bundle.Chain)-1]\n\t\tbundle.Root = root\n\t\tlog.Infof(\"the anchoring root is %v\", root.Subject)\n\t\t// Check if there is any platform that doesn't trust the chain.\n\t\t// Also, an warning will be generated if ubiquity.Platforms is nil,\n\t\tuntrusted = ubiquity.UntrustedPlatforms(root)\n\t\tuntrustedMsg := untrustedPlatformsWarning(untrusted)\n\t\tif len(untrustedMsg) > 0 {\n\t\t\tlog.Debug(\"Populate untrusted platform warning.\")\n\t\t\tstatusCode |= errors.BundleNotUbiquitousBit\n\t\t\tmessages = append(messages, untrustedMsg)\n\t\t}\n\t}\n\n\t// Check if there is any platform that rejects the chain because of SHA1 deprecation.\n\tsha1Msgs := ubiquity.SHA1DeprecationMessages(bundle.Chain)\n\tif len(sha1Msgs) > 0 {\n\t\tlog.Debug(\"Populate SHA1 deprecation warning.\")\n\t\tstatusCode |= errors.BundleNotUbiquitousBit\n\t\tmessages = append(messages, sha1Msgs...)\n\t}\n\n\tbundle.Status = &BundleStatus{ExpiringSKIs: getSKIs(bundle.Chain, expiringCerts), Code: statusCode, Messages: messages, Untrusted: untrusted}\n\n\t// attempt to not to include the root certificate for optimization\n\tif flavor != Force {\n\t\t// Include at least one intermediate if the leaf has enabled OCSP and is not CA.\n\t\tif bundle.Cert.OCSPServer != nil && !bundle.Cert.IsCA && len(bundle.Chain) <= 2 {\n\t\t\t// No op. Return one intermediate if there is one.\n\t\t} else {\n\t\t\t// do not include the root.\n\t\t\tbundle.Chain = bundle.Chain[:len(bundle.Chain)-1]\n\t\t}\n\t}\n\n\tbundle.Status.IsRebundled = diff(bundle.Chain, certs)\n\tbundle.Expires = helpers.ExpiryTime(bundle.Chain)\n\tbundle.LeafExpires = bundle.Chain[0].NotAfter\n\n\tlog.Debugf(\"bundle complete\")\n\treturn bundle, nil\n}", "func generateCreationBundle(b *backend, data *dataBundle) error {\n\t// Read in names -- CN, DNS and email addresses\n\tvar cn string\n\tvar ridSerialNumber string\n\tdnsNames := []string{}\n\temailAddresses := []string{}\n\t{\n\t\tif data.csr != nil && data.role.UseCSRCommonName {\n\t\t\tcn = data.csr.Subject.CommonName\n\t\t}\n\t\tif cn == \"\" {\n\t\t\tcn = data.apiData.Get(\"common_name\").(string)\n\t\t\tif cn == \"\" && data.role.RequireCN {\n\t\t\t\treturn errutil.UserError{Err: `the common_name field is required, or must be provided in a CSR with \"use_csr_common_name\" set to true, unless \"require_cn\" is set to false`}\n\t\t\t}\n\t\t}\n\n\t\tridSerialNumber = data.apiData.Get(\"serial_number\").(string)\n\n\t\t// only take serial number from CSR if one was not supplied via API\n\t\tif ridSerialNumber == \"\" && data.csr != nil {\n\t\t\tridSerialNumber = data.csr.Subject.SerialNumber\n\t\t}\n\n\t\tif data.csr != nil && data.role.UseCSRSANs {\n\t\t\tdnsNames = data.csr.DNSNames\n\t\t\temailAddresses = data.csr.EmailAddresses\n\t\t}\n\n\t\tif cn != \"\" && !data.apiData.Get(\"exclude_cn_from_sans\").(bool) {\n\t\t\tif strings.Contains(cn, \"@\") {\n\t\t\t\t// Note: emails are not disallowed if the role's email protection\n\t\t\t\t// flag is false, because they may well be included for\n\t\t\t\t// informational purposes; it is up to the verifying party to\n\t\t\t\t// ensure that email addresses in a subject alternate name can be\n\t\t\t\t// used for the purpose for which they are presented\n\t\t\t\temailAddresses = append(emailAddresses, cn)\n\t\t\t} else {\n\t\t\t\t// Only add to dnsNames if it's actually a DNS name but convert\n\t\t\t\t// idn first\n\t\t\t\tp := idna.New(\n\t\t\t\t\tidna.StrictDomainName(true),\n\t\t\t\t\tidna.VerifyDNSLength(true),\n\t\t\t\t)\n\t\t\t\tconverted, err := p.ToASCII(cn)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errutil.UserError{Err: err.Error()}\n\t\t\t\t}\n\t\t\t\tif hostnameRegex.MatchString(converted) {\n\t\t\t\t\tdnsNames = append(dnsNames, converted)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif data.csr == nil || !data.role.UseCSRSANs {\n\t\t\tcnAltRaw, ok := data.apiData.GetOk(\"alt_names\")\n\t\t\tif ok {\n\t\t\t\tcnAlt := strutil.ParseDedupLowercaseAndSortStrings(cnAltRaw.(string), \",\")\n\t\t\t\tfor _, v := range cnAlt {\n\t\t\t\t\tif strings.Contains(v, \"@\") {\n\t\t\t\t\t\temailAddresses = append(emailAddresses, v)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Only add to dnsNames if it's actually a DNS name but\n\t\t\t\t\t\t// convert idn first\n\t\t\t\t\t\tp := idna.New(\n\t\t\t\t\t\t\tidna.StrictDomainName(true),\n\t\t\t\t\t\t\tidna.VerifyDNSLength(true),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconverted, err := p.ToASCII(v)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn errutil.UserError{Err: err.Error()}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif hostnameRegex.MatchString(converted) {\n\t\t\t\t\t\t\tdnsNames = append(dnsNames, converted)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check the CN. This ensures that the CN is checked even if it's\n\t\t// excluded from SANs.\n\t\tif cn != \"\" {\n\t\t\tbadName := validateNames(data, []string{cn})\n\t\t\tif len(badName) != 0 {\n\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\"common name %s not allowed by this role\", badName)}\n\t\t\t}\n\t\t}\n\n\t\tif ridSerialNumber != \"\" {\n\t\t\tbadName := validateSerialNumber(data, ridSerialNumber)\n\t\t\tif len(badName) != 0 {\n\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\"serial_number %s not allowed by this role\", badName)}\n\t\t\t}\n\t\t}\n\n\t\t// Check for bad email and/or DNS names\n\t\tbadName := validateNames(data, dnsNames)\n\t\tif len(badName) != 0 {\n\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\"subject alternate name %s not allowed by this role\", badName)}\n\t\t}\n\n\t\tbadName = validateNames(data, emailAddresses)\n\t\tif len(badName) != 0 {\n\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\"email address %s not allowed by this role\", badName)}\n\t\t}\n\t}\n\n\tvar otherSANs map[string][]string\n\tif sans := data.apiData.Get(\"other_sans\").([]string); len(sans) > 0 {\n\t\trequested, err := parseOtherSANs(sans)\n\t\tif err != nil {\n\t\t\treturn errutil.UserError{Err: errwrap.Wrapf(\"could not parse requested other SAN: {{err}}\", err).Error()}\n\t\t}\n\t\tbadOID, badName, err := validateOtherSANs(data, requested)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn errutil.UserError{Err: err.Error()}\n\t\tcase len(badName) > 0:\n\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\"other SAN %s not allowed for OID %s by this role\", badName, badOID)}\n\t\tcase len(badOID) > 0:\n\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\"other SAN OID %s not allowed by this role\", badOID)}\n\t\tdefault:\n\t\t\totherSANs = requested\n\t\t}\n\t}\n\n\t// Get and verify any IP SANs\n\tipAddresses := []net.IP{}\n\t{\n\t\tif data.csr != nil && data.role.UseCSRSANs {\n\t\t\tif len(data.csr.IPAddresses) > 0 {\n\t\t\t\tif !data.role.AllowIPSANs {\n\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\"IP Subject Alternative Names are not allowed in this role, but was provided some via CSR\")}\n\t\t\t\t}\n\t\t\t\tipAddresses = data.csr.IPAddresses\n\t\t\t}\n\t\t} else {\n\t\t\tipAlt := data.apiData.Get(\"ip_sans\").([]string)\n\t\t\tif len(ipAlt) > 0 {\n\t\t\t\tif !data.role.AllowIPSANs {\n\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\"IP Subject Alternative Names are not allowed in this role, but was provided %s\", ipAlt)}\n\t\t\t\t}\n\t\t\t\tfor _, v := range ipAlt {\n\t\t\t\t\tparsedIP := net.ParseIP(v)\n\t\t\t\t\tif parsedIP == nil {\n\t\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\t\"the value '%s' is not a valid IP address\", v)}\n\t\t\t\t\t}\n\t\t\t\t\tipAddresses = append(ipAddresses, parsedIP)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tURIs := []*url.URL{}\n\t{\n\t\tif data.csr != nil && data.role.UseCSRSANs {\n\t\t\tif len(data.csr.URIs) > 0 {\n\t\t\t\tif len(data.role.AllowedURISANs) == 0 {\n\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\"URI Subject Alternative Names are not allowed in this role, but were provided via CSR\"),\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// validate uri sans\n\t\t\t\tfor _, uri := range data.csr.URIs {\n\t\t\t\t\tvalid := false\n\t\t\t\t\tfor _, allowed := range data.role.AllowedURISANs {\n\t\t\t\t\t\tvalidURI := glob.Glob(allowed, uri.String())\n\t\t\t\t\t\tif validURI {\n\t\t\t\t\t\t\tvalid = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif !valid {\n\t\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\t\"URI Subject Alternative Names were provided via CSR which are not valid for this role\"),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tURIs = append(URIs, uri)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\turiAlt := data.apiData.Get(\"uri_sans\").([]string)\n\t\t\tif len(uriAlt) > 0 {\n\t\t\t\tif len(data.role.AllowedURISANs) == 0 {\n\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\"URI Subject Alternative Names are not allowed in this role, but were provided via the API\"),\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, uri := range uriAlt {\n\t\t\t\t\tvalid := false\n\t\t\t\t\tfor _, allowed := range data.role.AllowedURISANs {\n\t\t\t\t\t\tvalidURI := glob.Glob(allowed, uri)\n\t\t\t\t\t\tif validURI {\n\t\t\t\t\t\t\tvalid = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif !valid {\n\t\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\t\"URI Subject Alternative Names were provided via CSR which are not valid for this role\"),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tparsedURI, err := url.Parse(uri)\n\t\t\t\t\tif parsedURI == nil || err != nil {\n\t\t\t\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\t\t\t\"the provided URI Subject Alternative Name '%s' is not a valid URI\", uri),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tURIs = append(URIs, parsedURI)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsubject := pkix.Name{\n\t\tCommonName: cn,\n\t\tSerialNumber: ridSerialNumber,\n\t\tCountry: strutil.RemoveDuplicates(data.role.Country, false),\n\t\tOrganization: strutil.RemoveDuplicates(data.role.Organization, false),\n\t\tOrganizationalUnit: strutil.RemoveDuplicates(data.role.OU, false),\n\t\tLocality: strutil.RemoveDuplicates(data.role.Locality, false),\n\t\tProvince: strutil.RemoveDuplicates(data.role.Province, false),\n\t\tStreetAddress: strutil.RemoveDuplicates(data.role.StreetAddress, false),\n\t\tPostalCode: strutil.RemoveDuplicates(data.role.PostalCode, false),\n\t}\n\n\t// Get the TTL and verify it against the max allowed\n\tvar ttl time.Duration\n\tvar maxTTL time.Duration\n\tvar notAfter time.Time\n\t{\n\t\tttl = time.Duration(data.apiData.Get(\"ttl\").(int)) * time.Second\n\n\t\tif ttl == 0 && data.role.TTL > 0 {\n\t\t\tttl = data.role.TTL\n\t\t}\n\n\t\tif data.role.MaxTTL > 0 {\n\t\t\tmaxTTL = data.role.MaxTTL\n\t\t}\n\n\t\tif ttl == 0 {\n\t\t\tttl = b.System().DefaultLeaseTTL()\n\t\t}\n\t\tif maxTTL == 0 {\n\t\t\tmaxTTL = b.System().MaxLeaseTTL()\n\t\t}\n\t\tif ttl > maxTTL {\n\t\t\tttl = maxTTL\n\t\t}\n\n\t\tnotAfter = time.Now().Add(ttl)\n\n\t\t// If it's not self-signed, verify that the issued certificate won't be\n\t\t// valid past the lifetime of the CA certificate\n\t\tif data.signingBundle != nil &&\n\t\t\tnotAfter.After(data.signingBundle.Certificate.NotAfter) && !data.role.AllowExpirationPastCA {\n\n\t\t\treturn errutil.UserError{Err: fmt.Sprintf(\n\t\t\t\t\"cannot satisfy request, as TTL would result in notAfter %s that is beyond the expiration of the CA certificate at %s\", notAfter.Format(time.RFC3339Nano), data.signingBundle.Certificate.NotAfter.Format(time.RFC3339Nano))}\n\t\t}\n\t}\n\n\tdata.params = &creationParameters{\n\t\tSubject: subject,\n\t\tDNSNames: dnsNames,\n\t\tEmailAddresses: emailAddresses,\n\t\tIPAddresses: ipAddresses,\n\t\tURIs: URIs,\n\t\tOtherSANs: otherSANs,\n\t\tKeyType: data.role.KeyType,\n\t\tKeyBits: data.role.KeyBits,\n\t\tNotAfter: notAfter,\n\t\tKeyUsage: x509.KeyUsage(parseKeyUsages(data.role.KeyUsage)),\n\t\tExtKeyUsage: parseExtKeyUsages(data.role),\n\t\tExtKeyUsageOIDs: data.role.ExtKeyUsageOIDs,\n\t\tPolicyIdentifiers: data.role.PolicyIdentifiers,\n\t\tBasicConstraintsValidForNonCA: data.role.BasicConstraintsValidForNonCA,\n\t\tNotBeforeDuration: data.role.NotBeforeDuration,\n\t}\n\n\t// Don't deal with URLs or max path length if it's self-signed, as these\n\t// normally come from the signing bundle\n\tif data.signingBundle == nil {\n\t\treturn nil\n\t}\n\n\t// This will have been read in from the getURLs function\n\tdata.params.URLs = data.signingBundle.URLs\n\n\t// If the max path length in the role is not nil, it was specified at\n\t// generation time with the max_path_length parameter; otherwise derive it\n\t// from the signing certificate\n\tif data.role.MaxPathLength != nil {\n\t\tdata.params.MaxPathLength = *data.role.MaxPathLength\n\t} else {\n\t\tswitch {\n\t\tcase data.signingBundle.Certificate.MaxPathLen < 0:\n\t\t\tdata.params.MaxPathLength = -1\n\t\tcase data.signingBundle.Certificate.MaxPathLen == 0 &&\n\t\t\tdata.signingBundle.Certificate.MaxPathLenZero:\n\t\t\t// The signing function will ensure that we do not issue a CA cert\n\t\t\tdata.params.MaxPathLength = 0\n\t\tdefault:\n\t\t\t// If this takes it to zero, we handle this case later if\n\t\t\t// necessary\n\t\t\tdata.params.MaxPathLength = data.signingBundle.Certificate.MaxPathLen - 1\n\t\t}\n\t}\n\n\treturn nil\n}", "func openBundle(r io.ReaderAt, size int64) (*Bundle, error) {\n\tz, err := zip.NewReader(r, size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbundle := &Bundle{files: make(map[digest.Digest][]byte)}\n\tvar manifest *zip.File\n\tfor _, file := range z.File {\n\t\tif file.Name == manifestPath {\n\t\t\tmanifest = file\n\t\t\tcontinue\n\t\t}\n\t\td, err := digest.Parse(file.Name)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"unexpected file name %s in bundle\", file.Name)\n\t\t\tcontinue\n\t\t}\n\t\tf, err := file.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbundle.files[d], err = ioutil.ReadAll(f)\n\t\t_ = f.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif manifest == nil {\n\t\treturn nil, errors.New(\"bundle is missing manifest\")\n\t}\n\tf, err := manifest.Open()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tif err := json.NewDecoder(f).Decode(&bundle.manifest); err != nil {\n\t\treturn nil, err\n\t}\n\treturn bundle, nil\n}", "func (fn *RuntimeMonitor) FinishBundle(ctx context.Context, emit func([]byte, []byte)) {\n\truntime.Update(ctx, time.Now().UnixNano())\n}", "func (s *DataStore) CreateSupportBundle(supportBundle *longhorn.SupportBundle) (*longhorn.SupportBundle, error) {\n\tret, err := s.lhClient.LonghornV1beta2().SupportBundles(s.namespace).Create(context.TODO(), supportBundle, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif SkipListerCheck {\n\t\treturn ret, nil\n\t}\n\n\tobj, err := verifyCreation(ret.Name, \"support bundle\", func(name string) (runtime.Object, error) {\n\t\treturn s.GetSupportBundleRO(name)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret, ok := obj.(*longhorn.SupportBundle)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"BUG: datastore: verifyCreation returned wrong type for support bundle\")\n\t}\n\n\treturn ret.DeepCopy(), nil\n}", "func (t DrupalType) Bundle() string {\n\t// TODO: some entities (like User) do not have a bundle type\n\treturn strings.Split(string(t), \"--\")[1]\n}", "func (g Generator) NewPatient(person *ir.Person, doctor *ir.Doctor) *state.Patient {\n\tp := &state.Patient{\n\t\tPatientInfo: &ir.PatientInfo{\n\t\t\tClass: g.messageConfig.PatientClass.Outpatient,\n\t\t\tPerson: person,\n\t\t\t// The Hospital Service might be overridden later with the doctor's specialty.\n\t\t\tHospitalService: g.messageConfig.HospitalService,\n\t\t\tAttendingDoctor: doctor,\n\t\t},\n\t\t// The code downstream assumes that Orders exists.\n\t\tOrders: make(map[string]*ir.Order),\n\t\tDocuments: make(map[string]*ir.Document),\n\t}\n\t// If none of the g.messageConfig.PrimaryFacility fields is set, we want the resulting HL7 message to have the entire\n\t// PD1.3 Patient Primary Facility field empty. This is achieved by leaving p.PatientInfo.PrimaryFacility nil.\n\tif g.messageConfig.PrimaryFacility != nil {\n\t\tp.PatientInfo.PrimaryFacility = &ir.PrimaryFacility{\n\t\t\tOrganization: g.messageConfig.PrimaryFacility.OrganizationName,\n\t\t\tID: g.messageConfig.PrimaryFacility.IDNumber,\n\t\t}\n\t}\n\tif doctor != nil {\n\t\tdocWithSpecialty := g.doctors.GetByID(doctor.ID)\n\t\tif docWithSpecialty != nil && docWithSpecialty.Specialty != \"\" {\n\t\t\tp.PatientInfo.HospitalService = docWithSpecialty.Specialty\n\t\t}\n\t}\n\treturn p\n}", "func ReadBundle(ctx context.Context, rw files.FileReaderWriter, g *GlobalOptions) (*bundle.Bundle, error) {\n\tvar bytes []byte\n\tvar err error\n\tif g.BundleFile != \"\" {\n\t\tlog.Infof(\"Reading bundle file %v\", g.BundleFile)\n\t\tbytes, err = rw.ReadFile(ctx, g.BundleFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tlog.Info(\"No component data file, reading from stdin\")\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tfor scanner.Scan() {\n\t\t\tbytes = append(bytes, scanner.Bytes()...)\n\t\t\tbytes = append(bytes, '\\n')\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tb, err := convertBundle(ctx, bytes, g)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// For now, we can only inline component data files because we need the path\n\t// context.\n\tif (g.InlineComponents || g.InlineObjects) && g.BundleFile != \"\" {\n\t\treturn inlineData(ctx, b, rw, g)\n\t}\n\treturn b, nil\n}", "func (api *API) GetPatients() (*models.PatientBundle, error) {\n\tcontents, getErr := api.getResource(\"patient\", nil)\n\tif getErr != nil {\n\t\tlog.Print(\"Error making api call for patients\")\n\t\treturn nil, getErr\n\t}\n\n\tdata := &models.PatientBundle{}\n\tif err := json.Unmarshal(contents, data); err != nil {\n\t\tlog.Print(\"Error unmarshalling patients\")\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (o *ControllerServiceAPI) GetBundleOk() (*Bundle, bool) {\n\tif o == nil || o.Bundle == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Bundle, true\n}", "func FromBundle(b *bundlev1.Bundle) (afero.Fs, error) {\n\tfsMap := map[string]*memguard.Enclave{}\n\n\t// Prepare filesystem\n\tfor _, p := range b.Packages {\n\t\tvar box *memguard.Enclave\n\n\t\t// Skip when no secret chain is defined\n\t\tif p.Secrets == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check if package has locked secret\n\t\tif p.Secrets.Locked != nil {\n\t\t\tbox = memguard.NewEnclave(p.Secrets.Locked.Value)\n\t\t\t// Clear buffer\n\t\t\tmemguard.WipeBytes(p.Secrets.Locked.Value)\n\t\t} else {\n\t\t\t// Convert secret as a map\n\t\t\tsecrets := map[string]interface{}{}\n\n\t\t\tfor _, s := range p.Secrets.Data {\n\t\t\t\tvar out interface{}\n\t\t\t\tif err := secret.Unpack(s.Value, &out); err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to load secret value, corrupted bundle\")\n\t\t\t\t}\n\n\t\t\t\t// Assign to secret map\n\t\t\t\tsecrets[s.Key] = out\n\t\t\t}\n\n\t\t\t// Check if secret is a file\n\t\t\tif value, ok := secrets[\"@content\"]; ok {\n\t\t\t\tcontent := value.([]byte)\n\n\t\t\t\t// Assign file content as value\n\t\t\t\tbox = memguard.NewEnclave(content)\n\n\t\t\t\t// Clear buffer\n\t\t\t\tmemguard.WipeBytes(content)\n\t\t\t} else {\n\t\t\t\t// Convert as json\n\t\t\t\tcontent, err := json.Marshal(secrets)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to extract secret map as json\")\n\t\t\t\t}\n\n\t\t\t\t// Lock buffer\n\t\t\t\tbox = memguard.NewEnclave(content)\n\n\t\t\t\t// Clear buffer\n\t\t\t\tmemguard.WipeBytes(content)\n\t\t\t}\n\t\t}\n\n\t\t// Add to map\n\t\tfsMap[fmt.Sprintf(\"/%s\", p.Name)] = box\n\t}\n\n\treturn &bundleFs{\n\t\tbundle: b,\n\t\tfiles: fsMap,\n\t}, nil\n}", "func (n *ParDo) FinishBundle(_ context.Context) error {\n\tif n.status != Active {\n\t\treturn errors.Errorf(\"invalid status for pardo %v: %v, want Active\", n.UID, n.status)\n\t}\n\tn.status = Up\n\tn.inv.Reset()\n\tif n.onTimerInvoker != nil {\n\t\tn.onTimerInvoker.Reset()\n\t}\n\n\tn.states.Set(n.ctx, metrics.FinishBundle)\n\n\tif _, err := n.invokeDataFn(n.ctx, typex.NoFiringPane(), window.SingleGlobalWindow, mtime.ZeroTimestamp, n.Fn.FinishBundleFn(), nil); err != nil {\n\t\treturn n.fail(err)\n\t}\n\t// Flush timers if any.\n\tif err := n.TimerTracker.FlushAndReset(n.ctx, n.timerManager); err != nil {\n\t\treturn n.fail(err)\n\t}\n\tn.reader = nil\n\tn.cache = nil\n\tn.timerManager = nil\n\n\tif err := MultiFinishBundle(n.ctx, n.Out...); err != nil {\n\t\treturn n.fail(err)\n\t}\n\treturn nil\n}", "func New(path string) (Bundle, error) {\n\tb := Bundle{}\n\tvar err error\n\tb.Type = DTRoot\n\tb.Path, err = filepath.Abs(path)\n\tif err != nil {\n\t\tlog.Printf(\"bun.New: cannot determine absolute path: %v\", err)\n\t\treturn b, err\n\t}\n\tinfos, err := ioutil.ReadDir(b.Path)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tre := regexp.MustCompile(hostRegexp)\n\tfor _, info := range infos {\n\t\tif !info.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tgroups := re.FindStringSubmatch(info.Name())\n\t\tif groups == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar host Host\n\t\thost.IP = IP(groups[1])\n\t\thost.Path = filepath.Join(b.Path, info.Name())\n\t\tswitch groups[5] {\n\t\tcase \"master\":\n\t\t\thost.Type = DTMaster\n\t\tcase \"agent\":\n\t\t\thost.Type = DTAgent\n\t\tcase \"agent_public\":\n\t\t\thost.Type = DTPublicAgent\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unknown directory type: %v\", groups[5]))\n\t\t}\n\t\tb.Hosts = append(b.Hosts, host)\n\t}\n\n\tif len(b.Hosts) == 0 {\n\t\t_, err = b.OpenFile(\"summary-report\")\n\t\tif err != nil {\n\t\t\t_, err = b.OpenFile(\"summary-errors-report\")\n\t\t\tif err != nil {\n\t\t\t\treturn b, errors.New(\"bundle not found in the given directory\")\n\t\t\t}\n\t\t}\n\t}\n\treturn b, nil\n}", "func (p *MatterpollPlugin) initBundle() (*i18n.Bundle, error) {\n\tbundle := i18n.NewBundle(language.English)\n\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\tbundlePath, err := p.API.GetBundlePath()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get bundle path\")\n\t}\n\n\ti18nDir := filepath.Join(bundlePath, \"assets\", \"i18n\")\n\tfiles, err := ioutil.ReadDir(i18nDir)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open i18n directory\")\n\t}\n\n\tfor _, file := range files {\n\t\tif !strings.HasPrefix(file.Name(), \"active.\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif file.Name() == \"active.en.json\" {\n\t\t\tcontinue\n\t\t}\n\t\t_, err = bundle.LoadMessageFile(filepath.Join(i18nDir, file.Name()))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to load message file %s\", file.Name())\n\t\t}\n\t}\n\n\treturn bundle, nil\n}", "func (s *AssessmentsServiceOp) RunBundle(ctx context.Context, bundleRequest *AssessmentBundleRequest) (*AssessmentResult, *http.Response, error) {\n\tpath := fmt.Sprintf(\"%s/bundleV2\", assessmentsBasePath)\n\n\treq, err := s.client.NewRequest(ctx, http.MethodPost, path, bundleRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := new(AssessmentResult)\n\tresp, err := s.client.Do(ctx, req, result)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn result, resp, err\n}", "func Add(db *gorm.DB, bundleID string, bookID int) {\n\tlogrus.Debug(\"add\", bundleID, bookID)\n\tif id, err := strconv.Atoi(bundleID); err == nil {\n\t\tvar bundleMaster database.BundleMaster\n\n\t\tif db.Where(database.BundleMaster{ID: uint(id)}).First(&bundleMaster).RecordNotFound() {\n\t\t\tfmt.Println(\"bundle ID does not exsit\")\n\t\t} else {\n\t\t\tbundleDetail := database.BundleDetail{BundleID: uint(id), BookID: bookID}\n\t\t\terr := db.Create(&bundleDetail).Error\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (myCISAssignments *CISAssignments) BundleID() (param *string) {\n\treturn myCISAssignments.BundleIDvar\n}", "func ConfigBundle(b *bundlr.Bundle, prototype interface{}) *bundlr.Bundle {\n\treturn b.WithFileExtension(\"parquet\").\n\t\tWithEncoderMaker(NewEncoderMaker(b).WithPrototype(prototype)).\n\t\tWithDecoderMaker(NewDecoderMaker(b).WithPrototype(prototype))\n}", "func NewManifestBundleReader(\n\tvalidate bool,\n\tbundle document.Bundle,\n\tmapper meta.RESTMapper) *ManifestBundleReader {\n\topts := manifestreader.ReaderOptions{\n\t\tMapper: mapper,\n\t\tValidate: validate,\n\t\tNamespace: metav1.NamespaceDefault,\n\t}\n\tbuffer := bytes.NewBuffer([]byte{})\n\treturn &ManifestBundleReader{\n\t\tBundle: bundle,\n\t\twriter: buffer,\n\t\tStreamReader: &manifestreader.StreamManifestReader{\n\t\t\tReaderName: \"airship\",\n\t\t\tReader: buffer,\n\t\t\tReaderOptions: opts,\n\t\t},\n\t}\n}", "func (_m *BundleBuilder) NewBundle(identifier string, inputID ias.SPInputID) (ias.Bundle, error) {\n\tret := _m.Called(identifier, inputID)\n\n\tvar r0 ias.Bundle\n\tif rf, ok := ret.Get(0).(func(string, ias.SPInputID) ias.Bundle); ok {\n\t\tr0 = rf(identifier, inputID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ias.Bundle)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, ias.SPInputID) error); ok {\n\t\tr1 = rf(identifier, inputID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (o *VersionedControllerService) GetBundleOk() (*Bundle, bool) {\n\tif o == nil || o.Bundle == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Bundle, true\n}", "func (f *CreateBundleReply) Serialize(buffer []byte) []byte {\n\tbinary.LittleEndian.PutUint32(buffer, uint32(f.Error))\n\treturn buffer\n}", "func (*Bundle) Descriptor() ([]byte, []int) {\n\treturn file_harp_bundle_v1_bundle_proto_rawDescGZIP(), []int{0}\n}", "func CreateStillBundle(mp4 string, still string) {\n\tfmt.Println(\"-- CREATE JPGS -- \", still[:len(still)-4])\n\tisolatedVideo := mp4[59 : len(mp4)-4]\n\ttrimDir := strings.SplitAfter(still[:len(still)-4], \"/edits\")\n\tremoveEditDir := trimDir[0][:len(trimDir[0])-5]\n\tnewDir := removeEditDir + \"jpg/\" + isolatedVideo\n\n\tfmt.Println(newDir)\n\n\tCreateDirectories(newDir)\n\n\tcheck := newDir + \"/\" + isolatedVideo + \"-frame-%04d.jpg\"\n\tcmd5 := exec.Command(\"ffmpeg\", \"-i\", mp4, check)\n\n\tcmd5.Run()\n}", "func (c *ClientWithResponses) CreatePatientTagWithBodyWithResponse(ctx context.Context, clinicId ClinicId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePatientTagResponse, error) {\n\trsp, err := c.CreatePatientTagWithBody(ctx, clinicId, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseCreatePatientTagResponse(rsp)\n}", "func (c *Controller) ProcessBundle(logger *zap.Logger, bundle *smith_v1.Bundle) (bool /*external*/, bool /*retriable*/, error) {\n\tst := bundleSyncTask{\n\t\tlogger: logger,\n\t\tbundleClient: c.BundleClient,\n\t\tsmartClient: c.SmartClient,\n\t\tchecker: c.Rc,\n\t\tstore: c.Store,\n\t\tspecChecker: c.SpecChecker,\n\t\tbundle: bundle,\n\t\tpluginContainers: c.PluginContainers,\n\t\tscheme: c.Scheme,\n\t\tcatalog: c.Catalog,\n\t\tbundleTransitionCounter: c.BundleTransitionCounter,\n\t\tbundleResourceTransitionCounter: c.BundleResourceTransitionCounter,\n\t\trecorder: c.Recorder,\n\t}\n\n\tvar external bool\n\tvar retriable bool\n\tvar err error\n\tif st.bundle.DeletionTimestamp != nil {\n\t\texternal, retriable, err = st.processDeleted()\n\t} else {\n\t\texternal, retriable, err = st.processNormal()\n\t}\n\tif err != nil {\n\t\tcause := errors.Cause(err)\n\t\t// short circuit on conflicts\n\t\tif api_errors.IsConflict(cause) {\n\t\t\treturn external, retriable, err\n\t\t}\n\t\t// proceed to handleProcessResult() for all other errors\n\t}\n\n\t// Updates bundle status\n\thandleProcessRetriable, handleProcessErr := st.handleProcessResult(retriable, err)\n\n\t// Inspect the resources for failures. They can fail for many different reasons.\n\t// The priority of errors to bubble up to the ctrl layer are:\n\t// 1. processDeleted/processNormal errors\n\t// 2. Internal resource processing errors are raised first\n\t// 3. External resource processing errors are raised last\n\t// 4. handleProcessResult errors of any sort.\n\n\t// Handle the errors from processDeleted/processNormal, taking precedence\n\t// over the handleProcessErr if any.\n\tif err != nil {\n\t\tif handleProcessErr != nil {\n\t\t\tst.logger.Error(\"Error processing Bundle\", zap.Error(handleProcessErr))\n\t\t}\n\n\t\treturn external, retriable || handleProcessRetriable, err\n\t}\n\n\t// Inspect resources, returning an error if necessary\n\tallExternalErrors := true\n\thasRetriableResourceErr := false\n\tvar failedResources []string\n\tfor resName, resInfo := range st.processedResources {\n\t\tresErr := resInfo.fetchError()\n\n\t\tif resErr != nil {\n\t\t\tallExternalErrors = allExternalErrors && resErr.isExternalError\n\t\t\thasRetriableResourceErr = hasRetriableResourceErr || resErr.isRetriableError\n\t\t\tfailedResources = append(failedResources, string(resName))\n\t\t}\n\t}\n\tif len(failedResources) > 0 {\n\t\tif handleProcessErr != nil {\n\t\t\tst.logger.Error(\"Error processing Bundle\", zap.Error(handleProcessErr))\n\t\t}\n\t\t// stable output\n\t\tsort.Strings(failedResources)\n\t\terr := errors.Errorf(\"error processing resource(s): %q\", failedResources)\n\t\treturn allExternalErrors, hasRetriableResourceErr || handleProcessRetriable, err\n\t}\n\n\t// Otherwise, return the result from handleProcessResult\n\treturn false, handleProcessRetriable, handleProcessErr\n}", "func (fn *RuntimeMonitor) StartBundle(ctx context.Context, emit func([]byte, []byte)) {\n\truntime.Update(ctx, time.Now().UnixNano())\n}", "func (p *SIFPacker) Pack() (*types.Bundle, error) {\n\treturn nil, fmt.Errorf(\"unsupported on this platform\")\n}", "func NewBundleProvisioner(bundlePath string) (Provisioner, error) {\n\treturn nil, unsupportedErr\n}", "func (c *Cache) StoreBundle(bundleRef cnab.BundleReference) (CachedBundle, error) {\n\tcb := CachedBundle{BundleReference: bundleRef}\n\n\tcacheDir, err := c.GetCacheDir()\n\tif err != nil {\n\t\treturn CachedBundle{}, err\n\t}\n\tcb.SetCacheDir(cacheDir)\n\n\t// Remove any previously cached bundle files\n\terr = c.FileSystem.RemoveAll(cb.cacheDir)\n\tif err != nil {\n\t\treturn CachedBundle{}, fmt.Errorf(\"cannot remove existing cache directory %s: %w\", cb.BundlePath, err)\n\t}\n\n\tcb.BundlePath = cb.BuildBundlePath()\n\terr = c.FileSystem.MkdirAll(filepath.Dir(cb.BundlePath), pkg.FileModeDirectory)\n\tif err != nil {\n\t\treturn CachedBundle{}, fmt.Errorf(\"unable to create cache directory: %w\", err)\n\t}\n\n\tf, err := c.FileSystem.OpenFile(cb.BundlePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable)\n\tif err != nil {\n\t\treturn CachedBundle{}, fmt.Errorf(\"error creating cnab/bundle.json for %s: %w\", cb.Reference, err)\n\t}\n\tdefer f.Close()\n\n\t_, err = cb.Definition.WriteTo(f)\n\tif err != nil {\n\t\treturn CachedBundle{}, fmt.Errorf(\"error writing to cnab/bundle.json for %s: %w\", cb.Reference, err)\n\t}\n\n\terr = c.cacheMetadata(&cb)\n\tif err != nil {\n\t\treturn CachedBundle{}, err\n\t}\n\n\terr = c.cacheManifest(&cb)\n\tif err != nil {\n\t\treturn CachedBundle{}, err\n\t}\n\n\t// we wrote the bundle, now lets store a relocation mapping in cnab/ and return the path\n\tif len(cb.RelocationMap) > 0 {\n\t\tcb.RelocationFilePath = cb.BuildRelocationFilePath()\n\t\tf, err = c.FileSystem.OpenFile(cb.RelocationFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable)\n\t\tif err != nil {\n\t\t\treturn CachedBundle{}, fmt.Errorf(\"error creating cnab/relocation-mapping.json for %s: %w\", cb.Reference, err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tb, err := json.Marshal(cb.RelocationMap)\n\t\tif err != nil {\n\t\t\treturn CachedBundle{}, fmt.Errorf(\"couldn't marshall relocation mapping for %s: %w\", cb.Reference, err)\n\t\t}\n\n\t\t_, err = f.Write(b)\n\t\tif err != nil {\n\t\t\treturn CachedBundle{}, fmt.Errorf(\"couldn't write relocation mapping for %s: %w\", cb.Reference, err)\n\t\t}\n\n\t}\n\n\treturn cb, nil\n}", "func NewListPatient(ctx *middleware.Context, handler ListPatientHandler) *ListPatient {\n\treturn &ListPatient{Context: ctx, Handler: handler}\n}", "func ParseBundles(rawBundles string) (*Bundles, error) {\n\tif strings.Contains(rawBundles, \"not able to capture\") {\n\t\treturn nil, errors.New(\"you aren't connected through Safaricom\")\n\t}\n\trows := strings.Split(rawBundles, \"<tr>\")\n\n\tres := map[string]string{\n\t\t\"Account Types\": \"\",\n\t\t\"Data Bundle</span>\": \"\",\n\t\t\"Data Bundle Expiry Date\": \"\",\n\t\t\"Airtime Balances\": \"\",\n\t\t\"Bonga SMS</\": \"\",\n\t\t\"Bonga Balance\": \"\",\n\t}\n\n\tfor _, val := range rows {\n\t\tif !strings.Contains(val, \"</tr>\") {\n\t\t\tcontinue\n\t\t}\n\t\tvar title string\n\t\tfor key := range res {\n\t\t\tif strings.Contains(val, key) {\n\t\t\t\ttitle = key\n\t\t\t}\n\t\t}\n\t\tif title == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Count(val, \"<td>\") < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tval2 := strings.Split(val, \"<td>\")[2]\n\t\tval2 = strings.Replace(val2, \"<td>\", \"\", 1)\n\t\tval2 = strings.Replace(val2, \"</td></tr>\", \"\", 1)\n\t\tres[title] = val2\n\t}\n\tvar ok bool\n\tfor _, val := range res {\n\t\tif val != \"\" {\n\t\t\tok = true // some data found\n\t\t\tbreak\n\t\t}\n\t}\n\tif !ok {\n\t\treturn nil, errors.New(\"Unable to get bundles\")\n\t}\n\n\tairtime, err := strconv.ParseFloat(res[\"Airtime Balances\"], 64)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to parse bundles: unable to get airtime\")\n\t}\n\treturn &Bundles{\n\t\tAccType: res[\"Account Types\"],\n\t\tBundles: res[\"Data Bundle</span>\"],\n\t\tAirtime: airtime,\n\t\tBundlesExpiry: res[\"Data Bundle Expiry Date\"],\n\t\tBongaSMS: res[\"Bonga SMS</\"],\n\t\tBongaBalance: res[\"Bonga Balance\"],\n\t}, nil\n\n}", "func CreateNewPatient(c *gin.Context) {\n\tvar patientRequest PatientRequest\n\tc.ShouldBind(&patientRequest)\n\tpatientResponse := PatientResponse{\n\t\tPatientID: \"2018-0001\",\n\t\tName: patientRequest.Name,\n\t\tLastname: patientRequest.Lastname,\n\t\tAge: patientRequest.Age,\n\t}\n\tc.JSON(201, patientResponse)\n\n}", "func NewBundles() *Bundles {\n\tthis := Bundles{}\n\treturn &this\n}", "func (n *ParDo) StartBundle(ctx context.Context, id string, data DataContext) error {\n\tif n.status != Up {\n\t\treturn errors.Errorf(\"invalid status for pardo %v: %v, want Up\", n.UID, n.status)\n\t}\n\tn.status = Active\n\tn.reader = data.State\n\tn.timerManager = data.Data\n\t// Allocating contexts all the time is expensive, but we seldom re-write them,\n\t// and never accept modified contexts from users, so we will cache them per-bundle\n\t// per-unit, to avoid the constant allocation overhead.\n\tn.ctx = metrics.SetPTransformID(ctx, n.PID)\n\n\tn.states.Set(n.ctx, metrics.StartBundle)\n\n\tif err := MultiStartBundle(n.ctx, id, data, n.Out...); err != nil {\n\t\treturn n.fail(err)\n\t}\n\n\t// TODO(BEAM-3303): what to set for StartBundle/FinishBundle window and emitter timestamp?\n\n\tif _, err := n.invokeDataFn(n.ctx, typex.NoFiringPane(), window.SingleGlobalWindow, mtime.ZeroTimestamp, n.Fn.StartBundleFn(), nil); err != nil {\n\t\treturn n.fail(err)\n\t}\n\treturn nil\n}", "func (o BucketOutput) BundleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringOutput { return v.BundleId }).(pulumi.StringOutput)\n}", "func (*CreateBundleResponse) Descriptor() ([]byte, []int) {\n\treturn file_spire_server_datastore_datastore_proto_rawDescGZIP(), []int{1}\n}", "func (b *AVRBundle) Open(trustRoots *x509.CertPool, ts time.Time) (*AttestationVerificationReport, error) {\n\treturn DecodeAVR(b.Body, b.Signature, b.CertificateChain, trustRoots, ts)\n}", "func NewBundleWriter(searchPaths []string, basePaths []string) *BundleWriter {\n\treturn &BundleWriter{\n\t\tbasePaths: basePaths,\n\t\tsearchPaths: searchPaths,\n\t}\n}", "func (t *HeathCare_Chaincode) createDrugInformation(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tfmt.Println(\"\\n=============== start createDrugInformation function ===============\")\n\tstart := time.Now()\n\ttime.Sleep(time.Second)\n\n\tif len(args) != 6 {\n\t\treturn shim.Error(\"expecting 6 argument\")\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif len(args[i]) == 0 {\n\t\t\treturn shim.Error(\"argument \" + strconv.Itoa(i+1) + \" must be declare\")\n\t\t}\n\t}\n\n\t//define argument\n\tpatientId := args[0]\n\tpatientName := args[1]\n\tdrugName := args[2]\n\texpirationDate := args[3]\n\tquantity := args[4]\n\tprescribedBy := args[5]\n\n\t//convert to json\n\tobjectType := \"DrugInformation\"\n\tdrugInformation := &DrugInformation{objectType, patientId, patientName, drugName,\n\t\texpirationDate, quantity, prescribedBy}\n\tdrugInformationAsByte, errDrugInformationAsByte := json.Marshal(drugInformation)\n\tif errDrugInformationAsByte != nil {\n\t\treturn shim.Error(errDrugInformationAsByte.Error())\n\t}\n\n\t//save to ledger\n\terrDrugInformationAsByte = stub.PutPrivateData(\"DrugInformationCollection\", patientId, drugInformationAsByte)\n\tif errDrugInformationAsByte != nil {\n\t\treturn shim.Error(errDrugInformationAsByte.Error())\n\t}\n\n\t//create and save key\n\tindexName := \"id~patient_name\"\n\tDrugInformationIndexKey, errDrugInformationIndexKey := stub.CreateCompositeKey(indexName, []string{drugInformation.ID, drugInformation.PatientName, drugInformation.DrugName, drugInformation.ExpirationDate, drugInformation.Quantity, drugInformation.ExpirationDate})\n\tif errDrugInformationIndexKey != nil {\n\t\treturn shim.Error(errDrugInformationIndexKey.Error())\n\t}\n\tvalue := []byte{0x00}\n\tstub.PutPrivateData(\"DrugInformationCollection\", DrugInformationIndexKey, value)\n\n\tend := time.Now()\n\telapsed := time.Since(start)\n\n\tfmt.Println(\"\\nfunction createDrugInformation\")\n\tfmt.Println(\"time start: \", start.String())\n\tfmt.Println(\"time end: \", end.String())\n\tfmt.Println(\"time execute: \", elapsed.String())\n\tfmt.Println(\"=============== end createDrugInformation function ===============\")\n\n\treturn shim.Success(nil)\n}", "func (m *BundleInfoBean) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (t *HeathCare_Chaincode) createMedicalRecord(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tfmt.Println(\"\\n=============== start createMedicalRecord function ===============\")\n\tstart := time.Now()\n\ttime.Sleep(time.Second)\n\n\tif len(args) != 7 {\n\t\treturn shim.Error(\"there must be 7 argument\")\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif len(args[i]) == 0 {\n\t\t\treturn shim.Error(\"argument \" + strconv.Itoa(i+1) + \" must be declare\")\n\t\t}\n\t}\n\tpatientId := args[0]\n\tpersonalIdentificationInformation := args[1]\n\tmedicalHistory := args[2]\n\tfamilyMedicalHistory := args[3]\n\tmedicationHistory := args[4]\n\ttreatmentHistory := args[5]\n\tmedicalDirectives := args[6]\n\n\t//convert variable to json\n\tobjectType := \"MedicalRecord\"\n\tmedialRecord := &MedicalRecord{objectType, patientId, personalIdentificationInformation,\n\t\tmedicalHistory, familyMedicalHistory, medicationHistory,\n\t\ttreatmentHistory, medicalDirectives}\n\n\t//convert data to byte\n\tMedicalRecordAsByte, errMedicalRecordAsByte := json.Marshal(medialRecord)\n\tif errMedicalRecordAsByte != nil {\n\t\treturn shim.Error(errMedicalRecordAsByte.Error())\n\t}\n\n\t//save to database\n\terrMedicalRecordAsByte = stub.PutPrivateData(\"MedicalRecordCollection\", patientId, MedicalRecordAsByte)\n\tif errMedicalRecordAsByte != nil {\n\t\treturn shim.Error(errMedicalRecordAsByte.Error())\n\t}\n\n\t//create index key\n\tindexName := \"id\"\n\tmedicalRecordIndexKey, errMedicalRecordIndexKey := stub.CreateCompositeKey(indexName, []string{medialRecord.ID, medialRecord.PersonalIdentificationInformation, medialRecord.MedicalHistory, medialRecord.FamilyMedicalHistory, medialRecord.MedicationHistory, medialRecord.TreatmentHistory, medialRecord.MedicalDirectives})\n\tif errMedicalRecordIndexKey != nil {\n\t\treturn shim.Error(errMedicalRecordIndexKey.Error())\n\t}\n\n\t//save index\n\tvalue := []byte{0x00}\n\tstub.PutPrivateData(\"MedicalRecordCollection\", medicalRecordIndexKey, value)\n\n\tend := time.Now()\n\telapsed := time.Since(start)\n\n\tfmt.Println(\"\\nfunction createMedicalRecord\")\n\tfmt.Printf(\"time start: %s\", start.String())\n\tfmt.Printf(\"time end: %s\", end.String())\n\tfmt.Println(\"time execute: \", elapsed.String())\n\tfmt.Println(\"=============== end createMedicalRecord function ===============\")\n\treturn shim.Success(nil)\n}", "func (r *repository) Create(ctx context.Context, item *model.BundleReference) error {\n\tif item == nil {\n\t\treturn apperrors.NewInternalError(\"item can not be empty\")\n\t}\n\n\tentity := r.conv.ToEntity(*item)\n\n\treturn r.creator.Create(ctx, entity)\n}", "func List(db *gorm.DB, bookName string, bundleName string) {\n\tlogrus.Debug(\"List\", bookName, bundleName)\n\tsql := `select m.id as ID\n\t\t,m.bundle_name as BundleName \n\t\t,m.note as Note\n\t\t,p.id as ProductID \n\t\t,p.product_category as ProductCategory\n\t\t,p.product_name as ProductName\n\t\tfrom bundle_masters m\n\t\tleft join bundle_details d on m.id = d.bundle_id\n\t\tleft join products p on d.book_id = p.id\n\t\twhere 1=1`\n\tif bookName != \"\" {\n\t\tsql = sql + \" and product_name like '%\" + bookName + \"%'\"\n\t}\n\tif bundleName != \"\" {\n\t\tsql = sql + \" and bundle_name like '%\" + bundleName + \"%'\"\n\t}\n\tsql = sql + \" order by m.id, p.id\"\n\tlogrus.Debug(sql)\n\n\trows, err := db.Raw(sql).Rows()\n\tdefer rows.Close()\n\n\tif err == nil {\n\t\tvar id string\n\t\tfor rows.Next() {\n\t\t\tvar (\n\t\t\t\tID string\n\t\t\t\tBundleName string\n\t\t\t\tNote string\n\t\t\t\tProductID string\n\t\t\t\tProductCategory string\n\t\t\t\tProductName string\n\t\t\t)\n\t\t\trows.Scan(&ID, &BundleName, &Note, &ProductID, &ProductCategory, &ProductName)\n\t\t\tif id != ID {\n\t\t\t\tid = ID\n\t\t\t\tfmt.Println(\"\\n---------------------------------------------------------------------\")\n\t\t\t\tfmt.Printf(\"Bundle ID: %-6s Bundle Name: %-20s Note: %s\\n\", ID, BundleName, Note)\n\t\t\t\tfmt.Printf(\"Product ID | Product Category | ProductName\\n\")\n\n\t\t\t}\n\t\t\tfmt.Printf(\"%10s | %-16s | %-40s\\n\", ProductID, ProductCategory, ProductName)\n\t\t}\n\t} else {\n\t\tlogrus.Error(err)\n\t}\n}", "func (c *ClientWithResponses) BundleIdsCreateInstanceWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BundleIdsCreateInstanceResponse, error) {\n\trsp, err := c.BundleIdsCreateInstanceWithBody(ctx, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBundleIdsCreateInstanceResponse(rsp)\n}", "func (s DescribeBundleOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Details != nil {\n\t\tv := s.Details\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"details\", v, metadata)\n\t}\n\treturn nil\n}", "func (c *AllergyIntoleranceController) Read(ctx *app.ReadAllergyIntoleranceContext) error {\n\t//var sqlParams []interface{}\n\tx := json.RawMessage{}\n\n\tabsPath, _ := filepath.Abs(\"bundle.json\")\n\tfmt.Println(absPath)\n\tfile, err := os.Open(absPath)\n\tif err == nil {\n\t\t_ = json.NewDecoder(file).Decode(&x)\n\t}\n\tfile.Close()\n\n\t//getJson(\"http://nprogram.azurewebsites.net/Patient/1?_format=json\", patient)\n\t//getJson(\"http://localhost:3001\", patient)\n\t// //getJson(\"https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient/Tbt3KuCY0B5PSrJvCu2j-PlK.aiHsu2xUjUM8bWpetXoB\", patient)\n\t//_, err = json.NewDecoder(file).Decode(patient)\n\t//, err := cc.Get(\"http://fhirtest.uhn.ca/baseDstu2/Patient/EXexample\")\n\t//r, err := cc.Get(\"http://nprogram.azurewebsites.net/Patient/1?_format=json\")\n\n\t// if err != nil {\n\t// \tfmt.Println(\"A timeout error occured\")\n\t// \tos.Exit(3)\n\t// }\n\t// defer r.Body.Close()\n\n\t// body, _ := ioutil.ReadAll(r.Body)\n\n\t// isJSON := IsJSON(string(body))\n\t// if isJSON == true {\n\t// \tfmt.Println(\"Yesssssssssssssssssssssssssssssssssssssssssssssssss\")\n\t// \t_ = json.Unmarshal(body, &x)\n\t// } else {\n\t// \tfmt.Println(\"NOoooooooooooooooooooooooooooooooooooooooooooo\")\n\t// \t_ = xml.Unmarshal(body, &x)\n\t// }\n\n\t//err = json.Unmarshal([]byte(r), &f)\n\n\t// //b, _ := json.Marshal(body)\n\t// return json.Unmarshal(body, &target)\n\t//fmt.Printf(\"%s\", x)\n\n\tfmt.Println()\n\t//main_rt := gjson.Get(string(x), \"resourceType\")\n\t//sub_rt := gjson.Get(string(x), \"entry.#.resource.resourceType\")\n\t// m, ok := gjson.Parse(string(x)).Value().(map[string]interface{})\n\t// if !ok {\n\t// \t// not a map\n\t// }\n\n\t//value1 := gjson.Get(string(x), \"*\")\n\t//value2 := gjson.Get(string(x), \"entry.#.resource.code.coding.#.display\")\n\t//value2 := gjson.Get(string(x), \"entry.#.resource.component.#.valueQuantity.value\")\n\t//value2 := gjson.Get(string(x), \"entry.#.resource.component.#.code.coding.#.display\")\n\n\t//value3 := gjson.Get(string(x), \"identifier\")\n\t//fmt.Println(\"value *:\", value1.String())\n\n\t//fmt.Println(\"resource:\", value11.String())\n\t//fmt.Println(\"entry:\", value2.String())\n\t//fmt.Println(\"value:\", value3.String())\n\t//result := gjson.Get(string(x), \"entry.#.resource\")\n\n\t// //results := gjson.GetMany(string(x), \"entry.#.resource.code.coding.#.display\", \"entry.#.resource.component.#.code.coding.#.display\", \"entry.#.resource.component.#.valueQuantity.Value\")\n\t// results := gjson.GetMany(string(x), \"entry.#.resource.component.#.code.coding.#.display\", \"entry.#.resource.component.#.valueQuantity.value\")\n\n\t//_ = json.Unmarshal(x, &patient)\n\t//_, _ = json.Marshal(string(x))\n\n\t//_ = json.NewDecoder(r.Body).Decode(&x)\n\t//fmt.Println(results)\n\t//fmt.Printf(\"Indentifer:\", x.Matches[0].Ad, \"\\n\")\n\t//fmt.Println(\"Address:\", x.Address)\n\t//fmt.Println(\"Telecom:\", x.Telecom)\n\t//fmt.Println(\"CareProvider:\", x.CareProvider)\n\t//fmt.Println(\"Name:\", x.Name)\n\t//fmt.Printf(\"Contact:\", x.Contact)\n\n\t//fmt.Println(\"x is equal to:\", x.Address[0].Text)\n\n\t// res := &app.Patient{}\n\t// res.Active = patient.Active\n\t// res.BirthDate = patient.BirthDate\n\t// res.Gender = patient.Gender\n\t// //res.Telecom = patient.Telecom\n\t//res.Address=patient.Address\n\t//res.Address=\n\n\t//json.Marshal(patient)\n\n\t// \ttype int64array []int64\n\n\t// func (a int64array) Value() (driver.Value, error) {\n\t// // Format a in PostgreSQL's array input format {1,2,3} and return it as as string or []byte.\n\t// }\n\t//_, _ = json.Marshal(x)\n\n\t//g, _ := json.Marshal(x)\n\t//fmt.Println(string(g))\n\t// _, err = stmt.Exec(uuid.NewV4().String(), string(g))\n\t// if err != nil {\n\t// \tfmt.Println(err.Error())\n\t// \tfmt.Println(\"Error with db\")\n\t// }\n\n\t//json.Marshal(x)\n\n\t// t := app.Observation{}\n\t// s := reflect.ValueOf(&t).Elem()\n\t// typeOfT := s.Type()\n\n\t// for i := 0; i < s.NumField(); i++ {\n\t// \t//f := s.Field(i)\n\t// \t//fmt.Printf(\"%d: %s %s = %v\\n\", i,\n\t// \t//typeOfT.Field(i).Name, f.Type(), f.Interface())\n\t// \t//test2 := fmt.Sprintf(\"%T\", s.Field(i))\n\t// \ttest2 := fmt.Sprintf(\"%T\", s.Field(i))\n\n\t// \tfmt.Println(reflect.TypeOf(test2).Kind())\n\t// \t//fmt.Println(*test2)\n\n\t// \ttest := fmt.Sprintf(\"%s\", strings.ToLower(typeOfT.Field(i).Name))\n\t// \tfmt.Println(test)\n\n\t// \tvalue := gjson.Get(string(x), test)\n\t// \tfmt.Println()\n\t// \tfmt.Println(\"value *:\", value.String())\n\n\t// }\n\n\t//res := &app.AllergyIntoleranceMedia{}\n\treturn nil\n\t//return ctx.OK(res)\n\n}", "func (b *Bundler) BundleFromPEMorDER(certsRaw, keyPEM []byte, flavor BundleFlavor, password string) (*Bundle, error) {\n\tlog.Debug(\"bundling from PEM files\")\n\tvar key crypto.Signer\n\tvar err error\n\tif len(keyPEM) != 0 {\n\t\tkey, err = helpers.ParsePrivateKeyPEM(keyPEM)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"failed to parse private key: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcerts, err := helpers.ParseCertificatesPEM(certsRaw)\n\tif err != nil {\n\t\t// If PEM doesn't work try DER\n\t\tvar keyDER crypto.Signer\n\t\tvar errDER error\n\t\tcerts, keyDER, errDER = helpers.ParseCertificatesDER(certsRaw, password)\n\t\t// Only use DER key if no key read from file\n\t\tif key == nil && keyDER != nil {\n\t\t\tkey = keyDER\n\t\t}\n\t\tif errDER != nil {\n\t\t\tlog.Debugf(\"failed to parse certificates: %v\", err)\n\t\t\t// If neither parser works pass along PEM error\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\tif len(certs) == 0 {\n\t\tlog.Debugf(\"no certificates found\")\n\t\treturn nil, errors.New(errors.CertificateError, errors.DecodeFailed)\n\t}\n\n\tlog.Debugf(\"bundle ready\")\n\treturn b.Bundle(certs, key, flavor)\n}", "func NewAppByBundleID(bundleID string, country string) (*App, error) {\n\tentry, err := Lookup().BundleID(bundleID).Country(country).App().Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewDetailedApp(entry, country), nil\n}", "func bundleData(bundle *plugintypes.Bundle) []byte {\n\tbundleData := new(bytes.Buffer)\n\tfor _, x509Authority := range bundle.X509Authorities {\n\t\t// no need to check the error since we're encoding into a memory buffer\n\t\t_ = pem.Encode(bundleData, &pem.Block{\n\t\t\tType: \"CERTIFICATE\",\n\t\t\tBytes: x509Authority.Asn1,\n\t\t})\n\t}\n\treturn bundleData.Bytes()\n}", "func (api *API) FindPatient(firstName string, lastName string, birthDate string) (*models.PatientResource, error) {\n\tqueryParams := make(map[string]string)\n\tqueryParams[\"family\"] = lastName\n\tqueryParams[\"given\"] = firstName\n\tqueryParams[\"birthDate\"] = birthDate\n\tcontents, getErr := api.getResource(\"patient\", queryParams)\n\tif getErr != nil {\n\t\tlog.Print(\"Error making api call to find patients\")\n\t\treturn nil, getErr\n\t}\n\n\tdata := &models.PatientBundle{}\n\tif err := json.Unmarshal(contents, data); err != nil {\n\t\tlog.Print(\"Error unmarshalling patients\")\n\t\treturn nil, err\n\t}\n\n\tif len(data.Entry) != 1 {\n\t\treturn nil, nil\n\t}\n\n\treturn &data.Entry[0].Resource, nil\n}", "func createVendorSpec(b *troubleshootv1beta2.SupportBundle) (*troubleshootv1beta2.SupportBundle, error) {\n\tsupportBundle, err := staticspecs.GetVendorSpec()\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to load vendor support bundle spec: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tif b.Spec.Collectors != nil {\n\t\tsupportBundle.Spec.Collectors = b.DeepCopy().Spec.Collectors\n\t}\n\tif b.Spec.Analyzers != nil {\n\t\tsupportBundle.Spec.Analyzers = b.DeepCopy().Spec.Analyzers\n\t}\n\treturn supportBundle, nil\n}", "func (s DescribeBundleInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BundleId != nil {\n\t\tv := *s.BundleId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"bundleId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (meta *BundleMetaData) BuildBundleImage(tag string) error {\n\n\timg := fmt.Sprintf(\"%s:%s\", meta.BaseImage, tag)\n\n\t// switch back to current working directory, so that subsequent\n\t// bundle version images can be built.\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif err := os.Chdir(cwd); err != nil {\n\t\t\tlog.Error(cwd)\n\t\t}\n\t}()\n\n\tif err := os.Chdir(filepath.Dir(meta.BundleDir)); err != nil {\n\t\treturn err\n\t}\n\n\tif len(meta.BuildCommand) != 0 {\n\t\t// TODO(varsha): Make this more user friendly by accepting a template which\n\t\t// can executed in each bundle subdirectory.\n\t\tlog.Infof(\"Using the specified command to build image\")\n\t\tcommandArg := strings.Split(meta.BuildCommand, \" \")\n\n\t\t// append the tag and build context to the command\n\t\tcmd := exec.Command(commandArg[0], append(commandArg[1:], img)...)\n\t\toutput, err := cmd.CombinedOutput()\n\t\tif err != nil || viper.GetBool(flags.VerboseOpt) {\n\t\t\tfmt.Println(string(output))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\toutput, err := exec.Command(\"docker\", \"build\", \"-f\", \"bundle.Dockerfile\", \"-t\", img, \".\").CombinedOutput()\n\t\tif err != nil || viper.GetBool(flags.VerboseOpt) {\n\t\t\tfmt.Println(string(output))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Infof(\"Successfully built image %s\", img)\n\treturn nil\n}", "func (m *MockRuncClient) CreateBundle(arg0 string, arg1 specs.Spec, arg2 specs.User) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateBundle\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func SetBundleInfo(yamlFilePath string) error {\n\tbundlesYaml, err := ioutil.ReadFile(yamlFilePath)\n\n\tif err != nil {\n\t\tsentry.CaptureException(err)\n\t\treturn err\n\t}\n\n\terr = yaml.Unmarshal([]byte(bundlesYaml), &bundleInfo)\n\tif err != nil {\n\t\tsentry.CaptureException(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}" ]
[ "0.58812463", "0.58354795", "0.58354795", "0.58257055", "0.57195896", "0.5603973", "0.5585345", "0.54169726", "0.5294175", "0.5292896", "0.49810573", "0.4955971", "0.49389362", "0.4921678", "0.4910256", "0.490386", "0.4901498", "0.4840695", "0.4840695", "0.4828141", "0.4810775", "0.4796767", "0.47365382", "0.47280174", "0.4717287", "0.47143584", "0.47019613", "0.46861818", "0.4598132", "0.45618296", "0.45613578", "0.45438728", "0.45309135", "0.45288262", "0.4525684", "0.44940677", "0.44899237", "0.44893712", "0.44870064", "0.4482491", "0.44564453", "0.44401577", "0.4434102", "0.44279402", "0.44249704", "0.44174647", "0.44141775", "0.4395315", "0.43760023", "0.43598357", "0.43487614", "0.43462557", "0.43462196", "0.43212426", "0.43124905", "0.43115553", "0.42974225", "0.4285255", "0.42801195", "0.42668936", "0.426371", "0.42630687", "0.422434", "0.4210525", "0.4207096", "0.42063585", "0.42036635", "0.42017028", "0.41944677", "0.41874552", "0.4173865", "0.41690984", "0.41674823", "0.41575754", "0.41517594", "0.4146534", "0.41351858", "0.41302025", "0.41258064", "0.4117916", "0.41159156", "0.41114023", "0.41016844", "0.40865526", "0.40761828", "0.40718308", "0.40511134", "0.404009", "0.40363348", "0.40353078", "0.40244022", "0.4019455", "0.40140134", "0.40047678", "0.39960882", "0.39956358", "0.39947188", "0.39925146", "0.3990152", "0.39900708" ]
0.7705309
0
encounterDiagnosis constructs the `Encounter.Diagnosis` field. `ref` must be a reference to either a condition or procedure. Reference:
func encounterDiagnosis(ref *dpb.Reference) *encounterpb.Encounter_Diagnosis { return &encounterpb.Encounter_Diagnosis{ Condition: ref, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Framework) NewDiagnosis(name, ns, nodeName, operationSet string) *diagnosisv1.Diagnosis {\n\n\treturn &diagnosisv1.Diagnosis{\n\t\tTypeMeta: metav1.TypeMeta{},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v-%v\", name, RandomSuffix()),\n\t\t\tNamespace: ns,\n\t\t\tLabels: map[string]string{\n\t\t\t\tf.SelectorKey: name,\n\t\t\t},\n\t\t},\n\t\tSpec: diagnosisv1.DiagnosisSpec{NodeName: nodeName, OperationSet: operationSet},\n\t\tStatus: diagnosisv1.DiagnosisStatus{},\n\t}\n}", "func (a *ClinicalMetadataServiceApiService) GetDiagnosis(ctx _context.Context, diagnosisId string) (Ga4ghDiagnosis, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Ga4ghDiagnosis\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/diagnoses/{diagnosis_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"diagnosis_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", diagnosisId)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v Ga4ghDiagnosis\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (d *Diagnosis) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Diagnosis(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", d.ID))\n\tbuilder.WriteString(\", DiagnosticMessages=\")\n\tbuilder.WriteString(d.DiagnosticMessages)\n\tbuilder.WriteString(\", SurveillancePeriod=\")\n\tbuilder.WriteString(d.SurveillancePeriod)\n\tbuilder.WriteString(\", DiagnosisDate=\")\n\tbuilder.WriteString(d.DiagnosisDate)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (m *DiseaseMutation) SetDiagnosisID(id int) {\n\tm.diagnosis = &id\n}", "func withDiagnosis(node *Diagnosis) diagnosisOption {\n\treturn func(m *DiagnosisMutation) {\n\t\tm.oldValue = func(context.Context) (*Diagnosis, error) {\n\t\t\treturn node, nil\n\t\t}\n\t\tm.id = &node.ID\n\t}\n}", "func (*PatientDiagnosis) Descriptor() ([]byte, []int) {\n\treturn file_heyrenee_v1_messages_patient_diagnosis_proto_rawDescGZIP(), []int{0}\n}", "func withDiagnosisID(id int) diagnosisOption {\n\treturn func(m *DiagnosisMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Diagnosis\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Diagnosis, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Diagnosis.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func (*Diagnosis) Descriptor() ([]byte, []int) {\n\treturn file_heyrenee_v1_messages_diagnosis_proto_rawDescGZIP(), []int{0}\n}", "func (m *DiagnosisMutation) SetDiagnosisDate(s string) {\n\tm._DiagnosisDate = &s\n}", "func (duo *DiagnosisUpdateOne) SetDiagnosisDate(t time.Time) *DiagnosisUpdateOne {\n\tduo.mutation.SetDiagnosisDate(t)\n\treturn duo\n}", "func (m *DiagnosisMutation) DiagnosisDate() (r string, exists bool) {\n\tv := m._DiagnosisDate\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (s *BasePlSqlParserListener) EnterInline_ref_constraint(ctx *Inline_ref_constraintContext) {}", "func (du *DiagnosisUpdate) SetDiagnosisDate(t time.Time) *DiagnosisUpdate {\n\tdu.mutation.SetDiagnosisDate(t)\n\treturn du\n}", "func (Diagnosis) Edges() []ent.Edge {\n\treturn []ent.Edge{\n\n\t\tedge.From(\"Doctor_name\", Doctor.Type).\n\t\t\tRef(\"DoctorToDiagnosis\").\n\t\t\tUnique(),\n\t\tedge.From(\"Patient\", Patient.Type).\n\t\t\tRef(\"PatientToDiagnosis\").\n\t\t\tUnique(),\n\t\tedge.From(\"type\", TreatmentType.Type).\n\t\t\tRef(\"TreatmentTypeToDiagnosis\").\n\t\t\tUnique(),\n\t}\n}", "func (m *DiseaseMutation) DiagnosisID() (id int, exists bool) {\n\tif m.diagnosis != nil {\n\t\treturn *m.diagnosis, true\n\t}\n\treturn\n}", "func newDiagnosisMutation(c config, op Op, opts ...diagnosisOption) *DiagnosisMutation {\n\tm := &DiagnosisMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDiagnosis,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func (m *DiagnosisMutation) OldDiagnosisDate(ctx context.Context) (v string, err error) {\n\tif !m.op.Is(OpUpdateOne) {\n\t\treturn v, fmt.Errorf(\"OldDiagnosisDate is allowed only on UpdateOne operations\")\n\t}\n\tif m.id == nil || m.oldValue == nil {\n\t\treturn v, fmt.Errorf(\"OldDiagnosisDate requires an ID field in the mutation\")\n\t}\n\toldValue, err := m.oldValue(ctx)\n\tif err != nil {\n\t\treturn v, fmt.Errorf(\"querying old value for OldDiagnosisDate: %w\", err)\n\t}\n\treturn oldValue.DiagnosisDate, nil\n}", "func (d *Dentry) DecRef() {\n\td.impl.DecRef()\n}", "func (s *BasePlSqlParserListener) EnterOut_of_line_ref_constraint(ctx *Out_of_line_ref_constraintContext) {\n}", "func (*Diagnosis) fkValues() []interface{} {\n\treturn []interface{}{\n\t\t&sql.NullInt64{}, // employee_diagnosis\n\t\t&sql.NullInt64{}, // patient_diagnosis\n\t}\n}", "func DashboardCategoryEnumRef(s string) *DashboardCategoryEnum {\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\n\tv := DashboardCategoryEnum(s)\n\treturn &v\n}", "func mockCheckDetailAddendumC() CheckDetailAddendumC {\n\tcdAddendumC := NewCheckDetailAddendumC()\n\tcdAddendumC.RecordNumber = 1\n\tcdAddendumC.EndorsingBankRoutingNumber = \"121042882\"\n\tcdAddendumC.BOFDEndorsementBusinessDate = time.Now()\n\tcdAddendumC.EndorsingBankItemSequenceNumber = \"1 \"\n\tcdAddendumC.TruncationIndicator = \"Y\"\n\tcdAddendumC.EndorsingBankConversionIndicator = \"1\"\n\tcdAddendumC.EndorsingBankCorrectionIndicator = 0\n\tcdAddendumC.ReturnReason = \"A\"\n\tcdAddendumC.UserField = \"\"\n\tcdAddendumC.EndorsingBankIdentifier = 0\n\treturn cdAddendumC\n}", "func (m *DiseaseMutation) ClearDiagnosis() {\n\tm.cleareddiagnosis = true\n}", "func NewCmdDiagnostic(out io.Writer) *cobra.Command {\n\topts := &diagsOpts{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"diagnose\",\n\t\tShort: \"Collects diagnostics about the nodes in the cluster\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) != 0 {\n\t\t\t\treturn fmt.Errorf(\"Unexpected args: %v\", args)\n\t\t\t}\n\n\t\t\treturn doDiagnostics(out, opts)\n\t\t},\n\t}\n\n\t// PersistentFlags\n\taddPlanFileFlag(cmd.PersistentFlags(), &opts.planFilename)\n\tcmd.Flags().BoolVar(&opts.verbose, \"verbose\", false, \"enable verbose logging from the installation\")\n\tcmd.Flags().StringVarP(&opts.outputFormat, \"output\", \"o\", \"simple\", \"installation output format (options \\\"simple\\\"|\\\"raw\\\")\")\n\n\treturn cmd\n}", "func (x *PDFDaInfo) Ref() *C.pdf_da_info {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_da_info)(unsafe.Pointer(x))\n}", "func (o ExpressionWarningOutput) FieldRef() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ExpressionWarning) string { return v.FieldRef }).(pulumi.StringOutput)\n}", "func AddContenuHospitalisationToPatientRecord(patientRecord record.PatientRecord, hospitalisationPayload record.NewHostpitalisationPayloadValidator, agent entity.Agent) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\thospitalisationCollection := db.ConnectDb().Collection(\"hospitalisation\")\n\thospitalisation := &record.Hospitalisation{\n\t\tID: primitive.NewObjectID(),\n\t\tAgent: agent,\n\t\tPatientRecord: patientRecord.ID,\n\t\tMotifHospitalisation: hospitalisationPayload.MotifHospitalisation,\n\t}\n\t_, err := hospitalisationCollection.InsertOne(ctx, hospitalisation)\n\treturn err\n}", "func (m *DiseaseMutation) ResetDiagnosis() {\n\tm.diagnosis = nil\n\tm.cleareddiagnosis = false\n}", "func (d *Dentry) IncRef() {\n\td.impl.IncRef()\n}", "func (s *BasevhdlListener) EnterRecord_nature_definition(ctx *Record_nature_definitionContext) {}", "func (v *Verifier) VerifyDiagnosisCertificate(ctx context.Context, authApp *aamodel.AuthorizedApp, publish *verifyapi.Publish) (*VerifiedClaims, error) {\n\t// These get assigned during the ParseWithClaims closure.\n\tvar healthAuthorityID int64\n\tvar claims *verifyapi.VerificationClaims\n\n\t// Unpack JWT so we can determine issuer and key version.\n\ttoken, err := jwt.ParseWithClaims(publish.VerificationPayload, &verifyapi.VerificationClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\tif method, ok := token.Method.(*jwt.SigningMethodECDSA); !ok || method.Name != jwt.SigningMethodES256.Name {\n\t\t\treturn nil, fmt.Errorf(\"unsupported signing method, must be %v\", jwt.SigningMethodES256.Name)\n\t\t}\n\n\t\tvar ok bool\n\t\tkid, ok := token.Header[verifyapi.KeyIDHeader]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"missing required header field, 'kid' indicating key id\")\n\t\t}\n\n\t\tclaims, ok = token.Claims.(*verifyapi.VerificationClaims)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"does not contain expected claim set\")\n\t\t}\n\n\t\tlookup := func() (interface{}, error) {\n\t\t\t// Based on issuer, load the key versions.\n\t\t\tha, err := v.db.GetHealthAuthority(ctx, claims.Issuer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error looking up issuer: %v : %w\", claims.Issuer, err)\n\t\t\t}\n\t\t\treturn ha, nil\n\t\t}\n\t\tcacheVal, err := v.haCache.WriteThruLookup(claims.Issuer, lookup)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tha := cacheVal.(*model.HealthAuthority)\n\n\t\t// Find a key version.\n\t\tfor _, hak := range ha.Keys {\n\t\t\t// Key version matches and the key is valid based on the current time.\n\t\t\tif hak.Version == kid && hak.IsValid() {\n\t\t\t\thealthAuthorityID = ha.ID\n\t\t\t\t// Extract the public key from the PEM block.\n\t\t\t\treturn hak.PublicKey()\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"key not found: iss: %v kid: %v\", claims.Issuer, kid)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !token.Valid {\n\t\treturn nil, fmt.Errorf(\"invalid verificationPayload\")\n\t}\n\tif err := claims.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// JWT is valid and signature is valid.\n\t// This is chacked after the signature verification to prevent timing attacks.\n\tif _, ok := authApp.AllowedHealthAuthorityIDs[healthAuthorityID]; !ok {\n\t\treturn nil, fmt.Errorf(\"app %v has not authorized health authority issuer: %v\", authApp.AppPackageName, claims.Issuer)\n\t}\n\n\t// Verify our cutom claim types\n\tif err := claims.CustomClaimsValid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Verify the HMAC.\n\tjwtHMAC, err := base64util.DecodeString(claims.SignedMAC)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding HMAC from claims: %w\", err)\n\t}\n\tsecret, err := base64util.DecodeString(publish.HMACKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding HMAC secret from publish request: %w\", err)\n\t}\n\t// Allow the HMAC to be calculated without transmission risk values IFF all transmission risks are zero.\n\tvalidHMACs, err := utils.CalculateAllAllowedExposureKeyHMAC(publish.Keys, secret)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"calculating expected HMAC: %w\", err)\n\t}\n\n\tvalid := false\n\tfor _, wantHMAC := range validHMACs {\n\t\tvalid = valid || hmac.Equal(wantHMAC, jwtHMAC)\n\t}\n\tif !valid {\n\t\treturn nil, fmt.Errorf(\"HMAC mismatch, publish request does not match disgnosis verification certificate\")\n\t}\n\n\t// Everything looks good. Return the relevant verified claims.\n\treturn &VerifiedClaims{\n\t\tHealthAuthorityID: healthAuthorityID,\n\t\tReportType: claims.ReportType,\n\t\tSymptomOnsetInterval: claims.SymptomOnsetInterval,\n\t}, nil\n}", "func (l *InstrumenterLogger) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, contract *vm.Contract, depth int, err error) error {\n\treturn nil\n}", "func startDiagnosis(t *testing.T, clients *test.Clients, duration time.Duration) *stateChecker {\n\tst := &stateChecker{\n\t\tstopChan: make(chan struct{}),\n\t\tticker: time.NewTicker(duration),\n\t\twg: &sync.WaitGroup{},\n\t}\n\tst.wg.Add(1)\n\tgo func() {\n\t\tdefer st.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-st.ticker.C:\n\t\t\t\tdiagnoseMe(t, clients)\n\t\t\tcase <-st.stopChan:\n\t\t\t\tst.ticker.Stop()\n\t\t\t\tt.Log(\"Stopping diagnose-me checker.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn st\n}", "func (m *DiseaseMutation) DiagnosisCleared() bool {\n\treturn m.cleareddiagnosis\n}", "func (x *PDFDesignatedName) Ref() *C.pdf_designated_name {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_designated_name)(unsafe.Pointer(x))\n}", "func (e GetDisscusRespValidationError) Cause() error { return e.cause }", "func (ref KeyReference) refString() string {\n\treturn fmt.Sprintf(\n\t\t\"FOREIGN KEY(%s) REFERENCES %s(%s)\",\n\t\tref.Key.Name,\n\t\tref.RefTable,\n\t\tref.RefCol.Name,\n\t)\n}", "func (fieldType *AdaReferentialType) String() string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"%s=REFINT(%s,%d,%s\", fieldType.shortName, fieldType.keys[1], fieldType.refFile, fieldType.keys[0]))\n\tswitch fieldType.refDeleteAction {\n\tcase 0:\n\t\tbuffer.WriteString(\"/DX\")\n\tcase 1:\n\t\tbuffer.WriteString(\"/DC\")\n\tcase 2:\n\t\tbuffer.WriteString(\"/DN\")\n\t}\n\tswitch fieldType.refUpdateAction {\n\tcase 0:\n\t\tbuffer.WriteString(\",UX\")\n\tcase 1:\n\t\tbuffer.WriteString(\",UC\")\n\tcase 2:\n\t\tbuffer.WriteString(\",UN\")\n\t}\n\tbuffer.WriteString(\")\")\n\tbuffer.WriteString(fmt.Sprintf(\" ; %s\", fieldType.name))\n\treturn buffer.String()\n}", "func WithDiagnosisService(ds diagnosis.Service) Option {\n\treturn Option{F: func(o *internal_server.Options, di *utils.Slice) {\n\t\to.Once.OnceOrPanic()\n\t\tdi.Push(fmt.Sprintf(\"WithDiagnosisService(%+v)\", ds))\n\n\t\to.DebugService = ds\n\t}}\n}", "func (rdAddendumB *ReturnDetailAddendumB) fieldInclusion() error {\n\tif rdAddendumB.recordType == \"\" {\n\t\treturn &FieldError{FieldName: \"recordType\",\n\t\t\tValue: rdAddendumB.recordType,\n\t\t\tMsg: msgFieldInclusion + \", did you use ReturnDetailAddendumB()?\"}\n\t}\n\tif rdAddendumB.PayorBankSequenceNumberField() == \" \" {\n\t\treturn &FieldError{FieldName: \"PayorBankSequenceNumber\",\n\t\t\tValue: rdAddendumB.PayorBankSequenceNumber,\n\t\t\tMsg: msgFieldInclusion + \", did you use ReturnDetailAddendumB()?\"}\n\t}\n\n\treturn nil\n}", "func (o ExpressionWarningPatchOutput) FieldRef() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExpressionWarningPatch) *string { return v.FieldRef }).(pulumi.StringPtrOutput)\n}", "func (me TAttlistCommentsCorrectionsRefType) IsErratumIn() bool { return me.String() == \"ErratumIn\" }", "func (s *BasePlSqlParserListener) EnterReferences_clause(ctx *References_clauseContext) {}", "func mockReturnDetailAddendumC() ReturnDetailAddendumC {\n\trdAddendumC := NewReturnDetailAddendumC()\n\trdAddendumC.ImageReferenceKeyIndicator = 1\n\trdAddendumC.MicrofilmArchiveSequenceNumber = \"1A\"\n\trdAddendumC.LengthImageReferenceKey = \"0034\"\n\trdAddendumC.ImageReferenceKey = \"0\"\n\trdAddendumC.Description = \"RD Addendum C\"\n\trdAddendumC.UserField = \"\"\n\treturn rdAddendumC\n}", "func (b *FollowUpBuilder) Incident(value *IncidentBuilder) *FollowUpBuilder {\n\tb.incident = value\n\tif value != nil {\n\t\tb.bitmap_ |= 256\n\t} else {\n\t\tb.bitmap_ &^= 256\n\t}\n\treturn b\n}", "func (s *BasePlSqlParserListener) ExitInline_ref_constraint(ctx *Inline_ref_constraintContext) {}", "func (shard *GRShard) Diagnose(ctx context.Context) (DiagnoseType, error) {\n\tshard.Lock()\n\tdefer shard.Unlock()\n\tdiagnoseResult, err := shard.diagnoseLocked(ctx)\n\tshard.shardStatusCollector.recordDiagnoseResult(diagnoseResult)\n\tshard.populateVTGRStatusLocked()\n\tif diagnoseResult != DiagnoseTypeHealthy {\n\t\tshard.logger.Warningf(`VTGR diagnose shard as unhealthy for %s/%s: result=%v, last_result=%v, instances=%v, primary=%v, primary_tablet=%v, problematics=%v, unreachables=%v,\\n%v`,\n\t\t\tshard.KeyspaceShard.Keyspace, shard.KeyspaceShard.Shard,\n\t\t\tshard.shardStatusCollector.status.DiagnoseResult,\n\t\t\tshard.lastDiagnoseResult,\n\t\t\tshard.shardStatusCollector.status.Instances,\n\t\t\tshard.shardStatusCollector.status.Primary,\n\t\t\tshard.primaryTabletAlias(),\n\t\t\tshard.shardStatusCollector.status.Problematics,\n\t\t\tshard.shardStatusCollector.status.Unreachables,\n\t\t\tshard.sqlGroup.ToString())\n\t}\n\tif diagnoseResult != shard.lastDiagnoseResult {\n\t\tshard.lastDiagnoseResult = diagnoseResult\n\t\tshard.lastDiagnoseSince = time.Now()\n\t}\n\treturn diagnoseResult, err\n}", "func (*Diagnosis) scanValues() []interface{} {\n\treturn []interface{}{\n\t\t&sql.NullInt64{}, // id\n\t\t&sql.NullString{}, // DiagnosticMessages\n\t\t&sql.NullString{}, // SurveillancePeriod\n\t\t&sql.NullString{}, // DiagnosisDate\n\t}\n}", "func (c *KebaUdp) Diagnose() {\n\tvar kr keba.Report100\n\tif err := c.roundtrip(\"report\", 100, &kr); err == nil {\n\t\tfmt.Printf(\"%+v\\n\", kr)\n\t}\n}", "func DetialContains(v string) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldDetial), v))\n\t})\n}", "func (e GetDisscusReqValidationError) Cause() error { return e.cause }", "func (m *MongoSearchSuite) TestConditionReferenceQueryObjectByPatientGender(c *C) {\n\tq := Query{\"Condition\", \"patient.gender=male\"}\n\n\to := m.MongoSearcher.createQueryObject(q)\n\tc.Assert(o, DeepEquals, bson.M{\n\t\t\"patient.referenceid\": bson.M{\"$in\": []string{\"4954037118555241963\"}},\n\t\t\"patient.type\": \"Patient\",\n\t})\n}", "func (s *BaseCGListener) EnterConceptreference(ctx *ConceptreferenceContext) {}", "func (fiba *FIBeneficiaryAdvice) AdviceCodeField() string {\n\treturn fiba.alphaField(fiba.Advice.AdviceCode, 3)\n}", "func (fiba *FIBeneficiaryAdvice) AdviceCodeField() string {\n\treturn fiba.alphaField(fiba.Advice.AdviceCode, 3)\n}", "func (m *DiseaseMutation) DiagnosisIDs() (ids []int) {\n\tif id := m.diagnosis; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (c *Client) DecodeEasypostInsurance(resp *http.Response) (*EasypostInsurance, error) {\n\tvar decoded EasypostInsurance\n\terr := c.Decoder.Decode(&decoded, resp.Body, resp.Header.Get(\"Content-Type\"))\n\treturn &decoded, err\n}", "func (o *FeatureCvtermDbxref) Dbxref(exec boil.Executor, mods ...qm.QueryMod) dbxrefQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"dbxref_id=$1\", o.DbxrefID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Dbxrefs(exec, queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"dbxref\\\"\")\n\n\treturn query\n}", "func (x *PDFAlertEvent) Ref() *C.pdf_alert_event {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_alert_event)(unsafe.Pointer(x))\n}", "func (s *BasevhdlListener) EnterDesignator(ctx *DesignatorContext) {}", "func (x *PDFOcgDescriptor) Ref() *C.pdf_ocg_descriptor {\n\tif x == nil {\n\t\treturn nil\n\t}\n\treturn (*C.pdf_ocg_descriptor)(unsafe.Pointer(x))\n}", "func TestParseReturnDetailAddendumC(t *testing.T) {\n\tvar line = \"3411A 00340 RD Addendum C \"\n\tr := NewReader(strings.NewReader(line))\n\tr.line = line\n\tclh := mockCashLetterHeader()\n\tr.addCurrentCashLetter(NewCashLetter(clh))\n\tbh := mockBundleHeader()\n\trb := NewBundle(bh)\n\tr.currentCashLetter.AddBundle(rb)\n\tr.addCurrentBundle(rb)\n\tcd := mockReturnDetail()\n\tr.currentCashLetter.currentBundle.AddReturnDetail(cd)\n\n\trequire.NoError(t, r.parseReturnDetailAddendumC())\n\trecord := r.currentCashLetter.currentBundle.GetReturns()[0].ReturnDetailAddendumC[0]\n\trequire.Equal(t, \"34\", record.recordType)\n\trequire.Equal(t, \"1\", record.ImageReferenceKeyIndicatorField())\n\trequire.Equal(t, \"1A \", record.MicrofilmArchiveSequenceNumberField())\n\trequire.Equal(t, \"0034\", record.LengthImageReferenceKeyField())\n\trequire.Equal(t, \"0 \", record.ImageReferenceKeyField())\n\trequire.Equal(t, \"RD Addendum C \", record.DescriptionField())\n\trequire.Equal(t, \" \", record.UserFieldField())\n\trequire.Equal(t, \" \", record.reservedField())\n}", "func (m *PatientMutation) ResetDiagnosis() {\n\tm.diagnosis = nil\n\tm.removeddiagnosis = nil\n}", "func (debitDDAdvice *FIDrawdownDebitAccountAdvice) AdviceCodeField() string {\n\treturn debitDDAdvice.alphaField(debitDDAdvice.Advice.AdviceCode, 3)\n}", "func Diag(scope *Scope, diagonal tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Diag\",\n\t\tInput: []tf.Input{\n\t\t\tdiagonal,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnum(s)\n\treturn &v\n}", "func (h *handler) postDiagnosisKeys(w http.ResponseWriter, r *http.Request) {\n\tuploadLimit := h.diagSvc.MaxUploadBatchSize() * diag.DiagnosisKeySize\n\tmaxBytesReader := http.MaxBytesReader(w, r.Body, int64(uploadLimit))\n\tdiagKeys, err := diag.ParseDiagnosisKeys(maxBytesReader)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Invalid body: %v\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = h.diagSvc.StoreDiagnosisKeys(r.Context(), diagKeys)\n\tif err != nil {\n\t\th.logger.Error(\"Could not store diagnosis keys\", zap.Error(err))\n\t\twriteInternalErrorResp(w, err)\n\t\treturn\n\t}\n\n\tfmt.Fprint(w, \"OK\")\n}", "func (d *Diagnosis) QueryPatient() *PatientQuery {\n\treturn (&DiagnosisClient{config: d.config}).QueryPatient(d)\n}", "func (*ClinicalImpression_Investigation) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_r4_core_resources_clinical_impression_proto_rawDescGZIP(), []int{0, 2}\n}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsValueDayOfWeekValueEnum(s)\n\treturn &v\n}", "func (s *BaseSyslParserListener) EnterReference(ctx *ReferenceContext) {}", "func (o ContainerV1Output) ContainerRef() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerV1) pulumi.StringOutput { return v.ContainerRef }).(pulumi.StringOutput)\n}", "func (e CreateDisscusRespValidationError) Cause() error { return e.cause }", "func (s *BasevhdlListener) EnterAccess_type_definition(ctx *Access_type_definitionContext) {}", "func (m Message) GetInterestAccrualDate(f *field.InterestAccrualDateField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m Message) GetInterestAccrualDate(f *field.InterestAccrualDateField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (m *MongoSearchSuite) TestConditionReferenceQueryObjectByPatientId(c *C) {\n\tq := Query{\"Condition\", \"patient=4954037118555241963\"}\n\n\to := m.MongoSearcher.createQueryObject(q)\n\tc.Assert(o, DeepEquals, bson.M{\n\t\t\"patient.referenceid\": bson.RegEx{Pattern: \"^4954037118555241963$\", Options: \"i\"},\n\t\t\"patient.type\": \"Patient\",\n\t})\n}", "func (f AdvRefIDField) Tag() quickfix.Tag { return tag.AdvRefID }", "func (d *Dao) ArcReason(c context.Context, aid int64) (tagID int64, err error) {\n\tvar (\n\t\trow = d.managerDB.QueryRow(c, _reasonSQL, aid)\n\t\ttagIDI xsql.NullInt64\n\t)\n\tif err := row.Scan(&tagIDI); err != nil {\n\t\tif err == xsql.ErrNoRows {\n\t\t\terr = nil\n\t\t} else {\n\t\t\tlog.Error(\"ArcReason row.Scan error(%v)\", err)\n\t\t}\n\t}\n\tlog.Info(\"ArcReason retrun(%v)\", tagIDI)\n\ttagID = tagIDI.Int64\n\treturn\n}", "func (db Database) Dereference(ref DBRef, slaveOk bool, result interface{}) os.Error {\n\tif ref.Database != \"\" {\n\t\tdb.Name = ref.Database\n\t}\n\treturn db.C(ref.Collection).Find(M{\"_id\": ref.Id}).SlaveOk(slaveOk).One(result)\n}", "func (m *DiagnosisMutation) AddField(name string, value ent.Value) error {\n\tswitch name {\n\t}\n\treturn fmt.Errorf(\"unknown Diagnosis numeric field %s\", name)\n}", "func Detial(v string) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldDetial), v))\n\t})\n}", "func newReference(refType ChannelType, properties map[string]edn.Serializable) (ref Reference, err error) {\n\n\tif properties == nil {\n\t\tproperties = make(map[string]edn.Serializable)\n\t}\n\n\tref = &refImpl{\n\t\trefType: refType,\n\t\tproperties: properties,\n\t}\n\n\treturn ref, err\n}", "func (s *BasePlSqlParserListener) ExitOut_of_line_ref_constraint(ctx *Out_of_line_ref_constraintContext) {\n}", "func DetialIn(vs ...string) predicate.Medicalfile {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldDetial), v...))\n\t})\n}", "func Ref(ref string) Option {\n\treturn func(influxdb *InfluxDB) {\n\t\tinfluxdb.Builder.RefID = ref\n\t}\n}", "func (s *BasePlSqlParserListener) EnterReferencing_clause(ctx *Referencing_clauseContext) {}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsLogicalOperatorEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsLogicalOperatorEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsLogicalOperatorEnum(s)\n\treturn &v\n}", "func (s *BasevhdlListener) EnterUnconstrained_nature_definition(ctx *Unconstrained_nature_definitionContext) {\n}", "func testRDAddendumCString(t testing.TB) {\n\tvar line = \"3411A 00340 RD Addendum C \"\n\tr := NewReader(strings.NewReader(line))\n\tr.line = line\n\tclh := mockCashLetterHeader()\n\tr.addCurrentCashLetter(NewCashLetter(clh))\n\tbh := mockBundleHeader()\n\trb := NewBundle(bh)\n\tr.currentCashLetter.AddBundle(rb)\n\tr.addCurrentBundle(rb)\n\tcd := mockReturnDetail()\n\tr.currentCashLetter.currentBundle.AddReturnDetail(cd)\n\n\trequire.NoError(t, r.parseReturnDetailAddendumC())\n\trecord := r.currentCashLetter.currentBundle.GetReturns()[0].ReturnDetailAddendumC[0]\n\n\trequire.Equal(t, line, record.String())\n}", "func (debitDDAdvice *FIDrawdownDebitAccountAdvice) Validate() error {\n\tif debitDDAdvice.tag != TagFIDrawdownDebitAccountAdvice {\n\t\treturn fieldError(\"tag\", ErrValidTagForType, debitDDAdvice.tag)\n\t}\n\tif err := debitDDAdvice.isAdviceCode(debitDDAdvice.Advice.AdviceCode); err != nil {\n\t\treturn fieldError(\"AdviceCode\", err, debitDDAdvice.Advice.AdviceCode)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineOne); err != nil {\n\t\treturn fieldError(\"LineOne\", err, debitDDAdvice.Advice.LineOne)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineTwo); err != nil {\n\t\treturn fieldError(\"LineTwo\", err, debitDDAdvice.Advice.LineTwo)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineThree); err != nil {\n\t\treturn fieldError(\"LineThree\", err, debitDDAdvice.Advice.LineThree)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineFour); err != nil {\n\t\treturn fieldError(\"LineFour\", err, debitDDAdvice.Advice.LineFour)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineFive); err != nil {\n\t\treturn fieldError(\"LineFive\", err, debitDDAdvice.Advice.LineFive)\n\t}\n\tif err := debitDDAdvice.isAlphanumeric(debitDDAdvice.Advice.LineSix); err != nil {\n\t\treturn fieldError(\"LineSix\", err, debitDDAdvice.Advice.LineSix)\n\t}\n\treturn nil\n}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsLogicalOperatorEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsLogicalOperatorEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsLogicalOperatorEnum(s)\n\treturn &v\n}", "func (s *BasevhdlListener) EnterScalar_nature_definition(ctx *Scalar_nature_definitionContext) {}", "func (PatientDiagnosisStatus) EnumDescriptor() ([]byte, []int) {\n\treturn file_heyrenee_v1_messages_patient_diagnosis_proto_rawDescGZIP(), []int{0}\n}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsOperatorEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsOperatorEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsRecordSuppressionsConditionExpressionsConditionsConditionsOperatorEnum(s)\n\treturn &v\n}", "func (s *BasevhdlListener) EnterComposite_nature_definition(ctx *Composite_nature_definitionContext) {\n}", "func DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsOperatorEnumRef(s string) *DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsOperatorEnum {\n\tv := DeidentifyTemplateDeidentifyConfigRecordTransformationsFieldTransformationsConditionExpressionsConditionsConditionsOperatorEnum(s)\n\treturn &v\n}", "func (m *PatientMutation) DiagnosisIDs() (ids []int) {\n\tfor id := range m.diagnosis {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func toGobDiagnostic(posToLocation func(start, end token.Pos) (protocol.Location, error), a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) {\n\tvar fixes []gobSuggestedFix\n\tfor _, fix := range diag.SuggestedFixes {\n\t\tvar gobEdits []gobTextEdit\n\t\tfor _, textEdit := range fix.TextEdits {\n\t\t\tloc, err := posToLocation(textEdit.Pos, textEdit.End)\n\t\t\tif err != nil {\n\t\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in SuggestedFixes: %w\", err)\n\t\t\t}\n\t\t\tgobEdits = append(gobEdits, gobTextEdit{\n\t\t\t\tLocation: loc,\n\t\t\t\tNewText: textEdit.NewText,\n\t\t\t})\n\t\t}\n\t\tfixes = append(fixes, gobSuggestedFix{\n\t\t\tMessage: fix.Message,\n\t\t\tTextEdits: gobEdits,\n\t\t})\n\t}\n\n\tvar related []gobRelatedInformation\n\tfor _, r := range diag.Related {\n\t\tloc, err := posToLocation(r.Pos, r.End)\n\t\tif err != nil {\n\t\t\treturn gobDiagnostic{}, fmt.Errorf(\"in Related: %w\", err)\n\t\t}\n\t\trelated = append(related, gobRelatedInformation{\n\t\t\tLocation: loc,\n\t\t\tMessage: r.Message,\n\t\t})\n\t}\n\n\tloc, err := posToLocation(diag.Pos, diag.End)\n\tif err != nil {\n\t\treturn gobDiagnostic{}, err\n\t}\n\n\t// The Code column of VSCode's Problems table renders this\n\t// information as \"Source(Code)\" where code is a link to CodeHref.\n\t// (The code field must be nonempty for anything to appear.)\n\tdiagURL := effectiveURL(a, diag)\n\tcode := \"default\"\n\tif diag.Category != \"\" {\n\t\tcode = diag.Category\n\t}\n\n\treturn gobDiagnostic{\n\t\tLocation: loc,\n\t\t// Severity for analysis diagnostics is dynamic,\n\t\t// based on user configuration per analyzer.\n\t\tCode: code,\n\t\tCodeHref: diagURL,\n\t\tSource: a.Name,\n\t\tMessage: diag.Message,\n\t\tSuggestedFixes: fixes,\n\t\tRelated: related,\n\t\t// Analysis diagnostics do not contain tags.\n\t}, nil\n}", "func Ref(ref string) interface{} {\n\treturn struct {\n\t\tRef string `json:\"$ref\"`\n\t}{\n\t\tRef: ref,\n\t}\n}" ]
[ "0.51529145", "0.505519", "0.49513835", "0.49229854", "0.4630447", "0.45470026", "0.4536887", "0.44784507", "0.44626653", "0.4388096", "0.43229127", "0.42825848", "0.4265162", "0.4254217", "0.42254162", "0.4214913", "0.4185692", "0.41121167", "0.41015118", "0.4071018", "0.4042993", "0.4029059", "0.4024365", "0.40078765", "0.3987213", "0.39717987", "0.3918872", "0.39157307", "0.39107162", "0.39017907", "0.38926202", "0.38862938", "0.3863949", "0.38625714", "0.38366294", "0.3835859", "0.38270012", "0.38174698", "0.38133296", "0.37972307", "0.37969363", "0.37720588", "0.37628138", "0.3761201", "0.3750891", "0.374723", "0.37341315", "0.3732026", "0.37308416", "0.37299988", "0.37295088", "0.37268156", "0.37262163", "0.3718645", "0.3718645", "0.3718342", "0.37045455", "0.37027106", "0.36989924", "0.36959752", "0.368834", "0.3687345", "0.366245", "0.36553124", "0.36528376", "0.3651114", "0.3640654", "0.36374566", "0.363297", "0.36275026", "0.36214536", "0.35999516", "0.3588812", "0.35879776", "0.35871473", "0.35871473", "0.35850486", "0.3583733", "0.35836196", "0.35834825", "0.35821766", "0.35811132", "0.35733482", "0.35691324", "0.35619122", "0.35611808", "0.3559146", "0.35581023", "0.3556766", "0.35556775", "0.3553538", "0.35514152", "0.35513818", "0.35376614", "0.35359666", "0.352965", "0.35237175", "0.3522329", "0.35126945", "0.35123274" ]
0.7796643
0
addURL adds the FullURL field to the resource, and if the bundle type is set to Batch the Request field is also set to provide execution information for the server. `url` is the HTTP URL for the resource, and is usually the resource type. addURL should only be called from internal methods where `entry` has already been constructed via a struct literal.
func (b *Bundler) addURL(entry *r4pb.Bundle_Entry, id, url string) *r4pb.Bundle_Entry { if b.bundleTypeCode == cpb.BundleTypeCode_BATCH { entry.Request = request(url) } entry.FullUrl = &dpb.Uri{Value: fmt.Sprintf("%s/%s", url, id)} return entry }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Person) AddURL(url string) error {\n\t// Must be greater than 5 characters\n\tif len(url) <= 5 {\n\t\treturn ErrURLTooShort\n\t}\n\n\t// Set the url\n\tnewURL := new(URL)\n\tnewURL.URL = url\n\tp.URLs = append(p.URLs, *newURL)\n\treturn nil\n}", "func addUrl(writer http.ResponseWriter, request *http.Request) {\n\tvars := mux.Vars(request)\n\thostname := vars[\"hostname\"]\n\tquerypath := vars[\"querypath\"]\n\n\tresponse := APIResponse{}\n\terr := utils.ValidateUrl(hostname)\n\tif err != nil {\n\t\tresponse.BadRequest(err)\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\tdecodedPath, err := utils.URLDecode(querypath)\n\tif err != nil {\n\t\tresponse.BadRequest(err)\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\t// Generate URL service for querying the URL\n\turlService, err := services.NewUrlService(hostname, decodedPath, config.DBType, config.CacheType)\n\tif err != nil {\n\t\tutils.LogError(utils.LogFields{\"hostname\": hostname, \"path\": decodedPath}, err, \"Error getting URL\")\n\t\tresponse.InternalError(errors.New(\"An error occurred\"))\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\terr = urlService.AddUrl()\n\tif err != nil {\n\t\tresponse.BadRequest(err)\n\t} else {\n\t\tresponse.Success(StringData{Message: \"Successfully added URL\"})\n\t}\n\n\thttp_respond(response, writer)\n}", "func (s Store) AddURL(url string) (string, error) {\n\turl = strings.TrimSpace(url)\n\tif url == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Empty url is not allowed\")\n\t}\n\tid := s.getID(url)\n\tif id != \"\" {\n\t\treturn id, nil\n\t}\n\n\tid = newID()\n\tif err := s.put(id, url); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn id, nil\n}", "func (s *Service) AddURL(url string) error {\n\tindex := s.indexOfURL(url)\n\n\tif index != -1 {\n\t\treturn fmt.Errorf(\"URL '%s' is already registered\", url)\n\t}\n\n\ts.URLs = append(s.URLs, url)\n\treturn nil\n}", "func (m *Manager) AddURL(url *ice.URL) error {\n\tswitch url.Scheme {\n\tcase ice.SchemeTypeSTUN:\n\t\tladdr, xoraddr, err := webrtcStun.AllocateUDP(url)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tp, err := newPort(laddr.String(), m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc := &ice.CandidateSrflx{\n\t\t\tCandidateBase: ice.CandidateBase{\n\t\t\t\tProtocol: ice.ProtoTypeUDP,\n\t\t\t\tAddress: xoraddr.IP.String(),\n\t\t\t\tPort: xoraddr.Port,\n\t\t\t\tConn: p.conn,\n\t\t\t},\n\t\t\tRemoteAddress: laddr.IP.String(),\n\t\t\tRemotePort: laddr.Port,\n\t\t}\n\n\t\tm.portsLock.Lock()\n\t\tdefer m.portsLock.Unlock()\n\t\tm.ports = append(m.ports, p)\n\t\tm.IceAgent.AddLocalCandidate(c)\n\tdefault:\n\t\treturn errors.Errorf(\"%s is not implemented\", url.Scheme.String())\n\t}\n\n\treturn nil\n}", "func (b *Builder) URL(s string) *Builder {\n\treturn b.appendMessage(s, func(offset, limit int) tg.MessageEntityClass {\n\t\treturn &tg.MessageEntityUrl{Offset: offset, Length: limit}\n\t})\n}", "func (uuo *UserUpdateOne) SetURL(u *url.URL) *UserUpdateOne {\n\tuuo.url = &u\n\treturn uuo\n}", "func (uuo *UserUpdateOne) SetURL(u *url.URL) *UserUpdateOne {\n\tuuo.url = &u\n\treturn uuo\n}", "func (b *PagesClearCacheBuilder) URL(v string) *PagesClearCacheBuilder {\n\tb.Params[\"url\"] = v\n\treturn b\n}", "func (txt *DNSSdTxtRecord) AddURL(key, value string) {\n\t*txt = append(*txt, DNSSdTxtItem{key, value, true})\n}", "func (r *Request) URL(uri string) *Request {\n\tr.URLStruct, r.Error = url.Parse(uri)\n\treturn r\n}", "func (f *File) SetURL(url string) {\n\tf.url = url\n}", "func (me *Crawler) AddUrl(URL string) (err error) {\n\tfor range only.Once {\n\t\tvar u *url.URL\n\t\tu, err = url.Parse(URL)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif u.Path == \"\" {\n\t\t\tu.Path = \"/\"\n\t\t}\n\t\tr := &colly.Request{\n\t\t\tURL: u,\n\t\t\tMethod: \"GET\",\n\t\t}\n\t\tvar b []byte\n\t\tb, err = r.Marshal()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\terr = me.Storage.AddRequest(b)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func (co *serverConfig) SetURL(URL string) ServerConfigBuilder {\n\tco.URL = URL\n\treturn co\n}", "func (r *Request) URL(url string) *Request {\n\tr.url = url\n\treturn r\n}", "func (r *Request) URL(url string) *Request {\n\tr.url = url\n\treturn r\n}", "func (c Credentials) addToURL(u string) (string, error) {\n\tif !c.Empty() {\n\t\tmodified, err := url.Parse(u)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to parse url '%v': %v\", u, err)\n\t\t}\n\t\tmodified.User = url.UserPassword(c.Username, c.Password)\n\t\tu = modified.String()\n\t}\n\treturn u, nil\n}", "func (e *DiscordWebhookEmbed) SetURL(URL string) {\n\te.URL = URL\n}", "func (k *Keyboard) AddURLButton(text, uri string) *Keyboard {\n\treturn k.addInlineButton(text, uri, \"url\")\n}", "func (uu *UserUpdate) SetURL(u *url.URL) *UserUpdate {\n\tuu.url = &u\n\treturn uu\n}", "func (uu *UserUpdate) SetURL(u *url.URL) *UserUpdate {\n\tuu.url = &u\n\treturn uu\n}", "func (rc *RestaurantCreate) SetURL(s string) *RestaurantCreate {\n\trc.mutation.SetURL(s)\n\treturn rc\n}", "func (buo *BankUpdateOne) SetURL(s string) *BankUpdateOne {\n\tbuo.mutation.SetURL(s)\n\treturn buo\n}", "func (c *Client) Url(method string, e ...Endpoint) Modifier {\n\t// TODO Create composite URLs? Add().Add().. etc? Easier to modify on the fly..\n\treturn func(r *http.Request) error {\n\t\tu := c.createURL(e...)\n\t\tr.URL = u\n\t\tr.Method = method\n\t\treturn nil\n\t}\n}", "func (m *WorkforceIntegration) SetUrl(value *string)() {\n m.url = value\n}", "func (sc *SourceCreate) SetURL(s string) *SourceCreate {\n\tsc.mutation.SetURL(s)\n\treturn sc\n}", "func (client ListManagementImageClient) AddImageURLInput(ctx context.Context, listID string, contentType string, imageURL BodyModel, tag *int32, label string) (result Image, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ListManagementImageClient.AddImageURLInput\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.AddImageURLInputPreparer(ctx, listID, contentType, imageURL, tag, label)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.AddImageURLInputSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.AddImageURLInputResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"contentmoderator.ListManagementImageClient\", \"AddImageURLInput\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (p *Manager) AddFromURL(purl string) {\n\tproxy := p.parseURL(purl)\n\tp.Add(proxy)\n}", "func (b *FollowUpBuilder) Url(value string) *FollowUpBuilder {\n\tb.url = value\n\tb.bitmap_ |= 16384\n\treturn b\n}", "func (bu *BankUpdate) SetURL(s string) *BankUpdate {\n\tbu.mutation.SetURL(s)\n\treturn bu\n}", "func (cb *ClientBuilder) URL(url string) *ClientBuilder {\n\tcb.client.url = url\n\treturn cb\n}", "func (cb *ClientBuilder) URL(url string) *ClientBuilder {\n\tcb.client.url = url\n\treturn cb\n}", "func (args *HTTPArgs) SetRequestURL() (err error) {\n\tif args.URL == \"\" {\n\t\terr = fmt.Errorf(\"url not found: %v\", args.URL)\n\t\treturn\n\t}\n\turlValues := url.Values{}\n\tfor key, value := range args.Values {\n\t\turlValues.Add(key, value)\n\t}\n\n\turlArgs := urlValues.Encode()\n\targs.URL = fmt.Sprintf(\"%s?%s\", args.URL, urlArgs)\n\treturn\n}", "func (upvc *UnsavedPostVideoCreate) SetURL(s string) *UnsavedPostVideoCreate {\n\tupvc.mutation.SetURL(s)\n\treturn upvc\n}", "func (b *HTTPSDConfigApplyConfiguration) WithURL(value string) *HTTPSDConfigApplyConfiguration {\n\tb.URL = &value\n\treturn b\n}", "func (juke *Jukebox) AddSongURL(name string, songURL string) error {\n\tsong, err := fetchSong(songURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn juke.addSong(name, song)\n}", "func (m *AuditLogMutation) SetURL(s string) {\n\tm.url = &s\n}", "func (c *CrawlerState) AddURL(url string) bool {\n\tc.Lock()\n\tif _, ok := c.urlMap[url]; ok {\n\t\t// URL already present. Return false indicating the new url was already present\n\t\tc.Unlock()\n\t\treturn false\n\t}\n\tc.urlMap[url] = struct{}{}\n\tc.seenURLCount++\n\tc.urls = append(c.urls, url)\n\tc.Unlock()\n\treturn true\n}", "func PutURL(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"PUT URL\")\n\turlKey := mux.Vars(r)[urlKeyPattern]\n\tdao := NewDao(shortURLDbPath)\n\texists, status := dao.DoesExist(urlKey)\n\n\tif status == Error {\n\t\tlog.Println(\"Internal Server Error\")\n\t\tsendJSON(w, http.StatusInternalServerError, genericResponse{\"Internal Server Error\"})\n\t\treturn\n\t}\n\n\tif !exists {\n\t\tsendJSON(w, http.StatusNotFound, genericResponse{\"No URL found for key \" + urlKey})\n\t\treturn\n\t}\n\n\twriteURLInfo(w, r, urlKey, http.StatusOK)\n}", "func WithURL(u *url.URL) Option {\n\treturn func(c *Client) {\n\t\tc.url = *u\n\t}\n}", "func (o *CreateEventPayloadActions) SetUrl(v string) {\n\to.Url = v\n}", "func (o *EntityWatchlistScreeningSearchTerms) SetUrl(v string) {\n\to.Url.Set(&v)\n}", "func (r *Request) SetURL(u *url.URL) *Request {\n\tr.URLStruct = u\n\treturn r\n}", "func URL(url string) Option {\n\treturn func(opts *options) {\n\t\topts.url = url\n\t}\n}", "func (o *WebhooksJsonWebhook) SetUrl(v string) {\n\to.Url = &v\n}", "func (hr HttpRequest) url(r Resource) (string, error) {\n\tslash := \"/\"\n\tpath := r.path\n\tbaseURL := r.protocol + r.baseURL\n\tif hr.overrideBaseURL != \"\" {\n\t\tbaseURL = hr.overrideBaseURL\n\t}\n\tif strings.HasPrefix(path, slash) && strings.HasSuffix(baseURL, slash) {\n\t\tstrings.TrimLeft(path, slash)\n\t} else if !strings.HasPrefix(path, slash) && !strings.HasSuffix(baseURL, slash) {\n\t\tpath = slash + path\n\t}\n\tquery, err := hr.queryString(r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif query != \"\" {\n\t\treturn baseURL + path + \"?\" + query, nil\n\t}\n\treturn baseURL + path, nil\n}", "func (b *SlackActionApplyConfiguration) WithURL(value string) *SlackActionApplyConfiguration {\n\tb.URL = &value\n\treturn b\n}", "func (c *Controller) AddNewURLEntry(urlEntry *URLEntry) {\n\tselect {\n\tcase <-c.ctx.Done():\n\t\treturn\n\tcase c.subTree <- urlEntry:\n\t}\n}", "func (a *AssetRegistry) SetRegistryURL(url string) {\n\ta.client = registryclient.NewHTTPClient(resty.New().SetHostURL(url))\n}", "func SetURL(url string) func(*MGO) error {\n\treturn func(m *MGO) error {\n\t\tm.url = url\n\t\treturn nil\n\t}\n}", "func (c *Config) SetURL(k string, u *url.URL) {\n\tc.SetString(k, u.String())\n}", "func WithURL(u string) Option {\n\treturn optionFn(func(n *namespaceClient) error {\n\t\tif _, err := url.ParseRequestURI(u); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.url = u\n\t\treturn nil\n\t})\n}", "func SetURL(name, newurl, oldurl string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"set-url\")\n\t\tg.AddOptions(name)\n\t\tg.AddOptions(newurl)\n\t\tif oldurl != \"\" {\n\t\t\tg.AddOptions(oldurl)\n\t\t}\n\t}\n}", "func (m *TelecomExpenseManagementPartner) SetUrl(value *string)() {\n err := m.GetBackingStore().Set(\"url\", value)\n if err != nil {\n panic(err)\n }\n}", "func (service *BaseService) SetURL(url string) error {\n\treturn service.SetServiceURL(url)\n}", "func WithURL(uri, compression string) Option {\n\tc, cerr := ovalutil.ParseCompressor(compression)\n\tu, uerr := url.Parse(uri)\n\treturn func(up *Updater) error {\n\t\t// Return any errors from the outer function.\n\t\tswitch {\n\t\tcase cerr != nil:\n\t\t\treturn cerr\n\t\tcase uerr != nil:\n\t\t\treturn uerr\n\t\t}\n\t\tup.Fetcher.Compression = c\n\t\tup.Fetcher.URL = u\n\t\treturn nil\n\t}\n}", "func URL(url string) func(*Config) {\n\treturn func(c *Config) {\n\t\tc.URL = url\n\t}\n}", "func URL(url string) func(*Config) {\n\treturn func(c *Config) {\n\t\tc.URL = url\n\t}\n}", "func (h *Handlers) NewURL(w http.ResponseWriter, r *http.Request, params map[string]string) {\n\tu := params[\"\"]\n\n\tif !h.ValidateURL(u) {\n\t\th.RespondError(w, ErrInvalidURL, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\treqDB := h.masterDB.Copy()\n\tdefer reqDB.Close()\n\n\tcollection := reqDB.DB(\"\").C(urlCollection)\n\n\tslug := h.slugifier.GenerateUniqueSlug(8, collection, \"slug\")\n\n\tnewUrl := URL{\n\t\tSlug: slug,\n\t\tOriginalURL: u,\n\t\tShortURL: h.Host + \"/\" + slug,\n\t}\n\n\tif err := collection.Insert(&newUrl); err != nil {\n\t\th.RespondError(w, ErrUnableToShortenUrl, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\th.RespondJSON(w, newUrl, 201)\n}", "func (o *UserFileUploadViaURLRequest) SetUrl(v string) {\n\to.Url = v\n}", "func (m *CommsNotification) SetResourceUrl(value *string)() {\n m.resourceUrl = value\n}", "func WithURL(apiURL *url.URL) Option {\n\treturn func(cfg *config) {\n\t\tcfg.apiURL = apiURL\n\t}\n}", "func (m *Attachment) UpdateURL() error {\n\turl, err := core.GetS3Object(core.DefaultSigningTime, m.PATH)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.URL = url\n\tm.SigningMinutes = core.DefaultSigningTime\n\tm.SigningTime = time.Now()\n\n\treturn nil\n}", "func withURL(u *url.URL) option {\n\treturn func(m *matcher) error {\n\t\tif u == nil {\n\t\t\treturn nil\n\t\t}\n\t\turlClone := *u\n\t\tm.url = &urlClone\n\t\treturn nil\n\t}\n}", "func (m *UserMutation) SetURL(u *url.URL) {\n\tm.url = &u\n}", "func (c *Client) URL(path string, a ...interface{}) string {\n\tu, _ := urlx.Parse(c.addr)\n\n\tu.Path = fmt.Sprintf(path, a...)\n\n\treturn u.String()\n}", "func SetURL(url string) ClientOptionFunc {\n\treturn func(c *TogglHttpClient) error {\n\t\tc.Url = url\n\t\treturn nil\n\t}\n}", "func (check *Check) Url(url string) *Check {\n\tcheck.url = &url\n\treturn check\n}", "func (htpc *HttpProcessorConfig) Url(url ...string) *HttpProcessorConfig {\n\thtpc.urls = append(htpc.urls, url...)\n\treturn htpc\n}", "func (s *MapURLStorage) AddNewURL(url string) string {\n\thashIdentifier := IDToHash(len(s.Storage))\n\n\t// TODO - Valudate URL and return if URL is invalid.\n\ts.Storage[hashIdentifier] = url\n\treturn hashIdentifier\n}", "func WithResourceURL(url string) UploadOption {\n\treturn func(u *httpUpload) {\n\t\tu.resourceURL = url\n\t}\n}", "func (o *Commitstatus) SetUrl(v string) {\n\to.Url = &v\n}", "func (b *AWSServiceEndpointApplyConfiguration) WithURL(value string) *AWSServiceEndpointApplyConfiguration {\n\tb.URL = &value\n\treturn b\n}", "func (b *Binary) SetURL(urlStr string) {\n\tif urlStr == \"\" {\n\t\treturn\n\t}\n\tu, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn\n\t}\n\tb.url = u\n}", "func AddUrl(ctx context.Context, client *firestore.Client, url string) (string, error) {\n\tkey, err := incrementCounter(ctx, client)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, _, err = client.Collection(\"urls\").Add(ctx, map[string]string{\n\t\t\"key\": key,\n\t\t\"url\": url,\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.New(\"could not add url to database\")\n\t}\n\treturn key, nil\n}", "func URLFormat(urlFormat string) Opt {\n\treturn func(c *HTTP) {\n\t\tc.manifestURLFmt = urlFormat\n\t}\n}", "func GenURL(cdi *container.Registry, resource string, v ...interface{}) string {\n\n\tif cdi == nil {\n\t\tif len(v) == 0 {\n\t\t\treturn resource\n\t\t}\n\t\treturn fmt.Sprintf(resource, v...)\n\t}\n\n\turLer := GetURLGen(cdi)\n\tif urLer == nil {\n\t\tif len(v) == 0 {\n\t\t\treturn resource\n\t\t}\n\t\treturn fmt.Sprintf(resource, v...)\n\t}\n\n\treturn urLer.URL(resource, v...)\n}", "func Add(name, url string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"add\")\n\t\tg.AddOptions(name)\n\t\tg.AddOptions(url)\n\t}\n}", "func (m *LogicAppTriggerEndpointConfiguration) SetUrl(value *string)() {\n err := m.GetBackingStore().Set(\"url\", value)\n if err != nil {\n panic(err)\n }\n}", "func (r *Repository) addImage(url string) error {\n\tif !isImage(url) {\n\t\treturn fmt.Errorf(\"not a supported image type\")\n\t}\n\n\tfilename, err := getFilename(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error parsing url: %w\", err)\n\t}\n\tfilename = filepath.Join(r.root, filename)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching image: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\timage, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading image: %w\", err)\n\t}\n\terr = os.WriteFile(filename, image, 0666)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error saving image: %w\", err)\n\t}\n\n\treturn nil\n}", "func URL(name string, value string) *url.URL {\n\tp := new(url.URL)\n\tURLVar(p, name, value)\n\treturn p\n}", "func (o *PostWebhook) SetUrl(v string) {\n\to.Url = v\n}", "func AddFeedURL(db *sql.DB, url string) (int64, error) {\n\tvar result int64\n\tfeedStmt := \"INSERT INTO feeds (uri) VALUES ($1)\"\n\n\tif FeedURLExist(db, url) {\n\t\treturn result, fmt.Errorf(\"Feed already exists\")\n\t}\n\n\tdbResult, err := db.Exec(feedStmt, url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult, err = dbResult.LastInsertId()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn result, nil\n}", "func RequestWithURL(task *Task) (io.Reader, error) {\n\treq, err := http.NewRequest(\"GET\", task.Url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(fmt.Sprintf(\"%s [%d]\", task.Url, resp.StatusCode))\n\ttask.Context.Request = req\n\ttask.Context.Response = resp\n\treturn resp.Body, nil\n}", "func (b *Builder) TextURL(s, url string) *Builder {\n\treturn b.appendMessage(s, func(offset, limit int) tg.MessageEntityClass {\n\t\treturn &tg.MessageEntityTextUrl{Offset: offset, Length: limit, URL: url}\n\t})\n}", "func (h *handler) CreateURL(response http.ResponseWriter, request *http.Request) {\n\tvar body createURLRequest\n\n\tdecoder := json.NewDecoder(request.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\thttp.Error(response, \"Invalid body: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := getUniquePath(body.URL)\n\n\tlog.Infof(\"Request to shorten URL '%s'. Path assigned: '%s'\", body.URL, path)\n\n\tif err := h.store.Put(path, body.URL); err != nil {\n\t\tlog.Errorf(\"Generated path '%s' cannot be stored due to: %+v\", path, err)\n\t\thttp.Error(response, \"There was a collision with the generated path, please try again\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Location\", \"/\"+path)\n\tresponse.WriteHeader(http.StatusCreated)\n}", "func (ucc *UpdateClientConfig) Add(url string) error {\n\tif url == \"\" {\n\t\treturn ErrorsUCEmptyURL\n\t}\n\n\tvar err error\n\tif !ucc.exist() {\n\t\terr = ucc.Init()\n\t} else {\n\t\terr = ucc.Load()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, repo := range ucc.Repos {\n\t\tif repo == url {\n\t\t\treturn ErrorsUCRepoExist\n\t\t}\n\t}\n\tucc.Repos = append(ucc.Repos, url)\n\n\treturn ucc.save()\n}", "func (s *UiTemplateInfo) SetUrl(v string) *UiTemplateInfo {\n\ts.Url = &v\n\treturn s\n}", "func (ctx *HijackRequest) SetURL(url string) *HijackRequest {\n\tctx.req.URL(url)\n\treturn ctx\n}", "func AddUserToURL(gitURL string, user string) (string, error) {\n\tu, err := url.Parse(gitURL)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"invalid git URL: %s\", gitURL)\n\t}\n\n\tif user != \"\" && u.Scheme != \"file\" {\n\t\tuserInfo := url.User(user)\n\t\tu.User = userInfo\n\t}\n\n\treturn u.String(), nil\n}", "func URL(url *url.URL) zapcore.Field {\n\treturn zap.Object(\"url\", &URLField{URL: url})\n}", "func SetURL(index int, url string) (err error) {\n\tclient := getClient()\n\terr = client.Set(\"url\"+string(index), url, 0).Err()\n\treturn\n}", "func (f *Feed) AddEntry(\n\ttitle string,\n\turl string,\n\tid string,\n\tupdatedDate time.Time,\n\tpubDate time.Time,\n\tauthorName string,\n\tauthorURL string,\n\tauthorEmail string,\n\tcontentHTML string) error {\n\n\tf.Entries = append(f.Entries, Entry{\n\t\tTitle: title,\n\t\tLink: Link{\n\t\t\tRel: \"alternate\",\n\t\t\tType: \"text/html\",\n\t\t\tHref: url,\n\t\t},\n\t\tID: id,\n\t\tUpdated: updatedDate,\n\t\tPublished: pubDate,\n\t\tAuthor: Author{\n\t\t\tName: authorName,\n\t\t\tURI: authorURL,\n\t\t\tEmail: authorEmail,\n\t\t},\n\t\tContent: Content{\n\t\t\tType: \"html\",\n\t\t\tText: contentHTML,\n\t\t},\n\t})\n\n\treturn nil\n}", "func (o *NotificationConfig) SetUrl(v string) {\n\to.Url = &v\n}", "func (m refCountedUrlSet) addUrl(urlStr string) bool {\n\tm[urlStr]++\n\treturn m[urlStr] == 1\n}", "func URL(s string) got.URL {\n\treturn got.URL(s)\n}", "func WithURL(url string) GitCommitOptionsFunc {\n\treturn func(c *CreateCommit) error {\n\t\tif url == \"\" {\n\t\t\treturn errors.New(\"url is required\")\n\t\t}\n\t\tc.URL = url\n\t\treturn nil\n\t}\n}", "func (b *ConnectionConfigApplyConfiguration) WithURL(value string) *ConnectionConfigApplyConfiguration {\n\tb.URL = &value\n\treturn b\n}", "func (r *Request) URLf(format string, args ...interface{}) *Request {\n\tr.url = fmt.Sprintf(format, args...)\n\treturn r\n}", "func URLOption(url string) Option {\n\treturn func(opts *options) {\n\t\topts.URL = url\n\t}\n}" ]
[ "0.669817", "0.64076823", "0.6359178", "0.622997", "0.61183804", "0.59739757", "0.59059775", "0.59059775", "0.5903072", "0.59013337", "0.586378", "0.58552855", "0.5844933", "0.58091784", "0.57978183", "0.57978183", "0.5795734", "0.5769567", "0.57462054", "0.5734217", "0.5734217", "0.5724442", "0.5691368", "0.5669058", "0.5637654", "0.5621184", "0.56117797", "0.5584226", "0.55778897", "0.5577584", "0.5560017", "0.5560017", "0.5543243", "0.5540423", "0.55261976", "0.54754436", "0.5462538", "0.54611856", "0.5433821", "0.54331905", "0.54180086", "0.5410393", "0.53682137", "0.53646845", "0.5341087", "0.53393424", "0.5338964", "0.5310014", "0.5301016", "0.52962023", "0.52810484", "0.5267573", "0.5259617", "0.5250129", "0.5246696", "0.52413756", "0.5235847", "0.5235847", "0.5217919", "0.52164596", "0.520932", "0.5200119", "0.5186953", "0.51843554", "0.5182475", "0.51814026", "0.5174357", "0.5169957", "0.5167912", "0.51655066", "0.5161737", "0.5123333", "0.5121812", "0.5121669", "0.51080984", "0.5105045", "0.5088554", "0.50845855", "0.50790167", "0.50765896", "0.5071068", "0.50621045", "0.5058005", "0.5055692", "0.5053849", "0.5047738", "0.50436175", "0.5042076", "0.503842", "0.5037617", "0.50372344", "0.503602", "0.50346565", "0.5024896", "0.50232756", "0.5020694", "0.5020451", "0.5017734", "0.5013488", "0.5000123" ]
0.8095527
0
NewServer creates a new pprof server
func NewServer() api.PProfServiceServer { return server{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewServer(addr string, enablePprof bool, ready *bool) *http.Server {\n\th := &handler{\n\t\tpromHandler: promhttp.Handler(),\n\t\tenablePprof: enablePprof,\n\t\tready: ready,\n\t}\n\n\treturn &http.Server{\n\t\tAddr: addr,\n\t\tHandler: h,\n\t\tReadHeaderTimeout: 15 * time.Second,\n\t}\n}", "func NewServer() *Server {}", "func newRPCServer(parallelTotal int, reporter reporters.Reporter) (*RPCServer, error) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RPCServer{\n\t\tlistener: listener,\n\t\thandler: newServerHandler(parallelTotal, reporter),\n\t}, nil\n}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func newServer(ctx context.Context, logger zerolog.Logger, dsn datastore.PGDatasourceName) (*server.Server, func(), error) {\n\t// This will be filled in by Wire with providers from the provider sets in\n\t// wire.Build.\n\twire.Build(\n\t\twire.InterfaceValue(new(trace.Exporter), trace.Exporter(nil)),\n\t\tgoCloudServerSet,\n\t\tapplicationSet,\n\t\tappHealthChecks,\n\t\twire.Struct(new(server.Options), \"HealthChecks\", \"TraceExporter\", \"DefaultSamplingPolicy\", \"Driver\"),\n\t\tdatastore.NewDB,\n\t\twire.Bind(new(datastore.Datastorer), new(*datastore.Datastore)),\n\t\tdatastore.NewDatastore)\n\treturn nil, nil, nil\n}", "func NewServer(address string, svc handlers.Service, opts *Options) xserver.Server {\n\tif opts == nil {\n\t\topts = NewOptions()\n\t}\n\n\tmux := http.NewServeMux()\n\thandlers.RegisterService(mux, svc)\n\tpprof.RegisterHandler(mux)\n\n\treturn &server{\n\t\topts: opts,\n\t\taddress: address,\n\t\tserver: &http.Server{\n\t\t\tHandler: mux,\n\t\t},\n\t}\n}", "func NewServer(stop chan bool) *Server {\n\tmux := http.NewServeMux()\n\ttotalTimeChan := make(chan time.Duration, 100)\n\tstatsRequestChan := make(chan int, 100)\n\tincomingStatsChan := make(chan Stats, 100)\n\tmgr := managerChannels{\n\t\ttotalTimeChan: totalTimeChan,\n\t\tstatsRequestChan: statsRequestChan,\n\t\tincomingStatsChan: incomingStatsChan,\n\t\tstop: stop,\n\t}\n\ts := &Server{\n\t\ttotaltime: totalTimeChan,\n\t\tstatsrequest: statsRequestChan,\n\t\tincomingstats: incomingStatsChan,\n\t\tstop: stop,\n\t\tmux: mux,\n\t}\n\n\tgo computeStats(mgr)\n\ts.mux.HandleFunc(\"/hash\", s.computePasswordHash)\n\ts.mux.HandleFunc(\"/shutdown\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"GET\" {\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tstop <- true\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t}\n\t})\n\ts.mux.HandleFunc(\"/stats\", s.getStats)\n\treturn s\n}", "func newServer(cert *shared.CertInfo, handler http.Handler) *httptest.Server {\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.TLS = util.ServerTLSConfig(cert)\n\tserver.StartTLS()\n\treturn server\n}", "func NewServer(config *config.Config, appCache *cache.AppCache, mySql *db.MysqlDB) *HttpServer {\n\ts := Server{\n\t\tConfig: config,\n\t\tInventory: &service.Inventory{\n\t\t\tAppCache: appCache,\n\t\t\tMysql: mySql,\n\t\t},\n\t}\n\n\t// Create a HTTP server for prometheus.\n\tserveMux := http.NewServeMux()\n\tserveMux.HandleFunc(\"/getQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.getQuantity(res, req)\n\t})\n\tserveMux.HandleFunc(\"/addQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.addQuantity(res, req)\n\t})\n\tserveMux.HandleFunc(\"/addNegativeQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.addNegativeQuantity(res, req)\n\t})\n\n\treturn &HttpServer{\n\t\tServeMux: serveMux,\n\t\tConfig: config,\n\t}\n}", "func newServer(mux *http.ServeMux, addr string) *http.Server {\n\tsrv := &http.Server{\n\t\tAddr: addr,\n\t\tReadTimeout: 5 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tIdleTimeout: 120 * time.Second,\n\t\tHandler: mux,\n\t}\n\n\treturn srv\n}", "func CreateServer(serverConfig ServerConfig) {\n\n}", "func NewServer(options ...ServerOption) *Server {\n s := &Server{\n codecs: make(map[string]Codec),\n services: new(serviceMap),\n }\n for _, option := range options {\n option(s)\n }\n return s\n}", "func NewServer(configFile string) (*Server, error) {\n\tmanager := schema.GetManager()\n\tconfig := util.GetConfig()\n\terr := config.ReadConfig(configFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Config load error: %s\", err)\n\t}\n\terr = os.Chdir(path.Dir(configFile))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Chdir error: %s\", err)\n\t}\n\terr = l.SetUpLogging(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Logging setup error: %s\", err)\n\t}\n\tlog.Info(\"logging initialized\")\n\n\tserver := &Server{}\n\n\tm := martini.Classic()\n\tm.Handlers()\n\tm.Use(middleware.WithContext())\n\tm.Use(middleware.Tracing())\n\tm.Use(middleware.Logging())\n\tm.Use(middleware.Metrics())\n\tm.Use(martini.Recovery())\n\tm.Use(middleware.JSONURLs())\n\n\tserver.martini = m\n\n\tport := os.Getenv(\"PORT\")\n\n\tif port == \"\" {\n\t\tport = \"9091\"\n\t}\n\n\tserver.extensions = config.GetStringList(\"extension/use\", []string{\n\t\t\"goext\",\n\t\t\"javascript\",\n\t})\n\tschema.DefaultExtension = config.GetString(\"extension/default\", \"javascript\")\n\n\tmanager.TimeLimit = time.Duration(config.GetInt(\"extension/timelimit\", 30)) * time.Second\n\n\tif config.GetList(\"extension/timelimits\", nil) != nil {\n\t\ttimeLimitList := config.GetList(\"extension/timelimits\", nil)\n\t\tfor _, timeLimit := range timeLimitList {\n\t\t\tcfgRaw := timeLimit.(map[string]interface{})\n\t\t\tcfgPath := cfgRaw[\"path\"].(string)\n\t\t\tcfgEvent := cfgRaw[\"event\"].(string)\n\t\t\tcfgTimeDuration := cfgRaw[\"timelimit\"].(int)\n\n\t\t\tmanager.TimeLimits = append(manager.TimeLimits, &schema.PathEventTimeLimit{\n\t\t\t\tPathRegex: regexp.MustCompile(cfgPath),\n\t\t\t\tEventRegex: regexp.MustCompile(cfgEvent),\n\t\t\t\tTimeDuration: time.Second * time.Duration(cfgTimeDuration),\n\t\t\t})\n\t\t}\n\t}\n\n\tserver.address = config.GetString(\"address\", \":\"+port)\n\tif config.GetBool(\"tls/enabled\", false) {\n\t\tlog.Info(\"TLS enabled\")\n\t\tserver.tls = &tlsConfig{\n\t\t\tKeyFile: config.GetString(\"tls/key_file\", \"./etc/key.pem\"),\n\t\t\tCertFile: config.GetString(\"tls/cert_file\", \"./etc/cert.pem\"),\n\t\t}\n\t}\n\n\tserver.sync, err = sync_util.CreateFromConfig(config)\n\tif err != nil {\n\t\tlog.Error(\"Failed to create sync, err: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tif dbErr := server.connectDB(); dbErr != nil {\n\t\tlog.Fatalf(\"Error while connecting to DB: %s\", dbErr)\n\t}\n\n\tschemaFiles := config.GetStringList(\"schemas\", nil)\n\tif schemaFiles == nil {\n\t\tlog.Fatal(\"No schema specified in configuration\")\n\t} else {\n\t\terr = manager.LoadSchemasFromFiles(schemaFiles...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid schema: %s\", err)\n\t\t}\n\t}\n\n\tif !config.GetBool(\"database/no_init\", false) {\n\t\tserver.initDB()\n\t}\n\n\tif err = metrics.SetupMetrics(config, server.address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.GetList(\"database/initial_data\", nil) != nil {\n\t\tinitialDataList := config.GetList(\"database/initial_data\", nil)\n\t\tfor _, initialData := range initialDataList {\n\t\t\tinitialDataConfig := initialData.(map[string]interface{})\n\t\t\tfilePath := initialDataConfig[\"connection\"].(string)\n\t\t\tlog.Info(\"Importing data from %s ...\", filePath)\n\t\t\tsource, err := initializer.NewInitializer(filePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tdbutil.CopyDBResources(source, server.db, false)\n\t\t}\n\t}\n\n\tm.Map(middleware.NewNobodyResourceService(manager.NobodyResourcePaths()))\n\n\tif config.GetBool(\"keystone/use_keystone\", false) {\n\t\tserver.keystoneIdentity, err = middleware.CreateIdentityServiceFromConfig(config)\n\t\tm.MapTo(server.keystoneIdentity, (*middleware.IdentityService)(nil))\n\t\tm.Use(middleware.Authentication())\n\t} else {\n\t\tm.MapTo(&middleware.NoIdentityService{}, (*middleware.IdentityService)(nil))\n\t\tauth := schema.NewAuthorizationBuilder().\n\t\t\tWithTenant(schema.Tenant{ID: \"admin\", Name: \"admin\"}).\n\t\t\tWithRoleIDs(\"admin\").\n\t\t\tBuildAdmin()\n\t\tm.Map(auth)\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid base dir: %s\", err)\n\t}\n\n\tif config.GetBool(\"profiling/enabled\", false) {\n\t\tserver.addPprofRoutes()\n\t}\n\tserver.addOptionsRoute()\n\tcors := config.GetString(\"cors\", \"\")\n\tif cors != \"\" {\n\t\tlog.Info(\"Enabling CORS for %s\", cors)\n\t\tif cors == \"*\" {\n\t\t\tlog.Warning(\"cors for * have security issue\")\n\t\t}\n\t\tserver.martini.Use(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\trw.Header().Add(\"Access-Control-Allow-Origin\", cors)\n\t\t\trw.Header().Add(\"Access-Control-Allow-Headers\", \"X-Auth-Token, Content-Type\")\n\t\t\trw.Header().Add(\"Access-Control-Expose-Headers\", \"X-Total-Count\")\n\t\t\trw.Header().Add(\"Access-Control-Allow-Methods\", \"GET,PUT,POST,DELETE\")\n\t\t})\n\t}\n\n\tdocumentRoot := config.GetString(\"document_root\", \"embed\")\n\tif config.GetBool(\"webui_config/enabled\", false) {\n\t\tm.Use(func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\t\tif req.URL.Path != \"/webui/config.json\" {\n\t\t\t\tc.Next()\n\t\t\t\treturn\n\t\t\t}\n\t\t\taddress := config.GetString(\"webui_config/address\", server.address)\n\t\t\tif address[0] == ':' {\n\t\t\t\taddress = \"__HOST__\" + address\n\t\t\t}\n\t\t\tbaseURL := \"http://\" + address\n\t\t\tauthURL := \"http://\" + address + \"/v2.0\"\n\t\t\tif config.GetBool(\"webui_config/tls\", config.GetBool(\"tls/enabled\", false)) {\n\t\t\t\tbaseURL = \"https://\" + address\n\t\t\t\tauthURL = \"https://\" + address + \"/v2.0\"\n\t\t\t}\n\t\t\tauthURL = config.GetString(\"webui_config/auth_url\", authURL)\n\t\t\twebUIConfig := map[string]interface{}{\n\t\t\t\t\"authUrl\": authURL,\n\t\t\t\t\"gohan\": map[string]interface{}{\n\t\t\t\t\t\"schema\": \"/gohan/v0.1/schemas\",\n\t\t\t\t\t\"url\": baseURL,\n\t\t\t\t},\n\t\t\t\t\"routes\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"path\": \"\",\n\t\t\t\t\t\t\"viewClass\": \"topView\",\n\t\t\t\t\t\t\"name\": \"top_view\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"errorMessages\": map[string]interface{}{\n\t\t\t\t\t\"tokenExpire\": \"The token is expired. Please re-login.\",\n\t\t\t\t},\n\t\t\t\t\"addingRelationDialog\": []interface{}{\n\t\t\t\t\t\"Pet\",\n\t\t\t\t},\n\t\t\t\t\"pageLimit\": 25,\n\t\t\t\t\"loginRequestTimeout\": 30000,\n\t\t\t\t\"extendTokenTime\": 300000,\n\t\t\t}\n\t\t\troutes.ServeJson(res, webUIConfig)\n\t\t})\n\t}\n\tif documentRoot == \"embed\" {\n\t\tm.Use(staticbin.Static(\"public\", util.Asset, staticbin.Options{\n\t\t\tSkipLogging: true,\n\t\t}))\n\t} else {\n\t\tlog.Info(\"Static file serving from %s\", documentRoot)\n\t\tdocumentRootABS, err := filepath.Abs(documentRoot)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserver.martini.Use(martini.Static(documentRootABS, martini.StaticOptions{\n\t\t\tSkipLogging: true,\n\t\t}))\n\t}\n\tserver.HealthCheck = healthcheck.NewHealthCheck(server.db, server.sync, server.address, config)\n\tserver.mapRoutes()\n\n\treturn server, nil\n}", "func newServer(handler connHandler, logger *zap.Logger) *server {\n\ts := &server{\n\t\thandler: handler,\n\t\tlogger: logger.With(zap.String(\"sector\", \"server\")),\n\t}\n\treturn s\n}", "func newServer(sc *ServerConfig, b backends.Backend, l log.Logger) (*server, error) {\n\tserver := &server{\n\t\tclientPool: NewPool(sc.MaxClients),\n\t\tclosedListener: make(chan bool, 1),\n\t\tlistenInterface: sc.ListenInterface,\n\t\tstate: ServerStateNew,\n\t\tenvelopePool: mail.NewPool(sc.MaxClients),\n\t}\n\tserver.logStore.Store(l)\n\tserver.backendStore.Store(b)\n\tlogFile := sc.LogFile\n\tif logFile == \"\" {\n\t\t// none set, use the same log file as mainlog\n\t\tlogFile = server.mainlog().GetLogDest()\n\t}\n\t// set level to same level as mainlog level\n\tmainlog, logOpenError := log.GetLogger(logFile, server.mainlog().GetLevel())\n\tserver.mainlogStore.Store(mainlog)\n\tif logOpenError != nil {\n\t\tserver.log().WithError(logOpenError).Errorf(\"Failed creating a logger for server [%s]\", sc.ListenInterface)\n\t}\n\n\tserver.setConfig(sc)\n\tserver.setTimeout(sc.Timeout)\n\tif err := server.configureSSL(); err != nil {\n\t\treturn server, err\n\t}\n\treturn server, nil\n}", "func newServer() *traceServer {\n\treturn &traceServer{\n\t\tevents: make(map[string]*trace.Trace),\n\t}\n}", "func NewServer(conf *Config, be *backend.Backend) (*Server, error) {\n\tauthInterceptor := interceptors.NewAuthInterceptor(be.Config.AuthWebhookURL)\n\tdefaultInterceptor := interceptors.NewDefaultInterceptor()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(\n\t\t\tauthInterceptor.Unary(),\n\t\t\tdefaultInterceptor.Unary(),\n\t\t\tgrpcprometheus.UnaryServerInterceptor,\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(\n\t\t\tauthInterceptor.Stream(),\n\t\t\tdefaultInterceptor.Stream(),\n\t\t\tgrpcprometheus.StreamServerInterceptor,\n\t\t)),\n\t}\n\n\tif conf.CertFile != \"\" && conf.KeyFile != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(conf.CertFile, conf.KeyFile)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t}\n\n\topts = append(opts, grpc.MaxConcurrentStreams(math.MaxUint32))\n\n\tyorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer(opts...)\n\thealthpb.RegisterHealthServer(grpcServer, health.NewServer())\n\tapi.RegisterYorkieServer(grpcServer, newYorkieServer(yorkieServiceCtx, be))\n\tapi.RegisterClusterServer(grpcServer, newClusterServer(be))\n\tgrpcprometheus.Register(grpcServer)\n\n\treturn &Server{\n\t\tconf: conf,\n\t\tgrpcServer: grpcServer,\n\t\tyorkieServiceCancel: yorkieServiceCancel,\n\t}, nil\n}", "func NewServer(config *Config, logger kitlog.Logger) *Server {\n\tdb := postgres.NewDB(&postgres.Config{\n\t\tConnStr: config.ConnStr,\n\t\tEncryptionPassword: config.EncryptionPassword,\n\t}, logger)\n\n\tds := datastore.NewDatastoreProtobufClient(\n\t\tconfig.DatastoreAddr,\n\t\t&http.Client{\n\t\t\tTimeout: time.Second * 10,\n\t\t},\n\t)\n\n\tmv := pipeline.NewMovingAverager(config.Verbose, clock.New(), logger)\n\n\tprocessor := pipeline.NewProcessor(ds, mv, config.Verbose, logger)\n\n\tmqttClient := mqtt.NewClient(logger, config.Verbose)\n\n\tenc := rpc.NewEncoder(&rpc.Config{\n\t\tDB: db,\n\t\tMQTTClient: mqttClient,\n\t\tProcessor: processor,\n\t\tVerbose: config.Verbose,\n\t\tBrokerAddr: config.BrokerAddr,\n\t\tBrokerUsername: config.BrokerUsername,\n\t}, logger)\n\n\thooks := twrpprom.NewServerHooks(registry.DefaultRegisterer)\n\n\tbuildInfo.WithLabelValues(version.BinaryName, version.Version, version.BuildDate)\n\n\tlogger = kitlog.With(logger, \"module\", \"server\")\n\tlogger.Log(\n\t\t\"msg\", \"creating server\",\n\t\t\"datastore\", config.DatastoreAddr,\n\t\t\"mqttBroker\", config.BrokerAddr,\n\t\t\"listenAddr\", config.ListenAddr,\n\t\t\"mqttUsername\", config.BrokerAddr,\n\t)\n\n\ttwirpHandler := encoder.NewEncoderServer(enc, hooks)\n\n\t// multiplex twirp handler into a mux with our other handlers\n\tmux := goji.NewMux()\n\n\tmux.Handle(pat.Post(encoder.EncoderPathPrefix+\"*\"), twirpHandler)\n\tmux.Handle(pat.Get(\"/pulse\"), PulseHandler(db))\n\tmux.Handle(pat.Get(\"/metrics\"), promhttp.Handler())\n\n\tmux.Use(middleware.RequestIDMiddleware)\n\n\tmetricsMiddleware := middleware.MetricsMiddleware(\"decode\", \"encoder\", registry.DefaultRegisterer)\n\tmux.Use(metricsMiddleware)\n\n\t// create our http.Server instance\n\tsrv := &http.Server{\n\t\tAddr: config.ListenAddr,\n\t\tHandler: mux,\n\t}\n\n\t// return the instantiated server\n\treturn &Server{\n\t\tsrv: srv,\n\t\tencoder: enc,\n\t\tdb: db,\n\t\tmqtt: mqttClient,\n\t\tlogger: kitlog.With(logger, \"module\", \"server\"),\n\t\tdomains: config.Domains,\n\t}\n}", "func NewServer(endpoint string) (*Server, error) {\n\n\tret := &Server{}\n\tvar err error\n\tret.Listener, err = net.Listen(\"tcp\", endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret.mux = http.NewServeMux()\n\tret.mux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"This is the monitoring endpoint\"))\n\t})\n\tret.mux.Handle(\"/mon/varz\", expvar.Handler())\n\n\tret.mux.HandleFunc(\"/mon/pprof/\", pprof.Index)\n\tret.mux.HandleFunc(\"/mon/pprof/cmdline\", pprof.Cmdline)\n\tret.mux.HandleFunc(\"/mon/pprof/profile\", pprof.Profile)\n\tret.mux.HandleFunc(\"/mon/pprof/symbol\", pprof.Symbol)\n\tEnableTracing()\n\tret.mux.HandleFunc(\"/mon/trace\", TraceHandler())\n\tret.srv = &http.Server{}\n\treturn ret, nil\n}", "func newPprofHandler(svr *server.Server, rd *render.Render) *pprofHandler {\n\treturn &pprofHandler{\n\t\tsvr: svr,\n\t\trd: rd,\n\t}\n}", "func NewServer(config *config.Config, metrics *metrics.Metrics) (server Server) {\n\tif config == nil {\n\t\tlog.Fatalf(\"error: config cannot be nil value.\")\n\t}\n\n\tserver.Log = config.Log\n\tserver.ListenPort = config.Server.ListenPort\n\tserver.CacheFolder = config.Server.CacheFolder\n\tserver.MetricsListenPort = config.Server.MetricsListenPort\n\n\tif config.Server.CacheResponse {\n\t\tserver.EnableCache(config.Server.CacheFolder, config.Server.CacheKey)\n\t}\n\n\tserver.Context = config.Context\n\tserver.Router = chi.NewRouter()\n\tserver.HTTP = &http.Server{Addr: \":\" + server.ListenPort, Handler: server.Router}\n\n\t// server.HTTP = &http.Server{\n\t// \tAddr: \":\" + server.ListenPort,\n\t// \tRouter: server.Router,\n\t// \t// Ian Kent recommends these timeouts be set:\n\t// \t// https://www.youtube.com/watch?v=YF1qSfkDGAQ&t=333s\n\t// \tIdleTimeout: time.Duration(time.Second), // This one second timeout may be too aggressive..*shrugs* :)\n\t// \tReadTimeout: time.Duration(time.Second),\n\t// \tWriteTimeout: time.Duration(time.Second),\n\t// }\n\n\tserver.DB = db.NewSimpleDB()\n\tserver.Metrics = metrics\n\treturn\n}", "func NewServer(config domain.ServerConfig) *Server {\n\tdebugger := logger.New(log.New(ioutil.Discard, \"\", 0))\n\tif config.Debug {\n\t\tdebugger = logger.New(log.New(os.Stderr, \"[debug] \", log.Flags()|log.Lshortfile))\n\t}\n\n\tdb, err := bolt.Open(config.BoltPath, 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start bolt db\")\n\t}\n\tdefer db.Close()\n\n\ts := &Server{\n\t\tConfig: config,\n\t\ti: uc.NewInteractor(\n\t\t\tconfig,\n\t\t\tcookies.New(config.CookieAge),\n\t\t\tdebugger,\n\t\t\tresources.New(encoder.New()),\n\t\t\thttpCaller.New(),\n\t\t\tmail.New(domain.EmailConfig{}),\n\t\t\tpathInfo.New(config),\n\t\t\tencoder.New(),\n\t\t\tsparql.New(),\n\t\t\tpages.New(config.DataRoot),\n\t\t\ttokenStorer.New(db),\n\t\t\tdomain.URIHandler{},\n\t\t\tuuid.New(),\n\t\t\tauthentication.New(httpCaller.New()),\n\t\t\tspkac.New(),\n\t\t),\n\t\tlogger: debugger,\n\t\tcookieManager: cookies.New(config.CookieAge),\n\t\tpathInformer: pathInfo.New(config),\n\t\turiManipulator: domain.URIHandler{},\n\t}\n\n\tmime.AddRDFExtension(s.Config.ACLSuffix)\n\tmime.AddRDFExtension(s.Config.MetaSuffix)\n\n\ts.logger.Debug(\"---- starting server ----\")\n\ts.logger.Debug(\"config: %#v\\n\", s.Config)\n\treturn s\n}", "func NewServer(addr,user, password string) (*HttpServer, error) {\n\tdb := pg.Connect(&pg.Options{\n\t\tAddr: addr,\n\t\tPassword: password,\n\t\tUser: user,\n\t})\n\t_, err := db.Exec(\"SELECT 1\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcron := cron.New()\n\treturn &HttpServer{\n\t\tdb: db,\n\t\tcron: cron,\n\t\trouter: httprouter.New(),\n\t}, nil\n}", "func NewServer() *Server {\n return &Server{\n Addr: DefaultAddr,\n }\n}", "func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {\n\tvalidator := new(Validator)\n\tfor _, user := range config.Users {\n\t\tu, err := user.ToMemoryUser()\n\t\tif err != nil {\n\t\t\treturn nil, newError(\"failed to get trojan user\").Base(err).AtError()\n\t\t}\n\n\t\tif err := validator.Add(u); err != nil {\n\t\t\treturn nil, newError(\"failed to add user\").Base(err).AtError()\n\t\t}\n\t}\n\n\tv := core.MustFromContext(ctx)\n\tserver := &Server{\n\t\tpolicyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),\n\t\tvalidator: validator,\n\t}\n\n\tif config.Fallbacks != nil {\n\t\tserver.fallbacks = make(map[string]map[string]*Fallback)\n\t\tfor _, fb := range config.Fallbacks {\n\t\t\tif server.fallbacks[fb.Alpn] == nil {\n\t\t\t\tserver.fallbacks[fb.Alpn] = make(map[string]*Fallback)\n\t\t\t}\n\t\t\tserver.fallbacks[fb.Alpn][fb.Path] = fb\n\t\t}\n\t\tif server.fallbacks[\"\"] != nil {\n\t\t\tfor alpn, pfb := range server.fallbacks {\n\t\t\t\tif alpn != \"\" { // && alpn != \"h2\" {\n\t\t\t\t\tfor path, fb := range server.fallbacks[\"\"] {\n\t\t\t\t\t\tif pfb[path] == nil {\n\t\t\t\t\t\t\tpfb[path] = fb\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn server, nil\n}", "func NewServer(listen string, port int, metrics bool) (*Server, error) {\n\n\tr := gin.Default()\n\tif metrics {\n\t\tp := ginprom.New(\n\t\t\tginprom.Engine(r),\n\t\t\tginprom.Subsystem(\"gin\"),\n\t\t\tginprom.Path(\"/metrics\"),\n\t\t)\n\t\tr.Use(p.Instrument())\n\t}\n\n\ts := &Server{\n\t\trouter: r,\n\t\tport: port,\n\t\tlisten: listen,\n\t}\n\ts.routes()\n\treturn s, nil\n}", "func NewServer(cfg *config.Config) (*Server, error) {\n\tvar rpt report.Reporter\n\tvar err error\n\tswitch cfg.Report {\n\tcase \"http\":\n\t\trpt, err = report.NewHttpReport(&cfg.Http)\n\tcase \"database\":\n\t\trpt, err = report.NewSqlReporter(&cfg.DB)\n\tdefault:\n\t\terr = errors.New(fmt.Sprintf(\"unspport %v\", cfg.Report))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Server{cfg.TCP.Ports, rpt}, nil\n}", "func newServer(deps dependencies) Component {\n\treturn newServerCompat(deps.Config, deps.Log, deps.Replay, deps.Debug, deps.Params.Serverless)\n}", "func newServer(config Config) *http.Server {\n\treturn &http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.Port),\n\t\tHandler: newRouter(config),\n\t}\n}", "func (metricsServer PrometheusMetricServer) NewServer(address string, pattern string) {\n\thttp.HandleFunc(\"/healthz\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"OK\"))\n\t})\n\tlog.Printf(\"Starting metrics server at %v\", address)\n\thttp.Handle(pattern, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))\n\n\t// initialize the total error metric\n\tscalerErrorsTotal.GetMetricWith(prometheus.Labels{})\n\n\tlog.Fatal(http.ListenAndServe(address, nil))\n}", "func NewServer(t *testing.T, dbc *sql.DB) (*server.Server, string) {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tjtest.RequireNil(t, err)\n\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(interceptors.UnaryServerInterceptor),\n\t\tgrpc.StreamInterceptor(interceptors.StreamServerInterceptor))\n\n\tsrv := server.New(dbc, dbc)\n\n\tpb.RegisterGokuServer(grpcServer, srv)\n\n\tgo func() {\n\t\terr := grpcServer.Serve(l)\n\t\tjtest.RequireNil(t, err)\n\t}()\n\n\treturn srv, l.Addr().String()\n}", "func NewServer() *Server {\n\ttr := make(chan TimingReport)\n\ts := &Server{\n\t\ttr,\n\t}\n\tgo s.MonitorTimingReports()\n\treturn s\n}", "func NewServer(cfg config.Config, ll *log.Logger) *Server {\n\tif ll == nil {\n\t\tll = log.New(ioutil.Discard, \"\", 0)\n\t}\n\n\t// Set up Prometheus instrumentation using the typical Go collectors.\n\treg := prometheus.NewPedanticRegistry()\n\treg.MustRegister(\n\t\tprometheus.NewGoCollector(),\n\t\tprometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),\n\t\tnewInterfaceCollector(cfg.Interfaces),\n\t)\n\n\treturn &Server{\n\t\tcfg: cfg,\n\n\t\tll: ll,\n\t\treg: reg,\n\n\t\tready: make(chan struct{}),\n\t}\n}", "func New(addr string) *Server {\n if addr == \"\" {\n addr = DefaultAddr\n }\n return &Server{\n addr: DefaultAddr,\n ds: newDataStore(),\n done: make(chan struct{}),\n }\n}", "func newServer(notifier *notifier, key string) *server {\n\treturn &server{\n\t\tnotifier: notifier,\n\t\tkey: key,\n\t}\n}", "func NewServer( /* db *Database */ ) *Server {\n\trouter := httprouter.New()\n\tserver := &Server{\n\t\trouter: router,\n\t\t//TODO\tdb: db,\n\t}\n\n\t// initialize cache\n\tnodes = make(map[string]NodeMetrics)\n\n\tserver.setupRoutes()\n\treturn server\n}", "func newGoplsServer(name string) (servertest.Connector, error) {\n\tif *goplsPath != \"\" && *goplsCommit != \"\" {\n\t\tpanic(\"can't set both -gopls_path and -gopls_commit\")\n\t}\n\tvar (\n\t\tgoplsPath = *goplsPath\n\t\tenv []string\n\t)\n\tif *goplsCommit != \"\" {\n\t\tgoplsPath = getInstalledGopls()\n\t}\n\tif goplsPath == \"\" {\n\t\tvar err error\n\t\tgoplsPath, err = os.Executable()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv = []string{fmt.Sprintf(\"%s=true\", runAsGopls)}\n\t}\n\tvar args []string\n\tif *cpuProfile != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-profile.cpu=%s\", name+\".\"+*cpuProfile))\n\t}\n\tif *memProfile != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-profile.mem=%s\", name+\".\"+*memProfile))\n\t}\n\tif *allocProfile != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-profile.alloc=%s\", name+\".\"+*allocProfile))\n\t}\n\tif *trace != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-profile.trace=%s\", name+\".\"+*trace))\n\t}\n\treturn &SidecarServer{\n\t\tgoplsPath: goplsPath,\n\t\tenv: env,\n\t\targs: args,\n\t}, nil\n}", "func newServer(a *Air) *server {\n\treturn &server{\n\t\ta: a,\n\t\tserver: &http.Server{},\n\t\taddressMap: map[string]int{},\n\t\trequestPool: &sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &Request{}\n\t\t\t},\n\t\t},\n\t\tresponsePool: &sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn &Response{}\n\t\t\t},\n\t\t},\n\t}\n}", "func NewServer(config Config) (*Server, error) {\n\tserver := &Server{\n\t\tstartTime: time.Now(),\n\t\tConfig: config,\n\t\ttcpServers: []*healthApi.Server{},\n\t\tconnectivity: &healthReport{},\n\t}\n\n\tswaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !config.Passive {\n\t\tcl, err := ciliumPkg.NewClient(config.CiliumURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tserver.Client = cl\n\t\tserver.Server = *server.newServer(swaggerSpec, 0)\n\t}\n\tfor port := range PortToPaths {\n\t\tsrv := server.newServer(swaggerSpec, port)\n\t\tserver.tcpServers = append(server.tcpServers, srv)\n\t}\n\n\treturn server, nil\n}", "func NewServer(newStorageClient NewStorageClientFunc, blockSizeLimit uint64) *Server {\n\treturn &Server{newStorageClient, blockSizeLimit, make(map[string]bool)}\n}", "func NewServer(ctx interface{}) (*Server, error) {\n\tif ctx == nil {\n\t\treturn nil, fmt.Errorf(\"rpc: ctx is nil\")\n\t}\n\tctxType := reflect.TypeOf(ctx)\n\tif ctxType.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"rpc: ctx is not pointer\")\n\t}\n\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t\tctxType: ctxType.Elem(),\n\t}, nil\n}", "func ServePprof() {\n\tgo servePprof()\n}", "func newGRPCServer(ctx context.Context, cfg *config.ServerConfig, authCtx interfaces.AuthenticationContext,\n\topts ...grpc.ServerOption) (*grpc.Server, error) {\n\t// Not yet implemented for streaming\n\tvar chainedUnaryInterceptors grpc.UnaryServerInterceptor\n\tif cfg.Security.UseAuth {\n\t\tlogger.Infof(ctx, \"Creating gRPC server with authentication\")\n\t\tchainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor,\n\t\t\tauth.GetAuthenticationCustomMetadataInterceptor(authCtx),\n\t\t\tgrpcauth.UnaryServerInterceptor(auth.GetAuthenticationInterceptor(authCtx)),\n\t\t\tauth.AuthenticationLoggingInterceptor,\n\t\t\tblanketAuthorization,\n\t\t)\n\t} else {\n\t\tlogger.Infof(ctx, \"Creating gRPC server without authentication\")\n\t\tchainedUnaryInterceptors = grpc_middleware.ChainUnaryServer(grpcPrometheus.UnaryServerInterceptor)\n\t}\n\n\tserverOpts := []grpc.ServerOption{\n\t\tgrpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor),\n\t\tgrpc.UnaryInterceptor(chainedUnaryInterceptors),\n\t}\n\tserverOpts = append(serverOpts, opts...)\n\tgrpcServer := grpc.NewServer(serverOpts...)\n\tgrpcPrometheus.Register(grpcServer)\n\tflyteService.RegisterAdminServiceServer(grpcServer, adminservice.NewAdminServer(cfg.KubeConfig, cfg.Master))\n\tif cfg.Security.UseAuth {\n\t\tflyteService.RegisterAuthMetadataServiceServer(grpcServer, authCtx.AuthMetadataService())\n\t\tflyteService.RegisterIdentityServiceServer(grpcServer, authCtx.IdentityService())\n\t}\n\n\thealthServer := health.NewServer()\n\thealthServer.SetServingStatus(\"\", grpc_health_v1.HealthCheckResponse_SERVING)\n\tgrpc_health_v1.RegisterHealthServer(grpcServer, healthServer)\n\n\tif cfg.GrpcServerReflection {\n\t\treflection.Register(grpcServer)\n\t}\n\treturn grpcServer, nil\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tk8sAPI *k8s.API,\n\tshutdown <-chan struct{},\n) *grpc.Server {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\tendpoints := watcher.NewEndpointsWatcher(k8sAPI, log)\n\tprofiles := watcher.NewProfileWatcher(k8sAPI, log)\n\ttrafficSplits := watcher.NewTrafficSplitWatcher(k8sAPI, log)\n\n\tsrv := server{\n\t\tendpoints,\n\t\tprofiles,\n\t\ttrafficSplits,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\t// controller/discovery.Discovery (controller-facing)\n\tdiscoveryPb.RegisterDiscoveryServer(s, &srv)\n\treturn s\n}", "func NewServer(opt ...Option) Server {\r\n\treturn newRpcServer(opt...)\r\n}", "func CreateServer(port string, systemConfig SystemConfig) *http.Server {\n\thttp.HandleFunc(\"/getpfs\", func(w http.ResponseWriter, r *http.Request) {\n\t\tpfs, err := getNodeData(systemConfig)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"ERROR: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tdata, err := json.Marshal(pfs)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"ERROR: failed to marshal pfs: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Fprintf(w, \"%s\", data)\n\t})\n\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, message, version)\n\t})\n\n\tserver := &http.Server{Addr: fmt.Sprintf(\":%s\", port), Handler: nil}\n\n\tlog.Println(\"Starting Server on port: \" + port)\n\treturn server\n}", "func NewServer(config *ServerConfig) (*Server, errors.Error) {\n\tengine := gin.New()\n\tserver := &Server{*config, engine, nil, make(map[string]Service, 0)}\n\n\t// global middlewares\n\tengine.Use(ginLogger)\n\n\t// metrics\n\tp := ginprometheus.NewPrometheus(config.SubSystemName)\n\tp.ReqCntURLLabelMappingFn = func(c *gin.Context) string {\n\t\turl := c.Request.URL.String()\n\t\tfor _, p := range c.Params {\n\t\t\tif p.Key == \"id\" {\n\t\t\t\turl = strings.Replace(url, p.Value, \":id\", 1)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn url\n\t}\n\tp.Use(engine)\n\n\t// server specific routes\n\tengine.GET(\"/healthz\", server.handleGetHealthz)\n\tengine.GET(\"/readiness\", server.handleGetReadiness)\n\n\treturn server, nil\n}", "func NewServer(cfg config.HTTP, staticResource bool, r *linmetric.Registry) Server {\n\ts := &server{\n\t\tcfg: cfg,\n\t\taddr: fmt.Sprintf(\":%d\", cfg.Port),\n\t\tgin: gin.New(),\n\t\tstaticResource: staticResource,\n\t\tserver: http.Server{\n\t\t\t// use extra timeout for ingestion and query timeout\n\t\t\t// if write timeout will return ERR_EMPTY_RESPONSE, chrome will does auto retry.\n\t\t\t// https://www.bennadel.com/blog/3257-google-chrome-will-automatically-retry-requests-on-certain-error-responses.htm\n\t\t\t// https://mariocarrion.com/2021/09/17/golang-software-architecture-resilience-http-servers.html\n\t\t\t// WriteTimeout: cfg.WriteTimeout.Duration(),\n\t\t\tReadTimeout: cfg.ReadTimeout.Duration(),\n\t\t\tIdleTimeout: cfg.IdleTimeout.Duration(),\n\t\t},\n\t\tr: r,\n\t\tlogger: logger.GetLogger(\"HTTP\", \"Server\"),\n\t}\n\ts.init()\n\treturn s\n}", "func newTestServer(logStore logstore.LogStore) *HTTPServer {\n\t// note: address doesn't matter since we will use httptest server\n\tserver := NewHTTP(&Config{BindAddress: \"127.0.0.1:8080\"}, logStore)\n\treturn server\n}", "func NewServer(conn *grpc.ClientConn) *Server {\n\treturn &Server{\n\t\ttopoConn: conn,\n\t\tclients: make(map[uint32]*webClient),\n\t}\n}", "func createHttpService(port int) {\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"/debug/pprof/\", pprof.Index)\n\thttpMux.HandleFunc(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\thttpMux.HandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\thttpMux.HandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\thttpMux.HandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n\thttpMux.HandleFunc(\"/check\", check)\n\n\thttpMux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`hello`))\n\t})\n\n\t// test stat prometheus\n\thttpMux.HandleFunc(\"/test\", testStat)\n\n\t// add prometheus metrics handler\n\thttpMux.Handle(\"/metrics\", promhttp.Handler())\n\n\t// http server\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Println(\"PProf exec recover: \", err)\n\t\t\t}\n\t\t}()\n\n\t\tlog.Println(\"server PProf run on: \", port)\n\n\t\tif err := http.ListenAndServe(fmt.Sprintf(\"0.0.0.0:%d\", port), httpMux); err != nil {\n\t\t\tlog.Println(\"PProf listen error: \", err)\n\t\t}\n\n\t}()\n}", "func NewRPCServer(config *config.Config, dom *domain.Domain, sm util.SessionManager) *grpc.Server {\n\tdefer func() {\n\t\tif v := recover(); v != nil {\n\t\t\tlogutil.BgLogger().Error(\"panic in TiDB RPC server\", zap.Reflect(\"r\", v),\n\t\t\t\tzap.Stack(\"stack trace\"))\n\t\t}\n\t}()\n\n\ts := grpc.NewServer(\n\t\tgrpc.KeepaliveParams(keepalive.ServerParameters{\n\t\t\tTime: time.Duration(config.Status.GRPCKeepAliveTime) * time.Second,\n\t\t\tTimeout: time.Duration(config.Status.GRPCKeepAliveTimeout) * time.Second,\n\t\t}),\n\t\tgrpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{\n\t\t\t// Allow clients send consecutive pings in every 5 seconds.\n\t\t\t// The default value of MinTime is 5 minutes,\n\t\t\t// which is too long compared with 10 seconds of TiDB's keepalive time.\n\t\t\tMinTime: 5 * time.Second,\n\t\t}),\n\t\tgrpc.MaxConcurrentStreams(uint32(config.Status.GRPCConcurrentStreams)),\n\t\tgrpc.InitialWindowSize(int32(config.Status.GRPCInitialWindowSize)),\n\t\tgrpc.MaxSendMsgSize(config.Status.GRPCMaxSendMsgSize),\n\t)\n\trpcSrv := &rpcServer{\n\t\tDiagnosticsServer: sysutil.NewDiagnosticsServer(config.Log.File.Filename),\n\t\tdom: dom,\n\t\tsm: sm,\n\t}\n\tdiagnosticspb.RegisterDiagnosticsServer(s, rpcSrv)\n\ttikvpb.RegisterTikvServer(s, rpcSrv)\n\ttopsql.RegisterPubSubServer(s)\n\treturn s\n}", "func newServer(ctx context.Context, dexDir string, port int32, environment string, ldap *ldaptest.TestLDAP) (*TestDex, error) {\n\tcertFile, keyFile := ssltest.CreateCertificates(\"localhost\", dexDir)\n\treturn newServerWithTLS(ctx, certFile, keyFile, port, environment, ldap)\n}", "func NewServer(isDebug bool) *Server {\n\tdebug = isDebug\n\ts := &Server{\n\t\tclients: cmap.New(),\n\t\tprefixes: make(map[string]prefixMap),\n\t\trpcHandlers: make(map[string]RPCHandler),\n\t\tsubHandlers: make(map[string]SubHandler),\n\t\tpubHandlers: make(map[string]PubHandler),\n\t\tsubscriptions: make(map[string]listenerMap),\n\t\tsubLock: new(sync.Mutex),\n\t}\n\ts.Server = websocket.Server{\n\t\tHandshake: checkWAMPHandshake,\n\t\tHandler: websocket.Handler(s.HandleWebsocket),\n\t}\n\treturn s\n}", "func NewServer(c Config) (*Server, error) {\n\tswitch {\n\tcase c.ZKTagsPrefix == \"\":\n\t\tfallthrough\n\tcase c.ReadReqRate < 1:\n\t\tfallthrough\n\tcase c.WriteReqRate < 1:\n\t\treturn nil, errors.New(\"invalid configuration parameter(s)\")\n\t}\n\n\trrt, _ := NewRequestThrottle(RequestThrottleConfig{\n\t\tCapacity: 10,\n\t\tRate: c.ReadReqRate,\n\t})\n\n\twrt, _ := NewRequestThrottle(RequestThrottleConfig{\n\t\tCapacity: 10,\n\t\tRate: c.WriteReqRate,\n\t})\n\n\ttcfg := TagHandlerConfig{\n\t\tPrefix: c.ZKTagsPrefix,\n\t}\n\n\tth, _ := NewTagHandler(tcfg)\n\tif c.test {\n\t\tth.Store = newzkTagStorageMock()\n\t}\n\n\treturn &Server{\n\t\tHTTPListen: c.HTTPListen,\n\t\tGRPCListen: c.GRPCListen,\n\t\tTags: th,\n\t\treadReqThrottle: rrt,\n\t\twriteReqThrottle: wrt,\n\t\ttest: c.test,\n\t}, nil\n}", "func NewServer(config *Config, serverConfig *ServerConfig) *Server {\n\tformat := serverConfig.Format\n\tif format == nil {\n\t\tformat = config.DefaultFormat\n\t}\n\n\tserver := &Server{\n\t\tid: serverConfig.ID,\n\t\tlock: sync.Mutex{},\n\t\tstopper: gstop.New(),\n\t\tformat: format,\n\t\trouters: make(map[int64]*Router, defaultMapSize),\n\t\tworkers: make(map[string]*worker, defaultMapSize),\n\t}\n\n\tif existsServer, ok := serverDB[server.id]; ok {\n\t\t_ = existsServer.Stop()\n\n\t\tdelete(serverDB, server.id)\n\t}\n\n\tserverDB[server.id] = server\n\n\tserver.initial(config, serverConfig)\n\n\treturn server\n}", "func NewServer(config *ServerConfig) *Server {\n\tserver := &Server{\n\t\tdnsOrIpaddr: config.DNSOrIPAddr,\n\t\tport: config.Port,\n\t\tcompletedLongTTL: config.LongTrim,\n\t\tcompletedAckTrim: config.ShortTrim,\n\t\tdeadlineIO: config.DeadlineIO,\n\t\tkeepAlivePeriod: config.KeepAlivePeriod,\n\t\tdontStartTrimmers: config.dontStartTrimmers,\n\t\tlogger: config.Logger,\n\t\ttlsCertificate: config.TLSCertificate}\n\tif server.logger == nil {\n\t\tvar logBuf bytes.Buffer\n\t\tserver.logger = log.New(&logBuf, \"\", 0)\n\t}\n\tserver.svrMap = make(map[string]*methodArgs)\n\tserver.perClientInfo = make(map[uint64]*clientInfo)\n\tserver.completedTickerDone = make(chan bool)\n\tserver.connections = list.New()\n\n\treturn server\n}", "func DevSession_NewServer(s DevSession_Server) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(DevSession_Methods(nil, s), s, c)\n}", "func NewServer(addr string, n http.Handler) (Server, error) {\n\tconf := ServerConfig{\n\t\tTimeout: time.Minute,\n\t\tHandler: n,\n\t\tAddress: addr,\n\t}\n\n\treturn conf.Resolve()\n}", "func NewServer(authFunc, cmdFunc func(io.ReadWriter, []byte) error) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.ln, err = nettest.NewLocalListener(\"tcp\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.serve(authFunc, cmdFunc)\n\treturn s, nil\n}", "func NewServer(conf config.Config) *Server {\n\tlog := logrus.New()\n\tif conf.Debug {\n\t\tlog.SetLevel(logrus.DebugLevel)\n\t}\n\tserver := &Server{\n\t\tconf: conf,\n\t\trouter: chi.NewRouter(),\n\t\troomManager: rooms.NewManager(log),\n\t\tlog: log,\n\t}\n\n\tr := server.router\n\t// A good base middleware stack\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.RealIP)\n\tr.Use(middleware.Logger)\n\tr.Use(middleware.Recoverer)\n\n\tr.Handle(\"/metrics\", promhttp.Handler())\n\tr.Get(\"/rooms/{roomName}/websocket\", server.websocketHandler)\n\tr.Group(func(r chi.Router) {\n\t\t// set timeout for non classic http calls\n\t\tr.Use(middleware.Timeout(60 * time.Second))\n\t\tserver.mountRestRoutes(r)\n\t\tserver.mountFileRoutes(r)\n\n\t})\n\n\treturn server\n}", "func NewServer(c *Carts) *Server {\n\treturn &Server{carts: c}\n}", "func NewServer(svc Service, config *Config) *Server {\n\tif !config.Debug {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\tserver := &Server{\n\t\tRoutes: initializeRoutes(\n\t\t\t!config.AuthDisabled,\n\t\t\tconfig.TokenURL,\n\t\t\tconfig.Tracer,\n\t\t),\n\t\tservice: svc,\n\t\tconfig: config,\n\t\tTitle: \"Cluster Registry\",\n\t\tVersion: \"0.0.1\",\n\t\tauthDisabled: config.AuthDisabled,\n\t}\n\n\t// enable pprof http endpoints in debug mode\n\tif config.Debug {\n\t\tpprof.Register(server.Routes.Engine)\n\t}\n\n\t// set logrus logger to TextFormatter with no colors\n\tlog.SetFormatter(&log.TextFormatter{DisableColors: true})\n\n\tserver.server = &http.Server{\n\t\tAddr: config.Address,\n\t\tHandler: server.Routes.Engine,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t}\n\n\tserver.serviceHealthyFn = svc.Healthy\n\n\tif !config.WellKnownDisabled {\n\t\tserver.Routes.configureWellKnown(server.isHealthy)\n\t}\n\n\t// configure healthz endpoint\n\tserver.Routes.GET(\"/healthz\", healthHandler(server.isHealthy))\n\n\treturn server\n}", "func NewServer() *server {\n\ts := &server{\n\t\tstore: make(map[string]*string),\n\t\tops: make(chan func()),\n\t}\n\tgo s.loop()\n\treturn s\n}", "func New(basepath string, addr []string) *Server {\n\ts := server.NewServer()\n\tstore := make(map[string]fn)\n\n\tbasepath = strings.Trim(basepath, \"/\")\n\tbasepath = \"/\" + basepath\n\n\treturn &Server{store, s, basepath, addr, ModeDebug}\n}", "func newRPCServerService() (*rpcServerService, error) {\n return &rpcServerService{serviceMap: util.NewSyncMap()}, nil\n}", "func createServer() {\n\tlistener := createServerListener()\n\tserver := Server{}\n\tgrpcServer := grpc.NewServer()\n\tRegisterAccountServer(grpcServer, &server)\n\tstartServer(grpcServer, listener)\n}", "func NewServer(conf *config.Config, projectClient project.Client, entriesClient timetracking.Client) *Server {\n\te := echo.New()\n\n\t//recover from panics\n\te.Use(middleware.Recover())\n\t//add a unique id to each request\n\te.Use(middleware.RequestID())\n\t//add request id to the context\n\te.Use(AddRequestIDToContext())\n\t//add a logger to the context\n\te.Use(AddLoggerToContext())\n\t//use custom logger for all requests\n\te.Use(Logger())\n\t//trace rest calls\n\te.Use(Tracing())\n\n\te.Use(Instrumenting())\n\n\te.HideBanner = true\n\te.HidePort = true\n\n\ts := &Server{\n\t\tconf: conf,\n\t\te: e,\n\t\thttpServer: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", conf.HTTPPort),\n\t\t\tReadTimeout: 60 * time.Second, // time to read request\n\t\t\tReadHeaderTimeout: 10 * time.Second, // time to read header, low value to cope with malicious behavior\n\t\t\tWriteTimeout: 20 * time.Second, // time write response\n\t\t\tIdleTimeout: 120 * time.Second, // time between keep-alives requests before connection is closed\n\t\t},\n\t}\n\n\th := &handler{\n\t\tentries: entriesClient,\n\t\tprojects: projectClient,\n\t}\n\n\ts.AddRoutes(h)\n\n\t//serve SPA\n\te.Static(\"/\", \"web\")\n\n\treturn s\n}", "func NewServer() Server {\n\treturn Server{\n\t\tport: \"5000\",\n\t\tserver: gin.Default(),\n\t}\n}", "func NewServer() *negroni.Negroni {\n\n formatter := render.New(render.Options{\n IndentJSON: true,\n })\n\n n := negroni.Classic()\n mx := mux.NewRouter()\n\n initRoutes(mx, formatter)\n\n n.UseHandler(mx)\n return n\n}", "func NewServer() *negroni.Negroni {\n\n formatter := render.New(render.Options{\n IndentJSON: true,\n })\n\n n := negroni.Classic()\n mx := mux.NewRouter()\n\n initRoutes(mx, formatter)\n\n n.UseHandler(mx)\n return n\n}", "func newServerConfig(fname, id, name, passWord, serverKey string) (err error) {\n\tconfig := Config{\n\t\tid,\n\t\tname,\n\t\t\"server\",\n\t\tpassWord,\n\t\tserverKey,\n\t\tDEFAULT_SERVER_URL,\n\t\tDEFAULT_PROCESS_USER,\n\t\tDEFAULT_PROCESS_LOCK,\n\t\tDEFAULT_PROCESS_LOG,\n\t\tDEFAULT_BASE_DIR,\n\t\tDEFAULT_DATA_DIR,\n\t\tDEFAULT_HTTP_LISTEN,\n\t\tfname,\n\t}\n\n\treturn SaveConfig(config)\n}", "func NewServer() *negroni.Negroni {\n\tfmt.Println(\"new server\")\n\tformatter := render.New(render.Options{\n\t\tIndentJSON: true,\n\t})\n\n\tn := negroni.Classic()\n\tmx := mux.NewRouter()\n\t//初始化路由\n\tinitRoutes(mx, formatter)\n\n\tn.UseHandler(mx)\n\treturn n\n}", "func newServerMetrics() (*serverMetrics, error) {\n\tsm := &serverMetrics{\n\t\tconnections: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"connections\",\n\t\t\t\tHelp: \"Number of currently opened connection to proxy peer clients.\",\n\t\t\t},\n\t\t\t[]string{\"local_id\", \"remote_id\", \"state\"},\n\t\t),\n\n\t\trpcs: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc\",\n\t\t\t\tHelp: \"Number of current server RPC requests.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"method\"},\n\t\t),\n\n\t\trpcTotal: prometheus.NewCounterVec(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc_total\",\n\t\t\t\tHelp: \"Total number of server RPC requests.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"method\", \"code\"},\n\t\t),\n\n\t\trpcDuration: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"rpc_duration_seconds\",\n\t\t\t\tHelp: \"Duration in seconds of RPCs sent by the server.\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\", \"code\"},\n\t\t),\n\n\t\tmessageSent: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"message_sent_size\",\n\t\t\t\tHelp: \"Size of messages sent by the server.\",\n\t\t\t\tBuckets: messageByteBuckets,\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\"},\n\t\t),\n\n\t\tmessageReceived: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: \"proxy_peer\",\n\t\t\t\tSubsystem: \"server\",\n\t\t\t\tName: \"message_received_size\",\n\t\t\t\tHelp: \"Size of messages received by the server.\",\n\t\t\t\tBuckets: messageByteBuckets,\n\t\t\t},\n\t\t\t[]string{\"service\", \"handler\"},\n\t\t),\n\t}\n\n\tif err := metrics.RegisterPrometheusCollectors(\n\t\tsm.connections,\n\t\tsm.rpcs,\n\t\tsm.rpcTotal,\n\t\tsm.rpcDuration,\n\t\tsm.messageSent,\n\t\tsm.messageReceived,\n\t); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn sm, nil\n}", "func newServer(listenAddrs []string, notifier chainntnfs.ChainNotifier,\n\tbio lnwallet.BlockChainIO, fundingSigner lnwallet.MessageSigner,\n\twallet *lnwallet.LightningWallet, chanDB *channeldb.DB) (*server, error) {\n\n\tprivKey, err := wallet.GetIdentitykey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivKey.Curve = btcec.S256()\n\n\tlisteners := make([]net.Listener, len(listenAddrs))\n\tfor i, addr := range listenAddrs {\n\t\tlisteners[i], err = brontide.NewListener(privKey, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tserializedPubKey := privKey.PubKey().SerializeCompressed()\n\ts := &server{\n\t\tlnwallet: wallet,\n\t\tbio: bio,\n\t\tchainNotifier: notifier,\n\t\tchanDB: chanDB,\n\n\t\tinvoices: newInvoiceRegistry(chanDB),\n\t\tutxoNursery: newUtxoNursery(chanDB, notifier, wallet),\n\t\thtlcSwitch: newHtlcSwitch(),\n\n\t\tidentityPriv: privKey,\n\t\tnodeSigner: newNodeSigner(privKey),\n\n\t\t// TODO(roasbeef): derive proper onion key based on rotation\n\t\t// schedule\n\t\tsphinx: sphinx.NewRouter(privKey, activeNetParams.Params),\n\t\tlightningID: sha256.Sum256(serializedPubKey),\n\n\t\tpersistentPeers: make(map[string]struct{}),\n\t\tpersistentConnReqs: make(map[string][]*connmgr.ConnReq),\n\n\t\tpeersByID: make(map[int32]*peer),\n\t\tpeersByPub: make(map[string]*peer),\n\t\tinboundPeers: make(map[string]*peer),\n\t\toutboundPeers: make(map[string]*peer),\n\n\t\tnewPeers: make(chan *peer, 10),\n\t\tdonePeers: make(chan *peer, 10),\n\n\t\tbroadcastRequests: make(chan *broadcastReq),\n\t\tsendRequests: make(chan *sendReq),\n\n\t\tglobalFeatures: globalFeatures,\n\t\tlocalFeatures: localFeatures,\n\n\t\tqueries: make(chan interface{}),\n\t\tquit: make(chan struct{}),\n\t}\n\n\t// If the debug HTLC flag is on, then we invoice a \"master debug\"\n\t// invoice which all outgoing payments will be sent and all incoming\n\t// HTLCs with the debug R-Hash immediately settled.\n\tif cfg.DebugHTLC {\n\t\tkiloCoin := btcutil.Amount(btcutil.SatoshiPerBitcoin * 1000)\n\t\ts.invoices.AddDebugInvoice(kiloCoin, *debugPre)\n\t\tsrvrLog.Debugf(\"Debug HTLC invoice inserted, preimage=%x, hash=%x\",\n\t\t\tdebugPre[:], debugHash[:])\n\t}\n\n\t// If external IP addresses have been specified, add those to the list\n\t// of this server's addresses.\n\tselfAddrs := make([]net.Addr, 0, len(cfg.ExternalIPs))\n\tfor _, ip := range cfg.ExternalIPs {\n\t\tvar addr string\n\t\t_, _, err = net.SplitHostPort(ip)\n\t\tif err != nil {\n\t\t\taddr = net.JoinHostPort(ip, strconv.Itoa(defaultPeerPort))\n\t\t} else {\n\t\t\taddr = ip\n\t\t}\n\n\t\tlnAddr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tselfAddrs = append(selfAddrs, lnAddr)\n\t}\n\n\tchanGraph := chanDB.ChannelGraph()\n\n\t// TODO(roasbeef): make alias configurable\n\talias := lnwire.NewAlias(hex.EncodeToString(serializedPubKey[:10]))\n\tself := &channeldb.LightningNode{\n\t\tLastUpdate: time.Now(),\n\t\tAddresses: selfAddrs,\n\t\tPubKey: privKey.PubKey(),\n\t\tAlias: alias.String(),\n\t\tFeatures: globalFeatures,\n\t}\n\n\t// If our information has changed since our last boot, then we'll\n\t// re-sign our node announcement so a fresh authenticated version of it\n\t// can be propagated throughout the network upon startup.\n\t// TODO(roasbeef): don't always set timestamp above to _now.\n\tself.AuthSig, err = discovery.SignAnnouncement(s.nodeSigner,\n\t\ts.identityPriv.PubKey(),\n\t\t&lnwire.NodeAnnouncement{\n\t\t\tTimestamp: uint32(self.LastUpdate.Unix()),\n\t\t\tAddresses: self.Addresses,\n\t\t\tNodeID: self.PubKey,\n\t\t\tAlias: alias,\n\t\t\tFeatures: self.Features,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate signature for \"+\n\t\t\t\"self node announcement: %v\", err)\n\t}\n\tif err := chanGraph.SetSourceNode(self); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't set self node: %v\", err)\n\t}\n\n\ts.chanRouter, err = routing.New(routing.Config{\n\t\tGraph: chanGraph,\n\t\tChain: bio,\n\t\tNotifier: notifier,\n\t\tSendToSwitch: func(firstHop *btcec.PublicKey,\n\t\t\thtlcAdd *lnwire.UpdateAddHTLC) ([32]byte, error) {\n\n\t\t\tfirstHopPub := firstHop.SerializeCompressed()\n\t\t\tdestInterface := chainhash.Hash(sha256.Sum256(firstHopPub))\n\n\t\t\treturn s.htlcSwitch.SendHTLC(&htlcPacket{\n\t\t\t\tdest: destInterface,\n\t\t\t\tmsg: htlcAdd,\n\t\t\t})\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't create router: %v\", err)\n\t}\n\n\ts.discoverSrv, err = discovery.New(discovery.Config{\n\t\tBroadcast: s.broadcastMessage,\n\t\tNotifier: s.chainNotifier,\n\t\tRouter: s.chanRouter,\n\t\tSendToPeer: s.sendToPeer,\n\t\tTrickleDelay: time.Millisecond * 300,\n\t\tProofMatureDelta: 0,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.rpcServer = newRPCServer(s)\n\ts.breachArbiter = newBreachArbiter(wallet, chanDB, notifier, s.htlcSwitch)\n\n\tvar chanIDSeed [32]byte\n\tif _, err := rand.Read(chanIDSeed[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.fundingMgr, err = newFundingManager(fundingConfig{\n\t\tIDKey: s.identityPriv.PubKey(),\n\t\tWallet: wallet,\n\t\tNotifier: s.chainNotifier,\n\t\tSignMessage: func(pubKey *btcec.PublicKey, msg []byte) (*btcec.Signature, error) {\n\t\t\tif pubKey.IsEqual(s.identityPriv.PubKey()) {\n\t\t\t\treturn s.nodeSigner.SignMessage(pubKey, msg)\n\t\t\t}\n\n\t\t\treturn fundingSigner.SignMessage(pubKey, msg)\n\t\t},\n\t\tSendAnnouncement: func(msg lnwire.Message) error {\n\t\t\ts.discoverSrv.ProcessLocalAnnouncement(msg,\n\t\t\t\ts.identityPriv.PubKey())\n\t\t\treturn nil\n\t\t},\n\t\tArbiterChan: s.breachArbiter.newContracts,\n\t\tSendToPeer: s.sendToPeer,\n\t\tFindPeer: s.findPeer,\n\t\tTempChanIDSeed: chanIDSeed,\n\t\tFindChannel: func(chanID lnwire.ChannelID) (*lnwallet.LightningChannel, error) {\n\t\t\tdbChannels, err := chanDB.FetchAllChannels()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, channel := range dbChannels {\n\t\t\t\tif chanID.IsChanPoint(channel.ChanID) {\n\t\t\t\t\treturn lnwallet.NewLightningChannel(wallet.Signer,\n\t\t\t\t\t\tnotifier, channel)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, fmt.Errorf(\"unable to find channel\")\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO(roasbeef): introduce closure and config system to decouple the\n\t// initialization above ^\n\n\t// Create the connection manager which will be responsible for\n\t// maintaining persistent outbound connections and also accepting new\n\t// incoming connections\n\tcmgr, err := connmgr.New(&connmgr.Config{\n\t\tListeners: listeners,\n\t\tOnAccept: s.inboundPeerConnected,\n\t\tRetryDuration: time.Second * 5,\n\t\tTargetOutbound: 100,\n\t\tGetNewAddress: nil,\n\t\tDial: noiseDial(s.identityPriv),\n\t\tOnConnection: s.outboundPeerConnected,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.connMgr = cmgr\n\n\treturn s, nil\n}", "func NewServer(addr string) (*Server, error) {\n\ts := &Server{\n\t\trequests: make(chan *protocol.NetRequest, 8),\n\t\tresponses: make(chan *protocol.NetResponse, 8),\n\t\tAddr: addr,\n\t\trunning: true,\n\t\tgames: make(map[uint64]poker.GameLike, 0),\n\t}\n\n\tlis, err := net.Listen(\"tcp\", serverAddr())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen: %v\\n\", err)\n\t}\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterGameServerServer(grpcServer, s)\n\n\tlog.Printf(\"server listening at %v\\n\", lis.Addr())\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to serve: `%v`\\n\", err)\n\t}\n\n\treturn s, nil\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tstatusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),\n\t}\n}", "func FileDescriptor_NewServer(s FileDescriptor_Server) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(FileDescriptor_Methods(nil, s), s, c)\n}", "func New(srv *cmutation.Server) *Server {\n\treturn &Server{srv}\n}", "func CreateServer(db string) *Server {\n\tdatastorage.InitDataStore(db)\n\n\tserver := &Server{\n\t\tpending: make(chan net.Conn),\n\t\tleaving: make(chan net.Conn),\n\t}\n\treturn server\n}", "func NewServer(id uuid.UUID, csrv *conf.Service, c *conf.Server, logger log.Logger, r *etcd.Registry) (*Server, error) {\n\tlogicClient, err := logic.NewClient(context.Background(), grpc.WithDiscovery(r))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Server{\n\t\tc: c,\n\t\tuuid: id.String(),\n\t\tround: NewRound(c),\n\t\trpcClient: logicClient,\n\t}\n\t// init bucket\n\ts.buckets = make([]*Bucket, c.Bucket.Size)\n\ts.bucketIdx = uint32(c.Bucket.Size)\n\tfor i := int32(0); i < c.Bucket.Size; i++ {\n\t\ts.buckets[i] = NewBucket(c.Bucket)\n\t}\n\ts.serverID = ip.InternalIP()\n\tgo s.onlineproc()\n\n\tif err := InitWhitelist(c.Whitelist, logger); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := InitTCP(logger, s, c.Tcp.Bind, runtime.NumCPU()); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := InitWebsocket(logger, s, c.Websocket.Bind, runtime.NumCPU()); err != nil {\n\t\tpanic(err)\n\t}\n\t// if conf.Conf.Websocket.TLSOpen {\n\t// \tif err := comet.InitWebsocketWithTLS(srv, conf.Conf.Websocket.TLSBind, conf.Conf.Websocket.CertFile, conf.Conf.Websocket.PrivateFile, runtime.NumCPU()); err != nil {\n\t// \t\tpanic(err)\n\t// \t}\n\t// }\n\n\treturn s, nil\n}", "func NewServer(opts ...Option) AtlasServer {\n\tatlas := &server{\n\t\tcurr: newRunningTraces(),\n\t}\n\tfor _, opt := range opts {\n\t\topt(&atlas.opts)\n\t}\n\tatlas.tc = newTokenCache(atlas.opts.ca)\n\tatlas.limit = rate.NewLimiter(rate.Every(time.Millisecond*12), 5000)\n\treturn atlas\n}", "func newServer() *negroni.Negroni {\n\tn := negroni.Classic()\n\tn.UseHandler(router())\n\treturn n\n}", "func NewServer(ctx Context) *Server {\n\treturn &Server{\n\t\tctx: ctx,\n\t}\n}", "func NewServer(rpc *cosmos.RPC, eventPublisher *publisher.EventPublisher, tokenToRunnerHash *sync.Map, logger tmlog.Logger) *Server {\n\treturn &Server{\n\t\trpc: rpc,\n\t\teventPublisher: eventPublisher,\n\t\ttokenToRunnerHash: tokenToRunnerHash,\n\t\texecInProgress: &sync.Map{},\n\t\tlogger: logger,\n\t}\n}", "func NewServer(p string, r *mux.Router) *Server {\n\treturn &Server{\n\t\timpostersPath: p,\n\t\trouter: r,\n\t}\n}", "func NewServer() *http.Server {\n\tmux := http.NewServeMux()\n\n\tvar limiter *ratelimiter.Limiter\n\tif useMem {\n\t\tlimiter = ratelimiter.New(ratelimiter.Options{\n\t\t\tIPLimit: ipLimit,\n\t\t\tDuration: duration,\n\t\t})\n\n\t} else {\n\t\tclient := redis.NewClient(&redis.Options{Addr: \"localhost:6379\"})\n\t\tlimiter = ratelimiter.New(ratelimiter.Options{\n\t\t\tIPLimit: ipLimit,\n\t\t\tDuration: duration,\n\t\t\tClient: &redisClient{client},\n\t\t})\n\t}\n\n\tmux.HandleFunc(\"/hello\", func(w http.ResponseWriter, r *http.Request) {\n\t\tip := GetIP(r)\n\t\tres, err := limiter.Get(ip)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\theader := w.Header()\n\t\theader.Set(\"X-Ratelimit-Remaining\", strconv.FormatInt(int64(res.Remaining), 10))\n\t\theader.Set(\"X-Ratelimit-Reset\", res.Reset.String())\n\n\t\tif res.Remaining >= 0 {\n\t\t\tw.WriteHeader(200)\n\t\t} else {\n\t\t\thttp.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)\n\t\t}\n\t})\n\n\ts := &http.Server{\n\t\tAddr: \":8080\",\n\t\tHandler: mux,\n\t}\n\treturn s\n}", "func New() (s *Server) {\n\tp := NewPopulation(eliteSize, genSize)\n\ts = &Server{\n\t\tPopulation: p,\n\t}\n\treturn s\n}", "func NewServer(cfg *Config) *Server {\n\ts := NewUnstartedServer(cfg)\n\ts.Start()\n\treturn s\n}", "func NewServer(opts Opts) (net.Listener, *grpc.Server) {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on %s:%d: %v\", opts.Host, opts.Port, err)\n\t}\n\tlog.Notice(\"Listening on %s:%d\", opts.Host, opts.Port)\n\n\ts := grpc.NewServer(OptionalTLS(opts.KeyFile, opts.CertFile, opts.TLSMinVersion,\n\t\tgrpc.ChainUnaryInterceptor(append([]grpc.UnaryServerInterceptor{\n\t\t\tLogUnaryRequests,\n\t\t\tserverMetrics.UnaryServerInterceptor(),\n\t\t\tgrpc_recovery.UnaryServerInterceptor(),\n\t\t}, unaryAuthInterceptor(opts)...)...),\n\t\tgrpc.ChainStreamInterceptor(append([]grpc.StreamServerInterceptor{\n\t\t\tLogStreamRequests,\n\t\t\tserverMetrics.StreamServerInterceptor(),\n\t\t\tgrpc_recovery.StreamServerInterceptor(),\n\t\t}, streamAuthInterceptor(opts)...)...),\n\t\tgrpc.MaxRecvMsgSize(419430400), // 400MB\n\t\tgrpc.MaxSendMsgSize(419430400),\n\t)...)\n\n\tserverMetrics.InitializeMetrics(s)\n\treflection.Register(s)\n\tif !opts.NoHealth {\n\t\tgrpc_health_v1.RegisterHealthServer(s, health.NewServer())\n\t}\n\treturn lis, s\n}", "func newServer(listenAddrs []string) (*server, error) {\n\tlogin := cfg.Username + \":\" + cfg.Password\n\tauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(login))\n\ts := server{\n\t\tauthsha: sha256.Sum256([]byte(auth)),\n\t}\n\n\t// Check for existence of cert file and key file\n\tif !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {\n\t\t// if both files do not exist, we generate them.\n\t\terr := genCertPair(cfg.RPCCert, cfg.RPCKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tkeypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tCertificates: []tls.Certificate{keypair},\n\t}\n\n\tipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)\n\tlisteners := make([]net.Listener, 0,\n\t\tlen(ipv6ListenAddrs)+len(ipv4ListenAddrs))\n\tfor _, addr := range ipv4ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp4\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\n\tfor _, addr := range ipv6ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp6\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\tif len(listeners) == 0 {\n\t\treturn nil, errors.New(\"no valid listen address\")\n\t}\n\n\ts.listeners = listeners\n\n\treturn &s, nil\n}", "func NewServer(opt ...Option) Server {\n\treturn newGrpcServer(opt...)\n}", "func New() *Server {\n\ts := &Server{\n\t\thandlers: map[string][]HandlerFunc{},\n\t\tclosing: make(chan struct{}),\n\t\tclosed: make(chan struct{}),\n\t}\n\ts.pool.New = func() interface{} {\n\t\treturn s.allocateContext()\n\t}\n\treturn s\n}", "func NewServer(s *grpc.Server) *Server {\n\tts := NewUnstartedServer(s)\n\tts.Start()\n\treturn ts\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tenableEndpointSlices bool,\n\tk8sAPI *k8s.API,\n\tmetadataAPI *k8s.MetadataAPI,\n\tclusterStore *watcher.ClusterStore,\n\tclusterDomain string,\n\tdefaultOpaquePorts map[uint32]struct{},\n\tshutdown <-chan struct{},\n) (*grpc.Server, error) {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\n\t// Initialize indexers that are used across watchers\n\terr := watcher.InitializeIndexers(k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoints, err := watcher.NewEndpointsWatcher(k8sAPI, metadataAPI, log, enableEndpointSlices, \"local\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topaquePorts, err := watcher.NewOpaquePortsWatcher(k8sAPI, log, defaultOpaquePorts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprofiles, err := watcher.NewProfileWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tservers, err := watcher.NewServerWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := server{\n\t\tpb.UnimplementedDestinationServer{},\n\t\tendpoints,\n\t\topaquePorts,\n\t\tprofiles,\n\t\tservers,\n\t\tclusterStore,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tclusterDomain,\n\t\tdefaultOpaquePorts,\n\t\tk8sAPI,\n\t\tmetadataAPI,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\treturn s, nil\n}", "func NewServer(network *peer.Network) *Server {\n\ts := &Server{\n\t\trouter: httprouter.New(),\n\t\tnetwork: network,\n\t}\n\n\ts.OPTIONS(\"/\", s.Options)\n\ts.GET(\"/\", s.GetNetwork)\n\ts.POST(\"/start\", s.StartNetwork)\n\ts.POST(\"/stop\", s.StopNetwork)\n\ts.POST(\"/nodes\", s.CreateNode)\n\ts.GET(\"/nodes\", s.GetNodes)\n\ts.GET(\"/nodes/:nodeid\", s.GetNode)\n\ts.POST(\"/nodes/:nodeid/start\", s.StartNode)\n\ts.POST(\"/nodes/:nodeid/stop\", s.StopNode)\n\ts.POST(\"/nodes/:nodeid/conn/:peerid\", s.ConnectNode)\n\ts.DELETE(\"/nodes/:nodeid/conn/:peerid\", s.DisconnectNode)\n\n\treturn s\n}", "func New(opts *mdpb.Conf) *Server {\n\ts := &Server{\n\t\tstart: time.Now(),\n\t\topts: opts,\n\t\tdone: make(chan bool),\n\t\twaitGroup: &sync.WaitGroup{},\n\t}\n\n\ts.mTicker = time.NewTicker(time.Millisecond * InspectorHbPeriodMs)\n\ts.bTicker = time.NewTicker(time.Millisecond * InspectorHbPeriodMs)\n\ts.logTicker = time.NewTicker(time.Second * LogKeepIntev)\n\ts.isp = NewInspector(opts)\n\n\treturn s\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t}\n}", "func New(cfg *config.Config) (*Server, error) {\n\tstorageMgr, err := storage.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create storage manager\")\n\t}\n\n\tsourceClient, err := source.NewSourceClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create source client\")\n\t}\n\t// progress manager\n\tprogressMgr, err := progress.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create progress manager\")\n\t}\n\n\t// cdn manager\n\tcdnMgr, err := cdn.NewManager(cfg, storageMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create cdn manager\")\n\t}\n\n\t// task manager\n\ttaskMgr, err := task.NewManager(cfg, cdnMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create task manager\")\n\t}\n\tstorageMgr.SetTaskMgr(taskMgr)\n\tstorageMgr.InitializeCleaners()\n\tprogressMgr.SetTaskMgr(taskMgr)\n\t// gc manager\n\tgcMgr, err := gc.NewManager(cfg, taskMgr, cdnMgr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create gc manager\")\n\t}\n\n\treturn &Server{\n\t\tConfig: cfg,\n\t\tTaskMgr: taskMgr,\n\t\tGCMgr: gcMgr,\n\t}, nil\n}", "func NewServer() *SimpleServer {\n\t//create server\n\ts := &SimpleServer{\n\t\tWaitGroup: sync.WaitGroup{},\n\t\tServer: http.Server{\n\t\t\tAddr: fmt.Sprintf(\"%s:%d\", config.Host, config.Port),\n\t\t\tReadTimeout: 10 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t},\n\t\tshutdownReq: make(chan bool),\n\t}\n\trouter := NewRouter()\n\ts.Handler = router\n\treturn s\n}" ]
[ "0.72778267", "0.7109852", "0.67946696", "0.6771581", "0.6713264", "0.6634198", "0.6629443", "0.65876275", "0.65573615", "0.65469426", "0.65321046", "0.652998", "0.6521397", "0.6517685", "0.6514072", "0.65068793", "0.6504692", "0.6503021", "0.65002555", "0.64741856", "0.6470686", "0.6470189", "0.6460093", "0.6430329", "0.6406786", "0.6396431", "0.6377726", "0.636854", "0.63656235", "0.63653064", "0.6349952", "0.6330302", "0.632262", "0.6320013", "0.63140815", "0.6283677", "0.6283522", "0.62796116", "0.6270547", "0.6270332", "0.62701327", "0.62570214", "0.6244072", "0.62437576", "0.6243526", "0.6233521", "0.6230944", "0.62298894", "0.6219435", "0.62048846", "0.619407", "0.6181233", "0.6163441", "0.61611444", "0.61480576", "0.6144123", "0.61404586", "0.6134913", "0.61278844", "0.6126232", "0.61237705", "0.61224955", "0.61200535", "0.61180246", "0.61162907", "0.61069185", "0.61068386", "0.6097485", "0.6097355", "0.60930586", "0.60930586", "0.6091157", "0.6090986", "0.60880953", "0.6080285", "0.6079113", "0.6078795", "0.6076101", "0.60750073", "0.6071988", "0.6069686", "0.60691756", "0.60649085", "0.60627884", "0.6061277", "0.60586834", "0.605711", "0.6056592", "0.60551864", "0.6049481", "0.6048877", "0.60479885", "0.60468304", "0.6043788", "0.6042308", "0.6039797", "0.6036124", "0.6034449", "0.60319895", "0.6031661" ]
0.7663686
0
TestTransferBetweenOrbits tests the number of orbital transfers needed to travel from an origin to a destination
func TestTransferBetweenOrbits(t *testing.T) { r := strings.NewReader(`COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN `) preOrbits, err := readPreOrbits(r) if err != nil { t.Error(err) } orbits := processOrbits(preOrbits) you, _ := orbits.get(YOU) san, _ := orbits.get(SAN) transfers := transferBetweenOrbits(you, san) if transfers != 4 { t.Errorf("expected transfers == %d, got %d\n", 4, transfers) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func orbitalTransfers(ob1, ob2 *orbit) int {\n\tvar lca *orbit // lowest common ancestor\n\tob1parents := make([]*orbit, 0)\n\tob1gen := 0 // how many steps from lca to ob1\n\tfor ptr := ob1; ptr != nil; ptr = ptr.parent {\n\t\tob1parents = append(ob1parents, ptr)\n\t}\n\tob2parents := make([]*orbit, 0)\nexterloop:\n\tfor ptr := ob2; ptr != nil; ptr = ptr.parent {\n\t\tfor count, key := range ob1parents {\n\t\t\tif key == ptr {\n\t\t\t\tlca = ptr // well ptr is the lca!\n\t\t\t\tob1gen = count\n\t\t\t\tbreak exterloop\n\t\t\t}\n\t\t}\n\t\tob2parents = append(ob2parents, ptr)\n\t}\n\t_ = lca // we didn't really use this did we?\n\treturn ob1gen + len(ob2parents) - 2\n}", "func testConnectionPair(t *testing.T, src, dst *Chain) {\n\ttestConnection(t, src, dst)\n\ttestConnection(t, dst, src)\n}", "func testConnection(t *testing.T, src, dst *Chain) {\n\tconns, err := src.QueryConnections(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, len(conns), 1)\n\trequire.Equal(t, conns[0].GetClientID(), src.PathEnd.ClientID)\n\trequire.Equal(t, conns[0].GetCounterparty().GetClientID(), dst.PathEnd.ClientID)\n\trequire.Equal(t, conns[0].GetCounterparty().GetConnectionID(), dst.PathEnd.ConnectionID)\n\trequire.Equal(t, conns[0].GetState().String(), \"OPEN\")\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tconn, err := src.QueryConnection(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, conn.Connection.GetClientID(), src.PathEnd.ClientID)\n\trequire.Equal(t, conn.Connection.GetCounterparty().GetClientID(), dst.PathEnd.ClientID)\n\trequire.Equal(t, conn.Connection.GetCounterparty().GetConnectionID(), dst.PathEnd.ConnectionID)\n\trequire.Equal(t, conn.Connection.GetState().String(), \"OPEN\")\n}", "func TestMoby21233(t *testing.T) {\n\tgo testTransfer() // G1\n}", "func testChannelPair(t *testing.T, src, dst *Chain) {\n\ttestChannel(t, src, dst)\n\ttestChannel(t, dst, src)\n}", "func TestPagarmeTransferCreate(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n\n bankAccount := pagarme.NewBankAccount(2020)\n tranfer := pagarme.NewTransfer(100, bankAccount)\n result, err := Pagarme.TransferCreate(tranfer)\n\n if err != nil {\n t.Errorf(\"Erro ao get subscription: %v\", err)\n return\n }\n\n if !result.HasMovements() {\n t.Errorf(\"movement expected, but not has\")\n }\n}", "func TestJoinState_case4(t *testing.T){\n\n\trobot1 := shared.InitRobot(0, shared.Map{}, nil, \"\", \"\")\n\trobot2 := shared.InitRobot(1, shared.Map{}, nil, \"\", \"\")\n\trobot1.CurLocation = shared.Coordinate{0.0,0.0}\n\trobot2.CurLocation = shared.Coordinate{5.0,0.0}\n\n\trobot1.RobotNeighbours[0] = createNeighbour(1.0,3.0)\n\n\trobot2.RobotNeighbours[0] = createNeighbour(2.0,3.0)\n\n\tpayload:= shared.FarNeighbourPayload{NeighbourCoordinate: robot2.CurLocation, ItsNeighbours: []shared.Neighbour{}}\n\tresult :=robot1.WithinRadiusOfNetwork(&payload)\n\n\tif !result {\n\t\tt.FailNow()\n\t}\n// if time permits do stress test lols\n}", "func CanTransfer(view *txo.UtxoViewpoint, block *asiutil.Block, db fvm.StateDB, addr common.Address,\n\tamount *big.Int, vtx *virtualtx.VirtualTransaction, calculateBalanceFunc fvm.CalculateBalanceFunc, assets *protos.Asset) bool {\n\tif amount.Cmp(common.Big0) == 0 {\n\t\treturn true\n\t}\n\tif assets == nil {\n\t\treturn false\n\t}\n\tif assets.IsIndivisible() {\n\t\tif amount.Cmp(common.Big0) < 0 || amount.Cmp(common.BigMaxint64) > 0 {\n\t\t\treturn false\n\t\t}\n\t\ttotal := vtx.GetIncoming(addr, assets, amount.Int64())\n\t\tif total.Cmp(amount) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tbalance, _ := calculateBalanceFunc(view, block, addr, assets, amount.Int64())\n\t\treturn amount.Cmp(big.NewInt(balance)) == 0\n\t} else {\n\t\tif amount.Cmp(common.Big0) < 0 || amount.Cmp(common.BigMaxxing) > 0 {\n\t\t\treturn false\n\t\t}\n\n\t\t//check if there's incoming in the previous transfers from the same contract call.\n\t\ttotal := vtx.GetIncoming(addr, assets, amount.Int64())\n\t\tif total.Cmp(amount) >= 0 {\n\t\t\treturn true\n\t\t}\n\n\t\t//now check the balance.\n\t\tbalance, err := calculateBalanceFunc(view, block, addr, assets, amount.Int64())\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\ttotal.Add(total, big.NewInt(balance))\n\t\treturn total.Cmp(amount) >= 0\n\t}\n}", "func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tnt.isolate(3)\n\n\tlead := nt.peers[1].(*raft)\n\n\tnt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})\n\tif lead.leadTransferee != 3 {\n\t\tt.Fatalf(\"wait transferring, leadTransferee = %v, want %v\", lead.leadTransferee, 3)\n\t}\n\n\t// Transfer leadership to another node.\n\tnt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})\n\n\tcheckLeaderTransferState(t, lead, StateFollower, 2)\n}", "func TestJoinState_case3(t *testing.T){\n\n\trobot1 := shared.InitRobot(0, shared.Map{}, nil, \"\", \"\")\n\trobot2 := shared.InitRobot(1, shared.Map{}, nil, \"\", \"\")\n\trobot1.CurLocation = shared.Coordinate{0.0,0.0}\n\trobot2.CurLocation = shared.Coordinate{5.0,0.0}\n\n\trobot1.RobotNeighbours[0] = createNeighbour(-5.0,3.0)\n\n\trobot2.RobotNeighbours[0] = createNeighbour(10.0,3.0)\n\n\tpayload:= shared.FarNeighbourPayload{NeighbourCoordinate: robot2.CurLocation, ItsNeighbours: []shared.Neighbour{}}\n\tresult :=robot1.WithinRadiusOfNetwork(&payload)\n\n\tif result {\n\t\tt.FailNow()\n\t}\n\n\n}", "func tearDown(url string) {\n\tvar errTransactions int64\n\terrTransactions = 0\n\tfmt.Println(\"....... State transfer is happening, Lets take a nap for 2 mins ......\")\n\tsleep(120)\n\tval1, val2 := queryChaincode(counter)\n\tfmt.Println(\"========= After Query Vals A = \",val1,\" \\n B = \", val2,\"\\n\")\n\n/*\theight := getChainHeight(url) //Remove hardcoding ??\n\tfmt.Println(\"========= Total Blocks #\", height)\n\tfor i := 1; i < height; i++ {\n\t\t//TODO: Don't hard code IP , can we take this as argument ?\n\t\tnonHashData := chaincode.ChaincodeBlockTrxInfo(url, i)\n\t\tlength := len(nonHashData.TransactionResult)\n\t\tfor j := 0; j < length; j++ {\n\t\t\tif nonHashData.TransactionResult[j].ErrorCode > 0 {\n\t\t\t\tfmt.Printf(\"\\n========= Block[%d] Trx#[%s] UUID [%d] ErrorCode [%d] Error: %s\\n\", i, counter, nonHashData.TransactionResult[j].Uuid, nonHashData.TransactionResult[j].ErrorCode, nonHashData.TransactionResult[j].Error)\n\t\t\t\terrTransactions++\n\t\t\t}\n\t\t}\n\t}\n\tif errTransactions > 0 {\n\t\tfmt.Println(\"========= Failed transactions #\", errTransactions)\n\t}\n\tfmt.Println(\"========= Successful transactions #\", counter-errTransactions)\n\n\tnewVal,err := strconv.ParseInt(val2, 10, 64);\n\n\tif err != nil {\n\t\t\tfmt.Println(\"Failed to convert \",val2,\" to int64\\n Error: \", err)\n\t}*/\n\n\t//TODO: Block size again depends on the Block configuration in pbft config file\n\t//Test passes when 2 * block height match with total transactions, else fails\n\tif (newVal == counter) {\n\t\tfmt.Println(\"######### TEST PASSED #########\")\n\t} else {\n\t\tfmt.Println(\"######### TEST FAILED #########\")\n\t}\n\n}", "func TestJoinState_case2(t *testing.T){\n\n\trobot1 := shared.InitRobot(0, shared.Map{}, nil, \"\", \"\")\n\trobot2 := shared.InitRobot(1, shared.Map{}, nil, \"\", \"\")\n\trobot1.CurLocation = shared.Coordinate{0.0,0.0}\n\trobot2.CurLocation = shared.Coordinate{5.0,0.0}\n\n\trobot1.RobotNeighbours[0] = createNeighbour(-5.0,3.0)\n\n\t//robot2.RobotNeighbours[0] = createNeighbour(10.0,10.0)\n\n\tpayload:= shared.FarNeighbourPayload{NeighbourCoordinate: robot2.CurLocation, ItsNeighbours: []shared.Neighbour{}}\n\tresult :=robot1.WithinRadiusOfNetwork(&payload)\n\n\tif result {\n\t\tt.FailNow()\n\t}\n\n\n}", "func transfer_ (stub shim.ChaincodeStubInterface, from_account_name string, to_account_name string, amount int) error {\n if amount < 0 {\n return fmt.Errorf(\"Can't transfer a negative amount (%d)\", amount)\n }\n from_account,err := get_account_(stub, from_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"from\\\" account \\\"%s\\\"; %v\", from_account_name, err.Error())\n }\n to_account,err := get_account_(stub, to_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"to\\\" account \\\"%s\\\"; %v\", to_account_name, err.Error())\n }\n if from_account.Balance < amount {\n return fmt.Errorf(\"Can't transfer; \\\"from\\\" account balance (%d) is less than transfer amount (%d)\", from_account.Balance, amount)\n }\n\n from_account.Balance -= amount\n to_account.Balance += amount\n\n err = overwrite_account_(stub, from_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer from account %v; error was %v\", *from_account, err.Error())\n }\n\n err = overwrite_account_(stub, to_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer to account %v; error was %v\", *to_account, err.Error())\n }\n\n return nil\n}", "func TestOfnetHostBridge(t *testing.T) {\n\n\tfor i := 0; i < NUM_HOST_BRIDGE; i++ {\n\t\tmacAddr, _ := net.ParseMAC(\"02:02:01:AB:CD:EF\")\n\t\tipAddr := net.ParseIP(\"20.20.33.33\")\n\t\tendpoint := EndpointInfo{\n\t\t\tPortNo: uint32(NUM_AGENT + 3),\n\t\t\tMacAddr: macAddr,\n\t\t\tVlan: 1,\n\t\t\tIpAddr: ipAddr,\n\t\t}\n\n\t\tlog.Infof(\"Installing local host bridge endpoint: %+v\", endpoint)\n\n\t\t// Install the local endpoint\n\t\terr := hostBridges[i].AddHostPort(endpoint)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error installing endpoint: %+v. Err: %v\", endpoint, err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Finished adding local host bridge endpoint\")\n\n\t\t// verify all ovs switches have this route\n\t\tbrName := \"hostBridge\" + fmt.Sprintf(\"%d\", i)\n\t\tflowList, err := ofctlFlowDump(brName)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error getting flow entries. Err: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// verify flow entry exists\n\t\tgwInFlowMatch := fmt.Sprintf(\"priority=100,in_port=%d\", NUM_AGENT+3)\n\t\tif !ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwInFlowMatch) {\n\t\t\tt.Errorf(\"Could not find the flow %s on ovs %s\", gwInFlowMatch, brName)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Found gwInFlowMatch %s on ovs %s\", gwInFlowMatch, brName)\n\t\t// verify flow entry exists\n\t\tgwOutFlowMatch := fmt.Sprintf(\"priority=100,dl_dst=%s\", macAddr)\n\t\tif !ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwOutFlowMatch) {\n\t\t\tt.Errorf(\"Could not find the flow %s on ovs %s\", gwOutFlowMatch, brName)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Found gwOutFlowMatch %s on ovs %s\", gwOutFlowMatch, brName)\n\n\t\t// verify flow entry exists\n\t\tgwARPFlowMatch := fmt.Sprintf(\"priority=100,arp\")\n\t\tif !ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwARPFlowMatch) {\n\t\t\tt.Errorf(\"Could not find the flow %s on ovs %s\", gwARPFlowMatch, brName)\n\t\t\tt.Errorf(\"##FlowList: %v\", flowList)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Found gwARPFlowMatch %s on ovs %s\", gwARPFlowMatch, brName)\n\t\tlog.Infof(\"##FlowList: %v\", flowList)\n\n\t\t// Remove the gw endpoint\n\t\terr = hostBridges[i].DelHostPort(uint32(NUM_AGENT + 3))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error deleting endpoint: %+v. Err: %v\", endpoint, err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Deleted endpoints. Verifying they are gone\")\n\n\t\t// verify flows are deleted\n\t\tflowList, err = ofctlFlowDump(brName)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error getting flow entries. Err: %v\", err)\n\t\t}\n\n\t\tif ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwInFlowMatch) {\n\t\t\tt.Errorf(\"The flow %s not deleted from ovs %s\", gwInFlowMatch, brName)\n\t\t\treturn\n\t\t}\n\n\t\tif ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwOutFlowMatch) {\n\t\t\tt.Errorf(\"The flow %s not deleted from ovs %s\", gwOutFlowMatch, brName)\n\t\t\treturn\n\t\t}\n\n\t\tif ofctlFlowMatch(flowList, MAC_DEST_TBL_ID, gwARPFlowMatch) {\n\t\t\tt.Errorf(\"The flow %s not deleted from ovs %s\", gwARPFlowMatch, brName)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Infof(\"Verified all flows are deleted\")\n\t}\n}", "func TestCombine(t *testing.T) {\n\tfor _, test := range tests {\n\t\tt.Run(fnName(test.Fn), func(t *testing.T) {\n\t\t\tedge := getCombineEdge(t, test.Fn, reflectx.Int, test.AccumCoder)\n\n\t\t\tout := &CaptureNode{UID: 1}\n\t\t\tcombine := &Combine{UID: 2, Fn: edge.CombineFn, Out: out}\n\t\t\tn := &FixedRoot{UID: 3, Elements: makeKeyedInput(42, test.Input...), Out: combine}\n\n\t\t\tconstructAndExecutePlan(t, []Unit{n, combine, out})\n\n\t\t\texpected := makeKV(42, test.Expected)\n\t\t\tif !equalList(out.Elements, expected) {\n\t\t\t\tt.Errorf(\"combine(%s) = %v, want %v\", edge.CombineFn.Name(), extractKeyedValues(out.Elements...), extractKeyedValues(expected...))\n\t\t\t}\n\t\t})\n\t}\n}", "func (t *WSTunnelClient) TestConnection(devNetStatus *types.DeviceNetworkStatus, proxyURL *url.URL, localAddr net.IP, devUUID uuid.UUID) error {\n\n\tlog := t.log\n\tif t.Tunnel == \"\" {\n\t\treturn fmt.Errorf(\"Must specify tunnel server ws://hostname:port\")\n\t}\n\tif !strings.HasPrefix(t.Tunnel, \"ws://\") && !strings.HasPrefix(t.Tunnel, \"wss://\") {\n\t\treturn fmt.Errorf(\"Remote tunnel must begin with ws:// or wss://\")\n\t}\n\tt.Tunnel = strings.TrimSuffix(t.Tunnel, \"/\")\n\n\tif t.LocalRelayServer == \"\" {\n\t\treturn fmt.Errorf(\"Must specify local relay server hostOrIP:port\")\n\t}\n\tif strings.HasPrefix(t.LocalRelayServer, \"http://\") && strings.HasPrefix(t.LocalRelayServer, \"https://\") {\n\t\treturn fmt.Errorf(\"Local server relay must not begin with http:// or https://\")\n\t}\n\tt.LocalRelayServer = strings.TrimSuffix(t.LocalRelayServer, \"/\")\n\n\tlog.Tracef(\"Testing connection to %s on local address: %v, proxy: %v\", t.Tunnel, localAddr, proxyURL)\n\tlog.Functionf(\"Testing connection to %s on local address: %v, proxy: %v\", t.Tunnel, localAddr, proxyURL)\n\n\tzedcloudCtx := ZedCloudContext{\n\t\tV2API: UseV2API(),\n\t}\n\t// zedcloudCtx V2API UseV2API()\n\ttlsConfig, err := GetTlsConfig(devNetStatus, nil, &zedcloudCtx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdialer := &websocket.Dialer{\n\t\tReadBufferSize: 100 * 1024,\n\t\tWriteBufferSize: 100 * 1024,\n\t\tTLSClientConfig: tlsConfig,\n\t\tNetDial: func(network, addr string) (net.Conn, error) {\n\t\t\tlocalTCPAddr := net.TCPAddr{IP: localAddr}\n\t\t\tnetDialer := &net.Dialer{LocalAddr: &localTCPAddr}\n\t\t\treturn netDialer.DialContext(context.Background(), network, addr)\n\t\t},\n\t}\n\tif proxyURL != nil {\n\t\tdialer.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\tpingURL := URLPathString(t.Tunnel, zedcloudCtx.V2API, devUUID, \"connection/ping\")\n\t_, resp, err := dialer.Dial(pingURL, nil)\n\tif resp == nil { // this can get error, but with resp code is still 200\n\t\tlog.Functionf(\"TestConnection: url %s, resp %v, err %v\", pingURL, resp, err)\n\t\treturn err\n\t}\n\tlog.Tracef(\"Read ping response status code: %v for ping url: %s\", resp.StatusCode, pingURL)\n\n\tswitch resp.StatusCode {\n\tcase http.StatusOK, http.StatusCreated, http.StatusNotModified:\n\t\turl := URLPathString(t.Tunnel, zedcloudCtx.V2API, devUUID, \"connection/tunnel\")\n\t\tt.DestURL = url\n\t\tt.Dialer = dialer\n\t\tlog.Functionf(\"Connection test succeeded for url: %s on local address: %v, proxy: %v\", url, localAddr, proxyURL)\n\t\treturn nil\n\tdefault:\n\t\treturn err\n\t}\n}", "func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {\n\tnt := newNetwork(nil, nil, nil)\n\tdefer nt.closeAll()\n\tnt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})\n\n\tnt.isolate(3)\n\n\tlead := nt.peers[1].(*raft)\n\n\tnt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})\n\tif lead.leadTransferee != 3 {\n\t\tt.Fatalf(\"wait transferring, leadTransferee = %v, want %v\", lead.leadTransferee, 3)\n\t}\n\n\tfor i := 0; i < lead.heartbeatTimeout; i++ {\n\t\tlead.tick()\n\t}\n\t// Second transfer leadership request to the same node.\n\tnt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})\n\n\tfor i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {\n\t\tlead.tick()\n\t}\n\n\tcheckLeaderTransferState(t, lead, StateLeader, 1)\n}", "func TestUTXOs(t *testing.T) {\n\t// The various UTXO types to check:\n\t// 1. A valid UTXO in a mempool transaction\n\t// 2. A valid UTXO in a mined\n\t// 3. A UTXO that is invalid because it is non-existent\n\t// 4. A UTXO that is invalid because it has the wrong script type\n\t// 5. A UTXO that becomes invalid in a reorg\n\t// 6. A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem script\n\t// 7. A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem script\n\t// 8. A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\t// 9. A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2 multisig\n\t// redeem script\n\t// 10. A UTXO from a coinbase transaction, before and after maturing.\n\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// The vout will be randomized during reset.\n\tconst txHeight = uint32(50)\n\n\t// A general reset function that clears the testBlockchain and the blockCache.\n\treset := func() {\n\t\tbtc.blockCache.mtx.Lock()\n\t\tdefer btc.blockCache.mtx.Unlock()\n\t\tcleanTestChain()\n\t\tnewBC := newBlockCache()\n\t\tbtc.blockCache.blocks = newBC.blocks\n\t\tbtc.blockCache.mainchain = newBC.mainchain\n\t\tbtc.blockCache.best = newBC.best\n\t}\n\n\t// CASE 1: A valid UTXO in a mempool transaction\n\treset()\n\ttxHash := randomHash()\n\tblockHash := randomHash()\n\tmsg := testMakeMsgTx(false)\n\t// For a regular test tx, the output is at output index 0. Pass nil for the\n\t// block hash and 0 for the block height and confirmations for a mempool tx.\n\ttxout := testAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\t// Set the value for this one.\n\ttxout.Value = 5.0\n\t// There is no block info to add, since this is a mempool transaction\n\tutxo, err := btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - unexpected error: %v\", err)\n\t}\n\t// While we're here, check the spend script size and value are correct.\n\tscriptSize := utxo.SpendSize()\n\twantScriptSize := uint32(dexbtc.TxInOverhead + 1 + dexbtc.RedeemP2PKHSigScriptSize)\n\tif scriptSize != wantScriptSize {\n\t\tt.Fatalf(\"case 1 - unexpected spend script size reported. expected %d, got %d\", wantScriptSize, scriptSize)\n\t}\n\tif utxo.Value() != 500_000_000 {\n\t\tt.Fatalf(\"case 1 - unexpected output value. expected 500,000,000, got %d\", utxo.Value())\n\t}\n\t// Now \"mine\" the transaction.\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\t// Overwrite the test blockchain transaction details.\n\ttestAddTxOut(msg.tx, 0, txHash, blockHash, int64(txHeight), 1)\n\t// \"mining\" the block should cause a reorg.\n\tconfs, err := utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - error retrieving confirmations after transaction \\\"mined\\\": %v\", err)\n\t}\n\tif confs != 1 {\n\t\t// The confirmation count is not taken from the wire.TxOut.Confirmations,\n\t\t// so check that it is correctly calculated based on height.\n\t\tt.Fatalf(\"case 1 - expected 1 confirmation after mining transaction, found %d\", confs)\n\t}\n\t// Make sure the pubkey spends the output.\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - Auth error: %v\", err)\n\t}\n\n\t// CASE 2: A valid UTXO in a mined block. This UTXO will have non-zero\n\t// confirmations, a valid pkScipt\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - unexpected error: %v\", err)\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - Auth error: %v\", err)\n\t}\n\n\t// CASE 3: A UTXO that is invalid because it is non-existent\n\treset()\n\t_, err = btc.utxo(randomHash(), 0, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 3 - received no error for a non-existent UTXO\")\n\t}\n\n\t// CASE 4: A UTXO that is invalid because it has the wrong script type.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\t// make the script nonsense.\n\tmsg.tx.TxOut[0].PkScript = []byte{0x00, 0x01, 0x02, 0x03}\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 4 - received no error for a UTXO with wrong script type\")\n\t}\n\n\t// CASE 5: A UTXO that becomes invalid in a reorg\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error for utxo\")\n\t}\n\t_, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error before reorg\")\n\t}\n\ttestAddBlockVerbose(nil, nil, 1, txHeight)\n\t// Remove the txout from the blockchain, since bitcoind would no longer\n\t// return it.\n\ttestDeleteTxOut(txHash, msg.vout)\n\ttime.Sleep(blockPollDelay)\n\t_, err = utxo.Confirmations(context.Background())\n\tif err == nil {\n\t\tt.Fatalf(\"case 5 - received no error for orphaned transaction\")\n\t}\n\t// Now put it back in mempool and check again.\n\ttestAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - error checking confirmations on orphaned transaction back in mempool: %v\", err)\n\t}\n\tif confs != 0 {\n\t\tt.Fatalf(\"case 5 - expected 0 confirmations, got %d\", confs)\n\t}\n\n\t// CASE 6: A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig := testMsgTxP2SHMofN(1, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\t// First try to get the UTXO without providing the raw script.\n\t_, err = btc.utxo(txHash, msgMultiSig.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"no error thrown for p2sh utxo when no script was provided\")\n\t}\n\t// Now provide the script.\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - received error for utxo: %v\", err)\n\t}\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - error getting confirmations: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"case 6 - expected 1 confirmation, got %d\", confs)\n\t}\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - Auth error: %v\", err)\n\t}\n\n\t// CASE 7: A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - received error for utxo: %v\", err)\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 7 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - Auth error: %v\", err)\n\t}\n\n\t// CASE 8: A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(true) // true - P2WPKH at vout 0\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - unexpected error: %v\", err)\n\t}\n\t// Check that the segwit flag is set.\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 8 - script type parsed as non-segwit\")\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - Auth error: %v\", err)\n\t}\n\n\t// CASE 9: A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2\n\t// multisig redeem script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, true)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - received error for utxo: %v\", err)\n\t}\n\t// Check that the script is flagged segwit\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 9 - script type parsed as non-segwit\")\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 9 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - Auth error: %v\", err)\n\t}\n\n\t// CASE 10: A UTXO from a coinbase transaction, before and after maturing.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttxOut := testAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\ttxOut.Coinbase = true\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 10 - no error for immature transaction\")\n\t}\n\tif !errors.Is(err, immatureTransactionError) {\n\t\tt.Fatalf(\"case 10 - expected immatureTransactionError, got: %v\", err)\n\t}\n\t// Mature the transaction\n\tmaturity := uint32(testParams.CoinbaseMaturity)\n\ttestAddBlockVerbose(nil, nil, 1, txHeight+maturity-1)\n\ttxOut.Confirmations = int64(maturity)\n\ttime.Sleep(blockPollDelay)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 10 - unexpected error after maturing: %v\", err)\n\t}\n\n\t// CASE 11: A swap contract\n\tval := int64(5)\n\tcleanTestChain()\n\ttxHash = randomHash()\n\tblockHash = randomHash()\n\tswap := testMsgTxSwapInit(val, btc.segwit)\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\tbtcVal := btcutil.Amount(val).ToBTC()\n\ttestAddTxOut(swap.tx, 0, txHash, blockHash, int64(txHeight), 1).Value = btcVal\n\tverboseTx := testChain.txRaws[*txHash]\n\n\tspentTxHash := randomHash()\n\tverboseTx.Vin = append(verboseTx.Vin, testVin(spentTxHash, 0))\n\t// We need to add that transaction to the blockchain too, because it will\n\t// be requested for the previous outpoint value.\n\tspentMsg := testMakeMsgTx(false)\n\tspentTx := testAddTxVerbose(spentMsg.tx, spentTxHash, blockHash, 2)\n\tspentTx.Vout = []btcjson.Vout{testVout(1, nil)}\n\tswapOut := swap.tx.TxOut[0]\n\tbtcVal = btcutil.Amount(swapOut.Value).ToBTC()\n\tverboseTx.Vout = append(verboseTx.Vout, testVout(btcVal, swapOut.PkScript))\n\tutxo, err = btc.utxo(txHash, 0, swap.contract)\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - received error for utxo: %v\", err)\n\t}\n\n\tcontract := &Contract{Output: utxo.Output}\n\n\t// Now try again with the correct vout.\n\terr = btc.auditContract(contract) // sets refund and swap addresses\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - unexpected error auditing contract: %v\", err)\n\t}\n\tif contract.SwapAddress() != swap.recipient.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.SwapAddress(), swap.recipient.String())\n\t}\n\tif contract.RefundAddress() != swap.refund.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.RefundAddress(), swap.refund.String())\n\t}\n\tif contract.Value() != 5 {\n\t\tt.Fatalf(\"case 11 - unexpected output value. wanted 5, got %d\", contract.Value())\n\t}\n}", "func TestNeigbors(t *testing.T) {\n\tb := MakeBoard(10, 10, 10)\n\tvar tests = []struct {\n\t\tinputX, inputY int\n\t\toutputNeigbors [][2]int\n\t}{\n\t\t// center board\n\t\t{4, 3,\n\t\t\t[][2]int{\n\t\t\t\t{3, 2}, {3, 3}, {3, 4}, {4, 2},\n\t\t\t\t{4, 4}, {5, 2}, {5, 3}, {5, 4}},\n\t\t},\n\t\t// top left corner\n\t\t{0, 0,\n\t\t\t[][2]int{\n\t\t\t\t{0, 1}, {1, 0}, {1, 1}},\n\t\t},\n\t\t// bottom right corner\n\t\t{9, 9,\n\t\t\t[][2]int{\n\t\t\t\t{8, 9}, {9, 8}, {8, 8}},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tn := b.neigborCoords(test.inputX, test.inputY)\n\t\texpectedMap := make(map[[2]int]bool)\n\n\t\tfor _, coord := range test.outputNeigbors {\n\t\t\texpectedMap[coord] = true\n\t\t}\n\n\t\tfor _, coord := range n {\n\t\t\tif !expectedMap[coord] {\n\t\t\t\tt.Errorf(\"(%d, %d) Unexpected Coordinate: %v\",\n\t\t\t\t\ttest.inputX, test.inputY, coord)\n\t\t\t}\n\t\t\texpectedMap[coord] = false\n\t\t}\n\n\t\tfor coord, b := range expectedMap {\n\t\t\tif b {\n\t\t\t\tt.Errorf(\"(%d, %d) Coordinate not created: %v\",\n\t\t\t\t\ttest.inputX, test.inputY, coord)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestPagarmeTransferList(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n\n filter := pagarme.NewFilter()\n result, err := Pagarme.TransferList(filter)\n\n if err != nil {\n t.Errorf(\"Erro ao get subscription: %v\", err)\n return\n }\n\n if !result.HasMovements() {\n t.Errorf(\"movement expected, but not has\")\n }\n}", "func TestAcceptTransfer(t *testing.T) {\n\ttesttrans := []byte(`{\"To\": \"[email protected]\",\"Status\": \"pending\"}`)\n\n\treq, _ := http.NewRequest(\"POST\", \"/certificates/c001/transfers/create\", bytes.NewBuffer(testtrans))\n\treq.SetBasicAuth(\"rr01\", \"rrejh3294\")\n\tresponse := executeRequest(req)\n\n\treq, _ = http.NewRequest(\"PUT\", \"/certificates/c001/transfers/accept\", nil)\n\treq.SetBasicAuth(\"vvg01\", \"vwh39043f\")\n\tresponse = executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusOK, response.Code)\n\n\tif certs[0].OwnerID != \"vvg01\" {\n\t\tt.Errorf(\"Expected certificate owner to be changed. Got '%v'\", certs[0].OwnerID)\n\t}\n\n}", "func TestTransferNonMember(t *testing.T) {\n\tr := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())\n\tdefer closeAndFreeRaft(r)\n\tr.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})\n\n\tr.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})\n\tr.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})\n\tif r.state != StateFollower {\n\t\tt.Fatalf(\"state is %s, want StateFollower\", r.state)\n\t}\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.VorRandomnessRequestMockTransactor.contract.Transfer(opts)\n}", "func TestAccountMove(t *testing.T) {\n\tmoved, err := client.AccountMove(wallet, wallet, testAccount2)\n\n\tif moved || !accountExists(testAccount2) || err != nil {\n\t\tfailTest(t, true, moved, err, \"Moving accounts to the same wallet as moved from does not fail\")\n\t}\n\n\ttime.Sleep(wait)\n\n\tmoved, err = client.AccountMove(\"asdf\", \"asdf\", testAccount2)\n\n\tif moved || fmt.Sprint(err) != \"Bad wallet number\" {\n\t\tfailTest(t, true, moved, err, \"Moving accounts does not show an error\")\n\t}\n\n\ttime.Sleep(wait)\n}", "func TestCountBruno(t *testing.T) {\n\t_o = opts{\n\t\t\"./bruno.txt\",\n\t\tfalse,\n\t}\n\tgot := valueByInput(_o.filePath)\n\twant := 472\n\n\tif got != want {\n\t\tt.Errorf(\"Count orbits = %d; want %d\", got, want)\n\t}\n}", "func testClientPair(t *testing.T, src, dst *Chain) {\n\ttestClient(t, src, dst)\n\ttestClient(t, dst, src)\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.contract.Transfer(opts)\n}", "func (c *CoinTest) sendTransfer(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar A, B string // Entities\r\n\tvar Aval, Bval int // Asset holdings\r\n\tvar X int // Transaction value\r\n\tvar err error\r\n\r\n\tif len(args) != 3 {\r\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 3\")\r\n\t}\r\n\r\n\tA = args[0]\r\n\tB = args[1]\r\n\r\n\t// Get the state from the ledger\r\n\t// TODO: will be nice to have a GetAllState call to ledger\r\n\tAvalbytes, err := stub.GetState(A)\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to get state\")\r\n\t}\r\n\tif Avalbytes == nil {\r\n\t\treturn shim.Error(\"Entity not found\")\r\n\t}\r\n\tAval, _ = strconv.Atoi(string(Avalbytes))\r\n\r\n\tBvalbytes, err := stub.GetState(B)\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to get state\")\r\n\t}\r\n\tif Bvalbytes == nil {\r\n\t\treturn shim.Error(\"Entity not found\")\r\n\t}\r\n\tBval, _ = strconv.Atoi(string(Bvalbytes))\r\n\r\n\t// Perform the execution\r\n\tX, err = strconv.Atoi(args[2])\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Invalid transaction amount, expecting a integer value\")\r\n\t}\r\n\tAval = Aval - X\r\n\tBval = Bval + X\r\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\r\n\r\n\t// Write the state back to the ledger\r\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\r\n\tif err != nil {\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\r\n\tif err != nil {\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\t//TODO: make a transfer to update token out-of-ledger balance\r\n\r\n\treturn shim.Success(nil)\r\n}", "func TestAuthenticateUplinkTraffic(t *testing.T) {\n\tfmt.Println(\"\\nRunning TestAuthenticateUplinkTraffic...\")\n\ttr := NewTestRunner(t)\n\tassert.NoError(t, usePCRFMockDriver())\n\tdefer func() {\n\t\t// Clear hss, ocs, and pcrf\n\t\tassert.NoError(t, clearPCRFMockDriver())\n\t\tassert.NoError(t, tr.CleanUp())\n\t}()\n\n\tues, err := tr.ConfigUEs(1)\n\tassert.NoError(t, err)\n\n\timsi := ues[0].GetImsi()\n\tusageMonitorInfo := getUsageInformation(\"mkey1\", 2*MegaBytes)\n\n\tinitRequest := protos.NewGxCCRequest(imsi, protos.CCRequestType_INITIAL)\n\tinitAnswer := protos.NewGxCCAnswer(diam.Success).\n\t\tSetDynamicRuleInstall(getPassAllRuleDefinition(\"dynamic-pass-all\", \"mkey1\", nil, 100)).\n\t\tSetUsageMonitorInfo(usageMonitorInfo)\n\tinitExpectation := protos.NewGxCreditControlExpectation().Expect(initRequest).Return(initAnswer)\n\t// return success with credit on unexpected requests\n\tdefaultAnswer := protos.NewGxCCAnswer(2001).SetUsageMonitorInfo(usageMonitorInfo)\n\tassert.NoError(t, setPCRFExpectations([]*protos.GxCreditControlExpectation{initExpectation}, defaultAnswer))\n\n\ttr.AuthenticateAndAssertSuccess(imsi)\n\n\treq := &cwfprotos.GenTrafficRequest{\n\t\tImsi: imsi,\n\t\tVolume: &wrappers.StringValue{Value: \"1M\"},\n\t\tBitrate: &wrappers.StringValue{Value: \"60M\"},\n\t\tTimeout: 30,\n\t}\n\t_, err = tr.GenULTraffic(req)\n\tassert.NoError(t, err)\n\n\ttr.AssertAllGxExpectationsMetNoError()\n\n\ttr.DisconnectAndAssertSuccess(imsi)\n\ttr.AssertEventuallyAllRulesRemovedAfterDisconnect(imsi)\n}", "func portRangeConnectivityTest(t *testing.T, getAddresses func(validPort int) []string, portsToTryBefore int, portsToTryAfter int) {\n\tit.TesterWithConfigBuilder(t, func(config *hz.Config) {\n\t\tclusterAddress := config.Cluster.Network.Addresses[0]\n\t\t_, port, err := internal.ParseAddr(clusterAddress)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tconfig.Cluster.Network.SetAddresses(getAddresses(port)...)\n\t\tconfig.Cluster.Network.SetPortRange(port-portsToTryBefore, port+portsToTryAfter)\n\t},\n\t\tfunc(t *testing.T, client *hz.Client) {\n\t\t\tassert.True(t, client.Running())\n\t\t\tif err := client.Shutdown(context.Background()); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tassert.False(t, client.Running())\n\t\t})\n}", "func TestTransportChain(t *testing.T) {\n\toffer, answer, err := newPair()\n\tassert.NoError(t, err)\n\n\tpeerConnectionsConnected := untilConnectionState(PeerConnectionStateConnected, offer, answer)\n\tassert.NoError(t, signalPair(offer, answer))\n\tpeerConnectionsConnected.Wait()\n\n\tassert.NotNil(t, offer.SCTP().Transport().ICETransport())\n\n\tclosePairNow(t, offer, answer)\n}", "func TestTakeSteps(t *testing.T) {\n\tfor i, test := range []struct {\n\t\trotors *Rotors\n\t\tsteps []int\n\t\texpected [][]int\n\t}{\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{1, 1, 1},\n\t\t\t\t[]int{26, 26, 26},\n\t\t\t),\n\t\t\tsteps: []int{10, 26 * 26 * 26},\n\t\t\texpected: [][]int{{10, 0, 0}, {10, 0, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{1, 0, 0},\n\t\t\t\t[]int{1, 1, 1},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{3, 20},\n\t\t\texpected: [][]int{{4, 2, 1}, {24, 12, 6}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 13, 0},\n\t\t\t\t[]int{13, 13, 13},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{2, 8},\n\t\t\texpected: [][]int{{0, 0, 13}, {0, 0, 13}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t\t[]int{13, 13, 13},\n\t\t\t),\n\t\t\tsteps: []int{1, 14},\n\t\t\texpected: [][]int{{2, 0, 0}, {4, 2, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t[]int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n\t\t\t\t[]int{26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26},\n\t\t\t),\n\t\t\tsteps: []int{5, 26 * 26 * 26 * 26},\n\t\t\texpected: [][]int{\n\t\t\t\t{5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t{5, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t[]int{13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13},\n\t\t\t\t[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{15, 30},\n\t\t\texpected: [][]int{\n\t\t\t\t{13, 13, 13, 13, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t{13, 0, 13, 13, 0, 13, 0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{1, 2, 1},\n\t\t\t\t[]int{1, 13, 26},\n\t\t\t),\n\t\t\tsteps: []int{8, 2},\n\t\t\texpected: [][]int{{8, 16, 0}, {10, 20, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t\t[]int{\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t},\n\t\t\t\t[]int{\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t},\n\t\t\t),\n\t\t\tsteps: []int{30, 30},\n\t\t\texpected: [][]int{\n\t\t\t\t{\n\t\t\t\t\t0, 4, 13, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t0, 8, 0, 2, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tfor j, step := range test.steps {\n\t\t\tfor k := 0; k < step; k++ {\n\t\t\t\ttest.rotors.takeStep()\n\t\t\t}\n\n\t\t\tif diff := cmp.Diff(test.expected[j], test.rotors.Setting()); diff != \"\" {\n\t\t\t\tt.Errorf(\"test %d: mismatch (-want +got):\\n%s\", i, diff)\n\t\t\t}\n\t\t}\n\t}\n}", "func VerifyTransfer(lc []BlockHeader, index int, t *ITransfer) bool {\n\t// make a slice of hashes up that follow up to the genesis\n\thashSlice := []string{lc[index].Hash}\n\tfor index > 0 {\n\t\tstart := time.Now()\n\t\tprevLevelIndex := FindPrevLevelBlockIndex(lc, index)\n\t\tif lc[index].LevelPrevHash == lc[prevLevelIndex].Hash {\n\t\t\tindex = prevLevelIndex\n\t\t\thashSlice = append(hashSlice, lc[prevLevelIndex].Hash)\n\t\t}\n\t\tSimulationClock.Add(time.Since(start))\n\t\tNetworkSimulation()\n\t\tif Network == false {\n\t\t\treturn false\n\t\t}\n\t}\n\ttoHash := \"\"\n\tfor _, v := range hashSlice {\n\t\ttoHash += v\n\t}\n\n\tif CreateHashFromString(toHash) == t.Certificate {\n\n\t\treturn true\n\t}\n\treturn false\n\n}", "func TestCountingBits(t *testing.T) {\n\tvar cases = []struct {\n\t\tinput int\n\t\toutput []int\n\t}{\n\t\t{\n\t\t\tinput: 2,\n\t\t\toutput: []int{0, 1, 1},\n\t\t},\n\t\t{\n\t\t\tinput: 5,\n\t\t\toutput: []int{0, 1, 1, 2, 1, 2},\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\tx := countBits(c.input)\n\t\tif !reflect.DeepEqual(x, c.output) {\n\t\t\tt.Fail()\n\t\t}\n\t}\n}", "func (t *SimpleChaincode) transfer(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar err error\n\tvar fromBal, toBal, points, fromIndex, toIndex int\n\tvar accounts []Account\n\tvar transaction Transaction\n\tvar transactions []Transaction\n\n\tif len(args) != 3 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting from & to usernames and number of points\")\n\t}\n\n\t// get balances from accounts array\n\tfmt.Println(\"Retrieving accounts\")\n\taccountsBytes, err := stub.GetState(\"accounts\")\n\tif err != nil {\n\t\tfmt.Println(\"Error retrieving accounts\")\n\t\treturn nil, errors.New(\"Error retrieving accounts\")\n\t}\n\tfmt.Println(\"Converting accounts\")\n\terr = json.Unmarshal(accountsBytes, &accounts)\n\tif err != nil {\n\t\tfmt.Println(\"Error converting accounts\")\n\t\treturn nil, errors.New(\"Error converting accounts\")\n\t}\n\tfromIndex = -1\n\ttoIndex = -1\n\tfor i := 0; i < len(accounts); i++ {\n\t\tif accounts[i].ID == args[0] {\n\t\t\tfromBal = accounts[i].PointBalance\n\t\t\tfromIndex = i\n\t\t} else if accounts[i].ID == args[1] {\n\t\t\ttoBal = accounts[i].PointBalance\n\t\t\ttoIndex = i\n\t\t}\n\t}\n\tif fromIndex == -1 {\n\t\tfmt.Println(\"Could not retrieve balance for \" + args[0])\n\t\treturn nil, errors.New(\"Could not retrieve balance for \" + args[0])\n\t} else if toIndex == -1 {\n\t\tfmt.Println(\"Could not retrieve balance for \" + args[1])\n\t\treturn nil, errors.New(\"Could not retrieve balance for \" + args[0])\n\t}\n\n\t//\ttransfer points\n\tfmt.Println(\"convert points\")\n\tpoints, err = strconv.Atoi(args[2])\n\tif err != nil {\n\t\tfmt.Println(\"Failed to convert points to integer\")\n\t\treturn nil, errors.New(\"Failed to convert points to integer\")\n\t}\n\tif fromBal < points {\n\t\tfmt.Println(\"Point balance does not cover transfer amount for \" + args[0])\n\t\treturn nil, errors.New(\"Point balance does not cover transfer amount for \" + args[0])\n\t}\n\n\t//\tapply transfer\n\tfromBal = fromBal - points\n\t// toBal = toBal + points - don't include points received in gifting balance\n\tfmt.Println(\"apply transfer from \" + args[0] + \" to \" + args[1] + \" for \" + args[2] + \" points - new points \" + strconv.Itoa(fromBal) + \"/\" + strconv.Itoa(toBal))\n\terr = stub.PutState(args[0], []byte(strconv.Itoa(fromBal))) //write the variable into the chaincode state\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = stub.PutState(args[1], []byte(strconv.Itoa(toBal))) //write the variable into the chaincode state\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// update accounts\n\taccounts[fromIndex].PointBalance = fromBal\n\taccounts[fromIndex].Out = accounts[fromIndex].Out + points\n\taccounts[toIndex].PointBalance = toBal\n\taccounts[toIndex].In = accounts[toIndex].In + points\n\taccountsBytes, _ = json.Marshal(&accounts)\n\terr = stub.PutState(\"accounts\", accountsBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add transaction\n\ttransBytes, err := stub.GetState(\"transactions\")\n\tif err != nil {\n\t\tfmt.Println(\"Error retrieving transactions\")\n\t\treturn nil, errors.New(\"Error retrieving transactions\")\n\t}\n\tfmt.Println(\"Converting transactions\")\n\terr = json.Unmarshal(transBytes, &transactions)\n\tif err != nil {\n\t\tfmt.Println(\"Error converting transactions\")\n\t\treturn nil, errors.New(\"Error converting transactions\")\n\t}\n\ttransaction.FromID = args[0]\n\ttransaction.ToID = args[1]\n\ttransaction.Points = points\n\ttransactions = append(transactions, transaction)\n\ttransBytes, _ = json.Marshal(&transactions)\n\terr = stub.PutState(\"transactions\", transBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}", "func CanTransfer(db vm.StateDB, addr types.AddressHash, amount *big.Int) bool {\n\treturn db.GetBalance(addr).Cmp(amount) >= 0\n}", "func test_sendEth(t *testing.T) {\n\tt.Skip(nil)\n\teth_gateway.RunOnTestNet()\n\t// transfer\n\ttransferValue := big.NewInt(1)\n\ttransferValueInWei := new(big.Int).Mul(transferValue, oneWei)\n\t// Send ether to test account\n\ttxs, _, _, err := eth_gateway.EthWrapper.SendETH(eth_gateway.MainWalletAddress, eth_gateway.MainWalletPrivateKey, ethAddress02, transferValueInWei)\n\tif err != nil {\n\t\tt.Logf(\"failed to send ether to %v ether to %v\\n\", transferValue, ethAddress02.Hex())\n\t\tt.Fatalf(\"transaction error: %v\\n\", err)\n\t}\n\tfor tx := range txs {\n\t\ttransaction := txs[tx]\n\t\t// Store For Next Test\n\t\tlastTransaction = *transaction\n\t\tprintTx(transaction)\n\n\t\t// wait for confirmation\n\t\tconfirmed := eth_gateway.EthWrapper.WaitForConfirmation(lastTransaction.Hash(), 3)\n\t\tif confirmed == 1 {\n\t\t\tt.Logf(\"confirmed ether was sent to : %v\", ethAddress02.Hex())\n\t\t} else if confirmed == 0 {\n\t\t\tt.Logf(\"failed to confirm sending ether\")\n\t\t}\n\t}\n}", "func (suite *KeeperTestSuite) TestChanOpenTry() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tpreviousChannelID string\n\t\tportCap *capabilitytypes.Capability\n\t\theightDiff uint64\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"success with crossing hello\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\terr := suite.coordinator.ChanOpenInitOnBothChains(path)\n\t\t\tsuite.Require().NoError(err)\n\n\t\t\tpreviousChannelID = path.EndpointB.ChannelID\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"previous channel with invalid state\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// make previous channel have wrong ordering\n\t\t\tpath.EndpointA.ChanOpenInit()\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\tpath.EndpointA.ConnectionID = ibctesting.FirstConnectionID\n\t\t\tpath.EndpointB.ConnectionID = ibctesting.FirstConnectionID\n\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection is not OPEN\", func() {\n\t\t\tsuite.coordinator.SetupClients(path)\n\t\t\t// pass capability check\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\terr := path.EndpointB.ConnOpenInit()\n\t\t\tsuite.Require().NoError(err)\n\t\t}, false},\n\t\t{\"consensus state not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\n\t\t\theightDiff = 3 // consensus state doesn't exist at this height\n\t\t}, false},\n\t\t{\"channel verification failed\", func() {\n\t\t\t// not creating a channel on chainA will result in an invalid proof of existence\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"port capability not found\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connB versions\n\t\t\tconn := path.EndpointB.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainB.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\tpath.EndpointB.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainB.CreatePortCapability(suite.chainB.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainB.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tpath.SetChannelOrdered()\n\t\t\tpath.EndpointA.ChanOpenInit()\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\tsuite.SetupTest() // reset\n\t\t\theightDiff = 0 // must be explicitly changed in malleate\n\t\t\tpreviousChannelID = \"\"\n\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\n\t\t\ttc.malleate()\n\n\t\t\tif path.EndpointB.ClientID != \"\" {\n\t\t\t\t// ensure client is up to date\n\t\t\t\terr := path.EndpointB.UpdateClient()\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t}\n\n\t\t\tcounterparty := types.NewCounterparty(path.EndpointB.ChannelConfig.PortID, ibctesting.FirstChannelID)\n\n\t\t\tchannelKey := host.ChannelKey(counterparty.PortId, counterparty.ChannelId)\n\t\t\tproof, proofHeight := suite.chainA.QueryProof(channelKey)\n\n\t\t\tchannelID, cap, err := suite.chainB.App.GetIBCKeeper().ChannelKeeper.ChanOpenTry(\n\t\t\t\tsuite.chainB.GetContext(), types.ORDERED, []string{path.EndpointB.ConnectionID},\n\t\t\t\tpath.EndpointB.ChannelConfig.PortID, previousChannelID, portCap, counterparty, path.EndpointB.ChannelConfig.Version, path.EndpointA.ChannelConfig.Version,\n\t\t\t\tproof, malleateHeight(proofHeight, heightDiff),\n\t\t\t)\n\n\t\t\tif tc.expPass {\n\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\tsuite.Require().NotNil(cap)\n\n\t\t\t\tchanCap, ok := suite.chainB.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\tsuite.chainB.GetContext(),\n\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointB.ChannelConfig.PortID, channelID),\n\t\t\t\t)\n\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capapbility after successful ChanOpenTry\")\n\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t} else {\n\t\t\t\tsuite.Require().Error(err)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestPortaniaConnection(t *testing.T) {\n\n\ttestSuite := map[string]struct {\n\t\taddr string\n\t\tduration time.Duration\n\t\terr string\n\t\tsuccess bool\n\t}{\n\t\t\"testConnection should throw an due to a closed port on localhost\": {\n\t\t\taddr: \"localhost:555\",\n\t\t\tsuccess: false,\n\t\t\tduration: time.Second * 5,\n\t\t\terr: \"dial tcp [::1]:555: connect: connection refused\",\n\t\t},\n\t\t\"testConnection should return true indicating that the port is open\": {\n\t\t\taddr: \"github.com:443\",\n\t\t\tduration: time.Second * 5,\n\t\t\tsuccess: true,\n\t\t},\n\t}\n\n\tfor testName, testCase := range testSuite {\n\n\t\tt.Logf(\"Running test %v\\n\", testName)\n\n\t\tok, err := testConnection(testCase.addr, testCase.duration)\n\t\tif err != nil && err.Error() != testCase.err {\n\t\t\tt.Errorf(\"expected testConnection to fail with %v but received %v\\n\", testCase.err, err.Error())\n\t\t} else {\n\t\t\tt.Logf(\"received the expected error result %v\\n\", testCase.err)\n\t\t}\n\n\t\tif ok != testCase.success {\n\t\t\tt.Errorf(\"expected testConnection to return %v but received %v\\n\", testCase.success, ok)\n\t\t} else {\n\t\t\tt.Logf(\"received the expected response from testConnection\\n\")\n\t\t}\n\t}\n}", "func (t *SimpleChaincode) Transfer(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tif len(args) != 3 {\r\n\t\treturn nil, errors.New(\"Incorrect number of arguments. \")\r\n\t}\r\n\tvar A, B string\r\n\tvar Aval, Bval int\r\n\tvar X int\r\n\tA = args[0]\r\n\tB = args[1]\r\n\r\n\tAvalbytes, err := stub.GetState(A)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Failed to get state\")\r\n\t}\r\n\tif Avalbytes == nil {\r\n\t\treturn nil, errors.New(\"Entity not found\")\r\n\t}\r\n\tAval, _ = strconv.Atoi(string(Avalbytes))\r\n\r\n\tBvalbytes, err := stub.GetState(B)\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Failed to get state\")\r\n\t}\r\n\tif Bvalbytes == nil {\r\n\t\treturn nil, errors.New(\"Entity not found\")\r\n\t}\r\n\tBval, _ = strconv.Atoi(string(Bvalbytes))\r\n\r\n\t// Perform the execution\r\n\tX, err = strconv.Atoi(args[2])\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Invalid transaction amount, expecting a integer value\")\r\n\t}\r\n\tAval = Aval - X\r\n\tBval = Bval + X\r\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\r\n\r\n\t// Write the state back to the ledger\r\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn nil, nil\r\n}", "func TestConnectednessCorrect(t *testing.T) {\n\tnets := make([]network.Network, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tnets[i] = GenSwarm(t)\n\t}\n\n\t// connect 0-1, 0-2, 0-3, 1-2, 2-3\n\n\tdial := func(a, b network.Network) {\n\t\tDivulgeAddresses(b, a)\n\t\tif _, err := a.DialPeer(context.Background(), b.LocalPeer()); err != nil {\n\t\t\tt.Fatalf(\"Failed to dial: %s\", err)\n\t\t}\n\t}\n\n\tdial(nets[0], nets[1])\n\tdial(nets[0], nets[3])\n\tdial(nets[1], nets[2])\n\tdial(nets[3], nets[2])\n\n\t// The notifications for new connections get sent out asynchronously.\n\t// There is the potential for a race condition here, so we sleep to ensure\n\t// that they have been received.\n\ttime.Sleep(time.Millisecond * 100)\n\n\t// test those connected show up correctly\n\n\t// test connected\n\texpectConnectedness(t, nets[0], nets[1], network.Connected)\n\texpectConnectedness(t, nets[0], nets[3], network.Connected)\n\texpectConnectedness(t, nets[1], nets[2], network.Connected)\n\texpectConnectedness(t, nets[3], nets[2], network.Connected)\n\n\t// test not connected\n\texpectConnectedness(t, nets[0], nets[2], network.NotConnected)\n\texpectConnectedness(t, nets[1], nets[3], network.NotConnected)\n\n\trequire.Len(t, nets[0].Peers(), 2, \"expected net 0 to have two peers\")\n\trequire.Len(t, nets[2].Peers(), 2, \"expected net 2 to have two peers\")\n\trequire.NotZerof(t, nets[1].ConnsToPeer(nets[3].LocalPeer()), \"net 1 should have no connections to net 3\")\n\trequire.NoError(t, nets[2].ClosePeer(nets[1].LocalPeer()))\n\n\ttime.Sleep(time.Millisecond * 50)\n\texpectConnectedness(t, nets[2], nets[1], network.NotConnected)\n\n\tfor _, n := range nets {\n\t\tn.Close()\n\t}\n}", "func Deposit2ChannelTest(url string) {\n\tvar err error\n\tvar ChannelAddress string\n\tvar Status string\n\tvar Balance int32\n\tvar i int\n\tstart := time.Now()\n\tShowTime()\n\tlog.Println(\"Start Deposit2Channel\")\n\tBalance = 100\n\tlog.Println(\"Deposit to a not exist Channel\")\n\t//deposit to the channel that doesn't exist\n\tChannelAddress = \"0xffffffffffffffffffffffffffffffffffffffff\"\n\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\tShowError(err)\n\t//display the details of the error\n\tShowDeposit2ChannelMsgDetail(Status)\n\tif Status == \"409 Conflict\" {\n\t\tlog.Println(\"Test pass:Deposit to a not exist Channel\")\n\t} else {\n\t\tlog.Println(\"Test failed:Deposit to a not exist Channel\")\n\t\tif HalfLife {\n\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t}\n\t}\n\n\tlog.Println(\"Deposit to a opened Channel\")\n\t//query all channels of the node\n\tChannels, _, _ := QueryingNodeAllChannels(url)\n\t//deposit to the opened channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"opened\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"200 OK\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a open Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a open Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"Deposit to a closed Channel\")\n\t// deposit the closed channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"closed\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"408 Request Timeout\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a closed Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a closed Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlog.Println(\"Deposit to a settled Channel\")\n\t// deposit the settled channel\n\tfor i = 0; i < len(Channels); i++ {\n\t\tif Channels[i].State == \"settled\" {\n\t\t\tChannelAddress = Channels[i].ChannelAddress\n\t\t\tStatus, err = Deposit2Channel(url, ChannelAddress, Balance)\n\t\t\tShowError(err)\n\t\t\t//display the details of the error\n\t\t\tShowDeposit2ChannelMsgDetail(Status)\n\t\t\tif Status == \"408 Request Timeout\" {\n\t\t\t\tfmt.Printf(\"Test pass:Deposit to a settled Channel:%s\\n\", ChannelAddress)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Test failed:Deposit to a settled Channel:%s\\n\", ChannelAddress)\n\t\t\t\tif HalfLife {\n\t\t\t\t\tlog.Fatal(\"HalfLife,exit\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tduration := time.Since(start)\n\tShowTime()\n\tlog.Println(\"time used:\", duration.Nanoseconds()/1000000, \" ms\")\n}", "func TestGatewayOwnership(t *testing.T) {\n\ttestName := \"test-gateway-owned\"\n\tcontourName := fmt.Sprintf(\"%s-contour\", testName)\n\tgcName := \"test-gatewayclass-owned\"\n\tcfg := objcontour.Config{\n\t\tName: contourName,\n\t\tNamespace: operatorNs,\n\t\tSpecNs: specNs,\n\t\tNetworkType: operatorv1alpha1.NodePortServicePublishingType,\n\t\tGatewayClass: &gcName,\n\t}\n\n\tnonOwnedClass := \"test-gatewayclass-not-owned\"\n\t// Create Gateway API resources that should not be managed by the operator.\n\tif err := newGatewayClass(ctx, kclient, nonOwnedClass); err != nil {\n\t\tt.Fatalf(\"failed to create gatewayclass %s: %v\", nonOwnedClass, err)\n\t}\n\tt.Logf(\"created gatewayclass %s\", nonOwnedClass)\n\n\t// The gatewayclass should not report admitted.\n\tif err := waitForGatewayClassStatusConditions(ctx, kclient, 5*time.Second, nonOwnedClass, expectedNonOwnedGatewayClassConditions...); err != nil {\n\t\tt.Fatalf(\"failed to observe expected status conditions for gatewayclass %s: %v\", nonOwnedClass, err)\n\t}\n\n\t// Create the namespace used by the non-owned gateway\n\tif err := newNs(ctx, kclient, cfg.SpecNs); err != nil {\n\t\tt.Fatalf(\"failed to create namespace %s: %v\", cfg.SpecNs, err)\n\t}\n\n\tnonOwnedGateway := \"other-vendor\"\n\tappName := fmt.Sprintf(\"%s-%s\", testAppName, testName)\n\tif err := newGateway(ctx, kclient, cfg.SpecNs, nonOwnedGateway, nonOwnedClass, \"app\", appName); err != nil {\n\t\tt.Fatalf(\"failed to create gateway %s/%s: %v\", cfg.SpecNs, nonOwnedGateway, err)\n\t}\n\tt.Logf(\"created gateway %s/%s\", cfg.SpecNs, nonOwnedGateway)\n\n\t// The gateway should not report scheduled.\n\tif err := waitForGatewayStatusConditions(ctx, kclient, 5*time.Second, nonOwnedGateway, cfg.SpecNs, expectedNonOwnedGatewayConditions...); err != nil {\n\t\tt.Fatalf(\"failed to observe expected status conditions for gateway %s/%s: %v\", cfg.SpecNs, nonOwnedGateway, err)\n\t}\n\n\t// Create the Contour and Gateway API resources that should be managed by the operator.\n\tcntr, err := newContour(ctx, kclient, cfg)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create contour %s/%s: %v\", operatorNs, contourName, err)\n\t}\n\tt.Logf(\"created contour %s/%s\", cntr.Namespace, cntr.Name)\n\n\tif err := newOperatorGatewayClass(ctx, kclient, gcName, operatorNs, contourName); err != nil {\n\t\tt.Fatalf(\"failed to create gatewayclass %s: %v\", gcName, err)\n\t}\n\tt.Logf(\"created gatewayclass %s\", gcName)\n\n\t// The gatewayclass should now report admitted.\n\tif err := waitForGatewayClassStatusConditions(ctx, kclient, 1*time.Minute, gcName, expectedGatewayClassConditions...); err != nil {\n\t\tt.Fatalf(\"failed to observe expected status conditions for gatewayclass %s: %v\", gcName, err)\n\t}\n\n\t// The contour should now report available.\n\tif err := waitForContourStatusConditions(ctx, kclient, 1*time.Minute, contourName, operatorNs, expectedContourConditions...); err != nil {\n\t\tt.Fatalf(\"failed to observe expected status conditions for contour %s/%s: %v\", operatorNs, testName, err)\n\t}\n\tt.Logf(\"observed expected status conditions for contour %s/%s\", testName, operatorNs)\n\n\t// Create the gateway. The gateway must be projectcontour/contour until the following issue is fixed:\n\t// https://github.com/projectcontour/contour-operator/issues/241\n\tgwName := \"contour\"\n\tif err := newGateway(ctx, kclient, cfg.SpecNs, gwName, gcName, \"app\", appName); err != nil {\n\t\tt.Fatalf(\"failed to create gateway %s/%s: %v\", cfg.SpecNs, gwName, err)\n\t}\n\tt.Logf(\"created gateway %s/%s\", cfg.SpecNs, gwName)\n\n\t// The gateway should report admitted.\n\tif err := waitForGatewayStatusConditions(ctx, kclient, 3*time.Minute, gwName, cfg.SpecNs, expectedGatewayConditions...); err != nil {\n\t\tt.Fatalf(\"failed to observe expected status conditions for gateway %s/%s: %v\", cfg.SpecNs, gwName, err)\n\t}\n\n\tgateways := []string{nonOwnedGateway, gwName}\n\tfor _, gw := range gateways {\n\t\t// Ensure the gateway can be deleted and clean-up.\n\t\tif err := deleteGateway(ctx, kclient, 3*time.Minute, gw, cfg.SpecNs); err != nil {\n\t\t\tt.Fatalf(\"failed to delete gateway %s/%s: %v\", cfg.SpecNs, gw, err)\n\t\t}\n\t}\n\n\tclasses := []string{nonOwnedClass, gcName}\n\tfor _, class := range classes {\n\t\t// Ensure the gatewayclass can be deleted and clean-up.\n\t\tif err := deleteGatewayClass(ctx, kclient, 3*time.Minute, class); err != nil {\n\t\t\tt.Fatalf(\"failed to delete gatewayclass %s: %v\", class, err)\n\t\t}\n\t}\n\n\t// Ensure the contour can be deleted and clean-up.\n\tif err := deleteContour(ctx, kclient, 3*time.Minute, contourName, operatorNs); err != nil {\n\t\tt.Fatalf(\"failed to delete contour %s/%s: %v\", operatorNs, contourName, err)\n\t}\n\n\t// Ensure the envoy service is cleaned up automatically.\n\tif err := waitForServiceDeletion(ctx, kclient, 3*time.Minute, specNs, \"envoy\"); err != nil {\n\t\tt.Fatalf(\"failed to delete contour %s/envoy: %v\", specNs, err)\n\t}\n\tt.Logf(\"cleaned up envoy service %s/envoy\", specNs)\n\n\t// Delete the operand namespace since contour.spec.namespace.removeOnDeletion\n\t// defaults to false.\n\tif err := deleteNamespace(ctx, kclient, 5*time.Minute, cfg.SpecNs); err != nil {\n\t\tt.Fatalf(\"failed to delete namespace %s: %v\", cfg.SpecNs, err)\n\t}\n\tt.Logf(\"observed the deletion of namespace %s\", cfg.SpecNs)\n}", "func (_Erc20Mock *Erc20MockTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_TestABI *TestABIRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TestABI.Contract.TestABITransactor.contract.Transfer(opts)\n}", "func TestXorRxRyRz(t *testing.T) {\n\ta := assert.New(t)\n\tv := vm.NewState()\n\n\tfor _, test := range xorTestCases {\n\t\tv.Regs[2] = test.x\n\t\tv.Regs[4] = test.y\n\n\t\tif a.NoError(Eval(v, vm.Opcode(0x82420600))) {\n\t\t\tcheckOpResults(a, &test, v.Regs[6], v.Flags, \"^\")\n\t\t\ta.Equalf(vm.Pointer(vm.RAMStart), v.PC, \"PC shouldn't move\")\n\t\t\ta.Equalf(vm.Pointer(vm.StackStart), v.SP, \"SP shouldn't move\")\n\t\t}\n\t}\n}", "func (m *MockRepository) ListTransfers(arg0 wallet.ListTransfersRequest) ([]wallet.Transfer, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListTransfers\", arg0)\n\tret0, _ := ret[0].([]wallet.Transfer)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestEDCreditOrDebit(t *testing.T) {\n\ttestEDCreditOrDebit(t)\n}", "func (f *FakeUtxoVM) UtxoWorkWithLedgerBasic(t *testing.T) {\n\tutxoVM, ledger := f.U, f.L\n\t//创建链的时候分配财富\n\ttx, err := GenerateRootTx([]byte(`\n {\n \"version\" : \"1\"\n , \"consensus\" : {\n \"miner\" : \"0x00000000000\"\n }\n , \"predistribution\":[\n {\n \"address\" : \"` + f.BobAddress + `\",\n \"quota\" : \"10000000000000000\"\n },\n\t\t\t\t{\n \"address\" : \"` + f.AliceAddress + `\",\n \"quota\" : \"20000000000000000\"\n }\n\n ]\n , \"maxblocksize\" : \"128\"\n , \"period\" : \"5000\"\n , \"award\" : \"1\"\n\t\t} \n `))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tblock, _ := ledger.FormatRootBlock([]*pb.Transaction{tx})\n\tt.Logf(\"blockid %x\", block.Blockid)\n\tconfirmStatus := ledger.ConfirmBlock(block, true)\n\tif !confirmStatus.Succ {\n\t\tt.Fatal(\"confirm block fail\")\n\t}\n\tplayErr := utxoVM.Play(block.Blockid)\n\tif playErr != nil {\n\t\tt.Fatal(playErr)\n\t}\n\tbobBalance, _ := utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ := utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\trootBlockid := block.Blockid\n\tt.Logf(\"rootBlockid: %x\", rootBlockid)\n\t//bob再给alice转5\n\tnextBlock, _, _, blockErr := f.Transfer(\"bob\", \"alice\", t, \"5\", rootBlockid, []byte(\"\"), 0)\n\tnextBlockid := nextBlock.Blockid\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\t//bob再给alice转6\n\tnextBlock, _, _, blockErr = f.Transfer(\"bob\", \"alice\", t, \"6\", nextBlockid, []byte(\"\"), 0)\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tnextBlockid = nextBlock.Blockid\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n}", "func TestOrchestrationInit(t *testing.T) {\n\t// Build orchestration file path\n\tworkingDir, _ := os.Getwd()\n\tvar builder strings.Builder\n\tbuilder.WriteString(workingDir)\n\tbuilder.WriteString(\"/testdata/general/source/orch.toml\")\n\tfilepath := builder.String()\n\n\t// Initialize orchestration file\n\torch := Orchestration{}\n\torch.init(filepath)\n\n\t// Test `description` field was properly parsed\n\tt.Run(\"`description` field\", func(t *testing.T) {\n\t\texpected := \"This is an orchestration file\"\n\t\tactual := orch.Description\n\t\tif expected != actual {\n\t\t\tmsg := \"Description does not match.\\nExpected: %v\\nGot: %v\"\n\t\t\tt.Errorf(msg, expected, actual)\n\t\t}\n\t})\n\n\t// Test `execution_order` field was properly parsed.\n\t//\n\t// Assuming if first and last element were parsed correctly, then the whole\n\t// list was parsed correctly.\n\tt.Run(\"`execution_order` field\", func(t *testing.T) {\n\t\texpected := \"run:transaction.toml\"\n\t\tactual := orch.ExecutionOrder[0]\n\t\tif expected != actual {\n\t\t\tmsg := \"Mismatch for orch.ExecutionOrder[0].\\nExpected: %v\\nGot: %v\"\n\t\t\tt.Errorf(msg, expected, actual)\n\t\t}\n\t\tlen := len(orch.ExecutionOrder) - 1\n\t\texpected = \"run:transactions/transaction2.toml\"\n\t\tactual = orch.ExecutionOrder[len]\n\t\tif expected != actual {\n\t\t\tmsg := \"Mismatch for orch.ExecutionOrder[%v].\\nExpected: %v\\nGot: %v\"\n\t\t\tt.Errorf(msg, len, expected, actual)\n\t\t}\n\t})\n\n\t// Test multi-line string was properly parsed in orch file.\n\tt.Run(\"multi-line string parsing\", func(t *testing.T) {\n\t\texpected := \"then: transaction1.toml,transaction2.toml,transaction3.toml\"\n\t\tactual := orch.ExecutionOrder[2]\n\t\tif expected != actual {\n\t\t\tmsg := \"Mismatch for orch.ExecutionOrder[2].\\nExpected: %v\\nGot: %v\"\n\t\t\tt.Errorf(msg, expected, actual)\n\t\t}\n\t})\n}", "func TestIntegrationUploadDownload(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\t// create testing trio\n\th, c, _, err := newTestingTrio(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer h.Close()\n\tdefer c.Close()\n\n\t// get the host's entry from the db\n\thostEntry, ok := c.hdb.Host(h.PublicKey())\n\tif !ok {\n\t\tt.Fatal(\"no entry for host in db\")\n\t}\n\n\t// set an allowance but don't use SetAllowance to avoid automatic contract\n\t// formation.\n\tc.mu.Lock()\n\tc.allowance = modules.DefaultAllowance\n\tc.mu.Unlock()\n\n\t// form a contract with the host\n\t_, contract, err := c.managedNewContract(hostEntry, types.SiacoinPrecision.Mul64(50), c.blockHeight+100)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// revise the contract\n\teditor, err := c.Editor(contract.HostPublicKey, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdata := fastrand.Bytes(int(modules.SectorSize))\n\troot, err := editor.Upload(data)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = editor.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// download the data\n\tdownloader, err := c.Downloader(contract.HostPublicKey, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tretrieved, err := downloader.Download(root, 0, uint32(modules.SectorSize))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !bytes.Equal(data, retrieved) {\n\t\tt.Fatal(\"downloaded data does not match original\")\n\t}\n\terr = downloader.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func CanTransfer(db StateDB, addr common.Address, amount *big.Int) bool {\n\treturn db.GetBalance(addr).Cmp(amount) >= 0\n}", "func TestStationConnQuerier(t *testing.T) {\n\tquerier := New(\n\t\t&mockFinder{},\n\t\tranker.CreateRanker(ranker.SimpleRanker, nil),\n\t\t&mockPlaceLocationQuerier{},\n\t\t&topograph.MockConnectivityMap,\n\t\tmockOrigLocation,\n\t\tmockDestLocation,\n\t\t10,\n\t\t30,\n\t)\n\n\t// verify location\n\tlocationCases := []struct {\n\t\tqueryID entity.PlaceID\n\t\texpectLocation *nav.Location\n\t}{\n\t\t{\n\t\t\titeratortype.OrigLocationID,\n\t\t\tmockOrigLocation,\n\t\t},\n\t\t{\n\t\t\titeratortype.DestLocationID,\n\t\t\tmockDestLocation,\n\t\t},\n\t\t{\n\t\t\t1,\n\t\t\tmockStation1Location,\n\t\t},\n\t\t{\n\t\t\t2,\n\t\t\tmockStation2Location,\n\t\t},\n\t\t{\n\t\t\t3,\n\t\t\tmockStation3Location,\n\t\t},\n\t\t{\n\t\t\titeratortype.InvalidPlaceID,\n\t\t\tnil,\n\t\t},\n\t}\n\n\tfor _, c := range locationCases {\n\t\tactualLocation := querier.GetLocation(c.queryID)\n\t\tif !reflect.DeepEqual(actualLocation, c.expectLocation) {\n\t\t\tt.Errorf(\"Incorrect result for place.TopoQuerier.GetLocation, expect %+v but got %+v\\n\", c.expectLocation, actualLocation)\n\t\t}\n\t}\n\n\t// verify connectivity\n\tconnectivityCases := []struct {\n\t\tplaceID entity.PlaceID\n\t\texpectQueryResult []*entity.TransferInfo\n\t}{\n\t\t{\n\t\t\titeratortype.OrigLocationID,\n\t\t\t[]*entity.TransferInfo{\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: 3,\n\t\t\t\t\t\tLocation: mockStation3Location,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 4622.08948420977,\n\t\t\t\t\t\tDuration: 208.2022290184581,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: 2,\n\t\t\t\t\t\tLocation: mockStation2Location,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 4999.134247893073,\n\t\t\t\t\t\tDuration: 225.18622738257085,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: 1,\n\t\t\t\t\t\tLocation: mockStation1Location,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 6310.598332634715,\n\t\t\t\t\t\tDuration: 284.2611861547169,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\titeratortype.DestLocationID,\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t1,\n\t\t\t[]*entity.TransferInfo{\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: 2,\n\t\t\t\t\t\tLocation: mockStation2Location,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 1, // hard code value from mock MemoryTopoGraph\n\t\t\t\t\t\tDuration: 1, // hard code value from mock MemoryTopoGraph\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: iteratortype.DestLocationID,\n\t\t\t\t\t\tLocation: mockDestLocation,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 4873.817197753869,\n\t\t\t\t\t\tDuration: 219.54131521413822,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t3,\n\t\t\t[]*entity.TransferInfo{\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: iteratortype.DestLocationID,\n\t\t\t\t\t\tLocation: mockDestLocation,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 7083.8672907090095,\n\t\t\t\t\t\tDuration: 319.0931212031085,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t2,\n\t\t\t[]*entity.TransferInfo{\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: 3,\n\t\t\t\t\t\tLocation: mockStation3Location,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 2, // hard code value from mock MemoryTopoGraph\n\t\t\t\t\t\tDuration: 2, // hard code value from mock MemoryTopoGraph\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tPlaceWithLocation: entity.PlaceWithLocation{\n\t\t\t\t\t\tID: iteratortype.DestLocationID,\n\t\t\t\t\t\tLocation: mockDestLocation,\n\t\t\t\t\t},\n\t\t\t\t\tWeight: &entity.Weight{\n\t\t\t\t\t\tDistance: 7277.313067724465,\n\t\t\t\t\t\tDuration: 327.80689494254347,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range connectivityCases {\n\t\tactualQueryResult := querier.GetConnectedPlaces(c.placeID)\n\t\tif !reflect.DeepEqual(actualQueryResult, c.expectQueryResult) {\n\t\t\tfor _, r := range c.expectQueryResult {\n\t\t\t\tfmt.Printf(\"+++ %v, %v, %v, %v, %v\\n\", r.ID, r.Location.Lat, r.Location.Lon, r.Weight.Distance, r.Weight.Duration)\n\t\t\t}\n\n\t\t\tfor _, r := range actualQueryResult {\n\t\t\t\tfmt.Printf(\"+++ %v, %v, %v, %v, %v\\n\", r.ID, r.Location.Lat, r.Location.Lon, r.Weight.Distance, r.Weight.Duration)\n\t\t\t}\n\t\t\tt.Errorf(\"Incorrect result for place.TopoQuerier.GetConnectedPlaces, expect %#v but got %#v\\n\", c.expectQueryResult, actualQueryResult)\n\t\t}\n\t}\n}", "func testChannel(t *testing.T, src, dst *Chain) {\n\tchans, err := src.QueryChannels(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(chans))\n\trequire.Equal(t, chans[0].GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, chans[0].GetState().String(), \"OPEN\")\n\trequire.Equal(t, chans[0].GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, chans[0].GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tch, err := src.QueryChannel(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, ch.Channel.GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, ch.Channel.GetState().String(), \"OPEN\")\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n}", "func (_Erc20Mock *Erc20MockFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *Erc20MockTransfer, from []common.Address, to []common.Address) (event.Subscription, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\tvar toRule []interface{}\n\tfor _, toItem := range to {\n\t\ttoRule = append(toRule, toItem)\n\t}\n\n\tlogs, sub, err := _Erc20Mock.contract.WatchLogs(opts, \"Transfer\", fromRule, toRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(Erc20MockTransfer)\n\t\t\t\tif err := _Erc20Mock.contract.UnpackLog(event, \"Transfer\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func TestCopy(t *testing.T) {\n\t// Create a random state test to copy and modify \"independently\"\n\torig, _ := New(types.Hash32{}, NewDatabase(database.NewMemDatabase()))\n\n\tfor i := byte(0); i < 255; i++ {\n\t\tobj := orig.GetOrNewStateObj(types.BytesToAddress([]byte{i}))\n\t\tobj.AddBalance(uint64(i))\n\t\torig.updateStateObj(obj)\n\t}\n\n\t// Copy the state, modify both in-memory\n\tcopy := orig.Copy()\n\n\tfor i := byte(0); i < 255; i++ {\n\t\torigObj := orig.GetOrNewStateObj(types.BytesToAddress([]byte{i}))\n\t\tcopyObj := copy.GetOrNewStateObj(types.BytesToAddress([]byte{i}))\n\n\t\torigObj.AddBalance(2 * uint64(i))\n\t\tcopyObj.AddBalance(3 * uint64(i))\n\n\t\torig.updateStateObj(origObj)\n\t\tcopy.updateStateObj(copyObj)\n\t}\n\t// Finalise the changes on both concurrently\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tclose(done)\n\t}()\n\t<-done\n\n\t// Verify that the two states have been updated independently\n\tfor i := byte(0); i < 255; i++ {\n\t\torigObj := orig.GetOrNewStateObj(types.BytesToAddress([]byte{i}))\n\t\tcopyObj := copy.GetOrNewStateObj(types.BytesToAddress([]byte{i}))\n\n\t\tif want := (3 * uint64(i)); origObj.Balance() != want {\n\t\t\tt.Errorf(\"orig obj %d: balance mismatch: have %v, want %v\", i, origObj.Balance(), want)\n\t\t}\n\t\tif want := (4 * uint64(i)); copyObj.Balance() != want {\n\t\t\tt.Errorf(\"copy obj %d: balance mismatch: have %v, want %v\", i, copyObj.Balance(), want)\n\t\t}\n\t}\n}", "func testGatewayStorage(gwStorage storage.GatewayStorage, userID model.UserID, t *testing.T) {\n\t// Retrieve the empty list\n\tgwChan, err := gwStorage.GetList(userID)\n\tif err != nil {\n\t\tt.Fatal(\"Got error retrieving empty list: \", err)\n\t}\n\tcount := 0\n\tfor range gwChan {\n\t\tcount++\n\t}\n\tif count > 0 {\n\t\tt.Fatalf(\"Expected 0 elements but got %d\", count)\n\t}\n\n\t// Create a new gateway\n\tgw1EUI, _ := protocol.EUIFromString(\"00-01-02-03-04-05-06-07\")\n\tgateway1 := model.Gateway{\n\t\tGatewayEUI: gw1EUI,\n\t\tIP: net.ParseIP(\"127.0.0.1\"),\n\t\tStrictIP: false,\n\t\tLatitude: 63.0,\n\t\tLongitude: 10.0,\n\t\tAltitude: 50.0,\n\t\tTags: model.NewTags(),\n\t}\n\n\tif err := gwStorage.Put(gateway1, userID); err != nil {\n\t\tt.Fatal(\"Got error storing gateway: \", err)\n\t}\n\n\tif err := gwStorage.Put(gateway1, userID); err != storage.ErrAlreadyExists {\n\t\tt.Fatal(\"Should get ErrAlreadyExists when storing same gateway twice\")\n\t}\n\t// ...and another one\n\tgw2EUI, _ := protocol.EUIFromString(\"aa-01-02-03-04-05-06-07\")\n\tgateway2 := model.Gateway{\n\t\tGatewayEUI: gw2EUI,\n\t\tIP: net.ParseIP(\"127.0.0.2\"),\n\t\tStrictIP: true,\n\t\tLatitude: -63.0,\n\t\tLongitude: -10.0,\n\t\tAltitude: 0.0,\n\t\tTags: model.NewTags(),\n\t}\n\n\tgateway2.Tags.SetTag(\"Name\", \"Value\")\n\tgateway2.Tags.SetTag(\"Key\", \"Value\")\n\tif err := gwStorage.Put(gateway2, userID); err != nil {\n\t\tt.Fatal(\"Got error storing gateway: \", err)\n\t}\n\n\t// Retrieve the list\n\tgwChan, err = gwStorage.GetList(userID)\n\tif err != nil {\n\t\tt.Fatal(\"Got error retrieving list: \", err)\n\t}\n\n\tvar foundOne, foundTwo bool\n\tfor val := range gwChan {\n\t\tif gateway1.Equals(val) {\n\t\t\tfoundOne = true\n\t\t}\n\t\tif gateway2.Equals(val) {\n\t\t\tfoundTwo = true\n\t\t}\n\t}\n\n\tif !foundOne || !foundTwo {\n\t\tt.Fatal(\"One or both gateways missing from list\")\n\t}\n\n\t// Try adding the same gateway twice. Should yield error\n\tif err := gwStorage.Put(gateway1, userID); err == nil {\n\t\tt.Fatal(\"Expected error when adding gateway twice\")\n\t}\n\n\t// Retrieve the gateway as another user. It should return errnotfound\n\tif _, err := gwStorage.Get(gateway1.GatewayEUI, model.UserID(\"foo\")); err != storage.ErrNotFound {\n\t\tt.Fatal(\"Another user should not be able to access gateway\")\n\t}\n\t// Retrieve just the first gateway. It should - of course - be the same.\n\tfirst, err := gwStorage.Get(gateway1.GatewayEUI, userID)\n\tif err != nil {\n\t\tt.Fatal(\"Did not expect an error\")\n\t}\n\tif !gateway1.Equals(first) {\n\t\tt.Fatalf(\"Gateway did not match %v != %v\", gateway1, first)\n\t}\n\n\t// Retrieving gateway that doesn't exist should yield error\n\tnonEUI, _ := protocol.EUIFromString(\"00-00-00-00-00-00-00-00\")\n\t_, err = gwStorage.Get(nonEUI, userID)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error when retrieving gw that doesn't exist\")\n\t}\n\n\tif err := gwStorage.Update(gateway1, userID); err != nil {\n\t\tt.Fatalf(\"Got error storing tags on gateway: %v\", err)\n\t}\n\n\t// Update fields\n\tgateway1.Altitude = 111\n\tgateway1.Latitude = 222\n\tgateway1.Longitude = 333\n\tgateway1.IP = net.ParseIP(\"10.10.10.10\")\n\tgateway1.StrictIP = true\n\tif err := gwStorage.Update(gateway1, userID); err != nil {\n\t\tt.Fatalf(\"Got error updating gateway: %v\", err)\n\t}\n\tupdatedGw, _ := gwStorage.Get(gateway1.GatewayEUI, userID)\n\tif updatedGw.Altitude != gateway1.Altitude || updatedGw.Longitude != gateway1.Longitude || updatedGw.IP.String() != gateway1.IP.String() || updatedGw.StrictIP != gateway1.StrictIP {\n\t\tt.Fatalf(\"Gateways doesn't match! %v != %v\", updatedGw, gateway1)\n\t}\n\t// Remove both\n\tif err := gwStorage.Delete(gateway1.GatewayEUI, userID); err != nil {\n\t\tt.Fatalf(\"Got error removing gateway #1: %v\", err)\n\t}\n\tif err := gwStorage.Delete(gateway2.GatewayEUI, userID); err != nil {\n\t\tt.Fatalf(\"Got error removing gateway #2: %v\", err)\n\t}\n\t// Remove one that isn't supposed to exist in the list\n\tif err := gwStorage.Delete(gateway1.GatewayEUI, userID); err == nil {\n\t\tt.Fatal(\"Expected error when deleting gateway a second time\")\n\t}\n\n\t// Ensure list is empty again\n\t// Retrieve the empty list\n\tgwChan, err = gwStorage.GetList(userID)\n\tif err != nil {\n\t\tt.Fatal(\"Got error retrieving empty list: \", err)\n\t}\n\tcount = 0\n\tfor range gwChan {\n\t\tcount++\n\t}\n\tif count > 0 {\n\t\tt.Fatalf(\"Got more than 0 elements (got %d)\", count)\n\t}\n\n\ttestAllGateways(gwStorage, t)\n\n}", "func (s *Suite) TestChainingTwoStep() {\n\tvar (\n\t\tone, two coordinate.WorkSpec\n\t\tattempt coordinate.Attempt\n\t\tunits map[string]coordinate.WorkUnit\n\t\tunit coordinate.WorkUnit\n\t\terr error\n\t)\n\n\tsts := SimpleTestSetup{\n\t\tNamespaceName: \"TestChainingTwoStep\",\n\t\tWorkerName: \"worker\",\n\t}\n\tsts.SetUp(s)\n\tdefer sts.TearDown(s)\n\n\tone, err = sts.Namespace.SetWorkSpec(map[string]interface{}{\n\t\t\"name\": \"one\",\n\t\t\"then\": \"two\",\n\t})\n\tif !s.NoError(err) {\n\t\treturn\n\t}\n\n\ttwo, err = sts.Namespace.SetWorkSpec(map[string]interface{}{\n\t\t\"name\": \"two\",\n\t})\n\tif !s.NoError(err) {\n\t\treturn\n\t}\n\n\t_, err = one.AddWorkUnit(\"a\", map[string]interface{}{}, coordinate.WorkUnitMeta{})\n\ts.NoError(err)\n\n\tsts.WorkSpec = one\n\tattempt = sts.RequestOneAttempt(s)\n\terr = attempt.Renew(900*time.Second,\n\t\tmap[string]interface{}{\n\t\t\t\"output\": []interface{}{\n\t\t\t\t[]byte{1, 2, 3, 4},\n\t\t\t\tcborrpc.PythonTuple{Items: []interface{}{\n\t\t\t\t\t[]byte{1, 2, 3, 4},\n\t\t\t\t\tmap[interface{}]interface{}{},\n\t\t\t\t\tmap[interface{}]interface{}{\n\t\t\t\t\t\t\"priority\": 0,\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t})\n\ts.NoError(err)\n\n\terr = attempt.Finish(nil)\n\ts.NoError(err)\n\n\tunits, err = two.WorkUnits(coordinate.WorkUnitQuery{})\n\tif s.NoError(err) {\n\t\tif s.Contains(units, \"\\x01\\x02\\x03\\x04\") {\n\t\t\tunit = units[\"\\x01\\x02\\x03\\x04\"]\n\t\t\ts.DataEmpty(unit)\n\t\t\ts.UnitHasPriority(unit, 0.0)\n\t\t}\n\t}\n}", "func TestNewRevisionFundChecks(t *testing.T) {\n\t// helper func for revisions\n\trevWithValues := func(renterFunds, hostCollateralAvailable uint64) types.FileContractRevision {\n\t\tvalidOuts := make([]types.SiacoinOutput, 2)\n\t\tmissedOuts := make([]types.SiacoinOutput, 3)\n\n\t\t// funds remaining for renter, and payout to host.\n\t\tvalidOuts[0].Value = types.NewCurrency64(renterFunds)\n\t\tvalidOuts[1].Value = types.NewCurrency64(0)\n\n\t\t// Void payout from renter\n\t\tmissedOuts[0].Value = types.NewCurrency64(renterFunds)\n\n\t\t// Collateral\n\t\tmissedOuts[1].Value = types.NewCurrency64(hostCollateralAvailable)\n\n\t\treturn types.FileContractRevision{\n\t\t\tNewValidProofOutputs: validOuts,\n\t\t\tNewMissedProofOutputs: missedOuts,\n\t\t}\n\t}\n\n\t// Cost is less than renter funds should be okay.\n\t_, err := newDownloadRevision(revWithValues(100, 0), types.NewCurrency64(99))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Cost equal to renter funds should be okay.\n\t_, err = newDownloadRevision(revWithValues(100, 0), types.NewCurrency64(100))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Cost is more than renter funds should fail.\n\t_, err = newDownloadRevision(revWithValues(100, 0), types.NewCurrency64(101))\n\tif !errors.Contains(err, types.ErrRevisionCostTooHigh) {\n\t\tt.Fatal(err)\n\t}\n\n\t// Collateral checks (in each, renter funds <= cost)\n\t//\n\t// Cost less than collateral should be okay.\n\t_, err = newUploadRevision(revWithValues(100, 100), crypto.Hash{}, types.NewCurrency64(99), types.NewCurrency64(99))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Using up all collateral should be okay.\n\t_, err = newUploadRevision(revWithValues(100, 100), crypto.Hash{}, types.NewCurrency64(99), types.NewCurrency64(100))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Not enough collateral should cause an error.\n\t_, err = newUploadRevision(revWithValues(100, 100), crypto.Hash{}, types.NewCurrency64(99), types.NewCurrency64(100))\n\tif errors.Contains(err, types.ErrRevisionCollateralTooLow) {\n\t\tt.Fatal(err)\n\t}\n}", "func TestBlockAtDepthOnDAGWithTwoDifferentChains(t *testing.T) {\n\ttestutils.ForAllNets(t, true, func(t *testing.T, consensusConfig *consensus.Config) {\n\t\tfactory := consensus.NewFactory()\n\t\ttc, tearDown, err := factory.NewTestConsensus(consensusConfig,\n\t\t\t\"TestBlockAtDepthOnDAGWithTwoDifferentChains\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed creating a NewTestConsensus: %s\", err)\n\t\t}\n\t\tdefer tearDown(false)\n\n\t\tconst sizeOfTheFirstChildSubChainDAG = 3\n\t\tconst sizeOfTheSecondChildSubChainDAG = 2\n\n\t\tfirstChild, secondChild, err := createADAGWithTwoDifferentChains(consensusConfig.GenesisHash, tc, sizeOfTheFirstChildSubChainDAG,\n\t\t\tsizeOfTheSecondChildSubChainDAG)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed creating a DAG with two different chains in BlockAtDepthTEST: %+v\", err)\n\t\t}\n\n\t\tstagingArea := model.NewStagingArea()\n\n\t\tactualBlockHash, err := tc.DAGTraversalManager().BlockAtDepth(stagingArea, firstChild, sizeOfTheFirstChildSubChainDAG)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed in BlockAtDepth: %+v\", err)\n\t\t}\n\t\texpectedSameHash, err := tc.DAGTraversalManager().BlockAtDepth(stagingArea, secondChild, sizeOfTheSecondChildSubChainDAG)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed in BlockAtDepth: %+v\", err)\n\t\t}\n\n\t\tif !actualBlockHash.Equal(expectedSameHash) {\n\t\t\tt.Fatalf(\"Expected block %s but got %s\", expectedSameHash, actualBlockHash)\n\t\t}\n\t\texpectedDiffHash, err := tc.DAGTraversalManager().BlockAtDepth(stagingArea, secondChild, sizeOfTheSecondChildSubChainDAG-1)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed in BlockAtDepth: %+v\", err)\n\t\t}\n\t\tif actualBlockHash.Equal(expectedDiffHash) {\n\t\t\tt.Fatalf(\"Expected to a differente block\")\n\t\t}\n\t})\n}", "func TestAcceptTransferNotYours(t *testing.T) {\n\ttesttrans := []byte(`{\"To\": \"[email protected]\",\"Status\": \"pending\"}`)\n\n\treq, _ := http.NewRequest(\"POST\", \"/certificates/c002/transfers/create\", bytes.NewBuffer(testtrans))\n\treq.SetBasicAuth(\"vvg01\", \"vwh39043f\")\n\tresponse := executeRequest(req)\n\n\treq, _ = http.NewRequest(\"PUT\", \"/certificates/c002/transfers/accept\", nil)\n\treq.SetBasicAuth(\"rr01\", \"rrejh3294\")\n\tresponse = executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusUnauthorized, response.Code)\n\n\tif body := response.Body.String(); body != \"401: Transfer not intended for this user\" {\n\t\tt.Errorf(\"Expected transfer not for this user error. Got %s\", body)\n\t}\n\n}", "func (suite *KeeperTestSuite) TestChanOpenInit() {\n\tvar (\n\t\tpath *ibctesting.Path\n\t\tfeatures []string\n\t\tportCap *capabilitytypes.Capability\n\t)\n\n\ttestCases := []testCase{\n\t\t{\"success\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t\t{\"channel already exists\", func() {\n\t\t\tsuite.coordinator.Setup(path)\n\t\t}, false},\n\t\t{\"connection doesn't exist\", func() {\n\t\t\t// any non-empty values\n\t\t\tpath.EndpointA.ConnectionID = \"connection-0\"\n\t\t\tpath.EndpointB.ConnectionID = \"connection-0\"\n\t\t}, false},\n\t\t{\"capability is incorrect\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tportCap = capabilitytypes.NewCapability(3)\n\t\t}, false},\n\t\t{\"connection version not negotiated\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"2\", []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = append(conn.Versions, version)\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\tfeatures = []string{\"ORDER_ORDERED\", \"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, false},\n\t\t{\"connection does not support ORDERED channels\", func() {\n\t\t\tsuite.coordinator.SetupConnections(path)\n\n\t\t\t// modify connA versions to only support UNORDERED channels\n\t\t\tconn := path.EndpointA.GetConnection()\n\n\t\t\tversion := connectiontypes.NewVersion(\"1\", []string{\"ORDER_UNORDERED\"})\n\t\t\tconn.Versions = []*connectiontypes.Version{version}\n\n\t\t\tsuite.chainA.App.GetIBCKeeper().ConnectionKeeper.SetConnection(\n\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\tpath.EndpointA.ConnectionID, conn,\n\t\t\t)\n\t\t\t// NOTE: Opening UNORDERED channels is still expected to pass but ORDERED channels should fail\n\t\t\tfeatures = []string{\"ORDER_UNORDERED\"}\n\t\t\tsuite.chainA.CreatePortCapability(suite.chainA.GetSimApp().ScopedIBCMockKeeper, ibctesting.MockPort)\n\t\t\tportCap = suite.chainA.GetPortCapability(ibctesting.MockPort)\n\t\t}, true},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tsuite.Run(fmt.Sprintf(\"Case %s\", tc.msg), func() {\n\t\t\t// run test for all types of ordering\n\t\t\tfor _, order := range []types.Order{types.UNORDERED, types.ORDERED} {\n\t\t\t\tsuite.SetupTest() // reset\n\t\t\t\tpath = ibctesting.NewPath(suite.chainA, suite.chainB)\n\t\t\t\tpath.EndpointA.ChannelConfig.Order = order\n\t\t\t\tpath.EndpointB.ChannelConfig.Order = order\n\n\t\t\t\ttc.malleate()\n\n\t\t\t\tcounterparty := types.NewCounterparty(ibctesting.MockPort, ibctesting.FirstChannelID)\n\n\t\t\t\tchannelID, cap, err := suite.chainA.App.GetIBCKeeper().ChannelKeeper.ChanOpenInit(\n\t\t\t\t\tsuite.chainA.GetContext(), path.EndpointA.ChannelConfig.Order, []string{path.EndpointA.ConnectionID},\n\t\t\t\t\tpath.EndpointA.ChannelConfig.PortID, portCap, counterparty, path.EndpointA.ChannelConfig.Version,\n\t\t\t\t)\n\n\t\t\t\t// check if order is supported by channel to determine expected behaviour\n\t\t\t\torderSupported := false\n\t\t\t\tfor _, f := range features {\n\t\t\t\t\tif f == order.String() {\n\t\t\t\t\t\torderSupported = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Testcase must have expectedPass = true AND channel order supported before\n\t\t\t\t// asserting the channel handshake initiation succeeded\n\t\t\t\tif tc.expPass && orderSupported {\n\t\t\t\t\tsuite.Require().NoError(err)\n\t\t\t\t\tsuite.Require().NotNil(cap)\n\t\t\t\t\tsuite.Require().Equal(types.FormatChannelIdentifier(0), channelID)\n\n\t\t\t\t\tchanCap, ok := suite.chainA.App.GetScopedIBCKeeper().GetCapability(\n\t\t\t\t\t\tsuite.chainA.GetContext(),\n\t\t\t\t\t\thost.ChannelCapabilityPath(path.EndpointA.ChannelConfig.PortID, channelID),\n\t\t\t\t\t)\n\t\t\t\t\tsuite.Require().True(ok, \"could not retrieve channel capability after successful ChanOpenInit\")\n\t\t\t\t\tsuite.Require().Equal(chanCap.String(), cap.String(), \"channel capability is not correct\")\n\t\t\t\t} else {\n\t\t\t\t\tsuite.Require().Error(err)\n\t\t\t\t\tsuite.Require().Nil(cap)\n\t\t\t\t\tsuite.Require().Equal(\"\", channelID)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func TestReorg(t *testing.T) {\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// Clear the blockchain and set the provided chain to build on the ancestor\n\t// block.\n\treset := func() {\n\t\tbtc.blockCache.mtx.Lock()\n\t\tdefer btc.blockCache.mtx.Unlock()\n\t\tcleanTestChain()\n\t\tnewBC := newBlockCache()\n\t\tbtc.blockCache.blocks = newBC.blocks\n\t\tbtc.blockCache.mainchain = newBC.mainchain\n\t\tbtc.blockCache.best = newBC.best\n\t}\n\treset()\n\n\tancestorHeight := uint32(50)\n\tancestorHash := testAddBlockVerbose(nil, nil, 0, ancestorHeight)\n\n\tmakeChain := func() []*chainhash.Hash {\n\t\tchain := make([]*chainhash.Hash, 0, 3)\n\t\tfor i := 0; i < 3; i++ {\n\t\t\th := testAddBlockVerbose(nil, nil, 0, ancestorHeight+1+uint32(i))\n\t\t\tchain = append(chain, h)\n\t\t}\n\t\treturn chain\n\t}\n\tchainA := makeChain()\n\tchainB := makeChain()\n\n\tsetChain := func(hashes []*chainhash.Hash) {\n\t\ttestClearBestBlock()\n\t\trootConfs := int64(len(hashes)) + 1\n\t\t// Add the ancestor block\n\t\ttestAddBlockVerbose(ancestorHash, nil, rootConfs, ancestorHeight)\n\t\tprevHash := ancestorHash\n\t\tfor i, hash := range hashes {\n\t\t\tprevHash = testAddBlockVerbose(hash, prevHash, rootConfs-int64(i), ancestorHeight+uint32(i))\n\n\t\t}\n\t\ttime.Sleep(blockPollDelay)\n\t}\n\n\tsetSidechainConfs := func(hashes []*chainhash.Hash) {\n\t\tfor _, hash := range hashes {\n\t\t\tblk, err := btc.node.GetBlockVerbose(hash)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error retrieving sidechain block to set confirmations: %v\", err)\n\t\t\t}\n\t\t\t// Set Confirmations\n\t\t\tbtc.blockCache.mtx.Lock() // read from (*blockCache).add in cache.go\n\t\t\ttestChainMtx.Lock() // field of testChain\n\t\t\tblk.Confirmations = -1\n\t\t\ttestChainMtx.Unlock()\n\t\t\tbtc.blockCache.mtx.Unlock()\n\t\t}\n\t}\n\n\tcheckOrphanState := func(hashes []*chainhash.Hash, orphanState bool) bool {\n\t\tfor _, hash := range hashes {\n\t\t\tblk, err := btc.getBtcBlock(hash)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error retrieving block after reorg: %v\\n\", err)\n\t\t\t}\n\t\t\tif blk.orphaned != orphanState {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// The test will start with chain A at length lenA above the ancestor. A reorg\n\t// of length lenB will fully replace chain A. Chain A should be fully\n\t// orphaned and chain B should be fully mainchain afterwards.\n\ttest := func(lenA, lenB int) {\n\t\treset()\n\t\tsetChain(chainA[:lenA])\n\t\t// Check that chain A is all mainchain.\n\t\tif !checkOrphanState(chainA[:lenA], false) {\n\t\t\tt.Fatalf(\"chain A block not mainchain for test %d:%d before reorg\", lenA, lenB)\n\t\t}\n\t\t// Reorg the chain.\n\t\tsetSidechainConfs(chainA[:lenA])\n\t\tsetChain(chainB[:lenB])\n\t\t// Chain A should all be orphaned.\n\t\tif !checkOrphanState(chainA[:lenA], true) {\n\t\t\tt.Fatalf(\"chain A block still mainchain for test %d:%d after reorg\", lenA, lenB)\n\t\t}\n\t\t// Chain B should all be mainchain.\n\t\tif !checkOrphanState(chainB[:lenB], false) {\n\t\t\tt.Fatalf(\"chain B block not mainchain for test %d:%d after reorg\", lenA, lenB)\n\t\t}\n\t}\n\n\t// Now run 9 tests.\n\tfor a := 1; a <= 3; a++ {\n\t\tfor b := 1; b <= 3; b++ {\n\t\t\ttest(a, b)\n\t\t}\n\t}\n\n\t// Create a transaction at the tip, then orphan the block and move the\n\t// transaction to mempool.\n\treset()\n\tsetChain(chainA)\n\ttipHeight := btc.blockCache.tipHeight()\n\ttxHash := randomHash()\n\ttip, _ := btc.blockCache.atHeight(tipHeight)\n\tmsg := testMakeMsgTx(false)\n\ttestAddBlockVerbose(&tip.hash, nil, 1, tipHeight)\n\ttestAddTxOut(msg.tx, 0, txHash, &tip.hash, int64(tipHeight), 1)\n\tutxo, err := btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"utxo error 1: %v\", err)\n\t}\n\tconfs, err := utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"wrong number of confirmations. expected 1, got %d\", confs)\n\t}\n\n\t// Orphan the block and move the transaction to mempool.\n\tbtc.blockCache.reorg(int64(ancestorHeight))\n\ttestAddTxOut(msg.tx, 0, txHash, nil, 0, 0)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error after reorg: %v\", err)\n\t}\n\tif confs != 0 {\n\t\tt.Fatalf(\"Expected zero confirmations after reorg, found %d\", confs)\n\t}\n\n\t// Start over, but put it in a lower block instead.\n\treset()\n\tsetChain(chainA)\n\ttip, _ = btc.blockCache.atHeight(tipHeight)\n\ttestAddBlockVerbose(&tip.hash, nil, 1, tipHeight)\n\ttestAddTxOut(msg.tx, 0, txHash, &tip.hash, int64(tipHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"utxo error 2: %v\", err)\n\t}\n\n\t// Reorg and add a single block with the transaction.\n\tbtc.blockCache.reorg(int64(ancestorHeight))\n\tnewBlockHash := randomHash()\n\ttestAddTxOut(msg.tx, 0, txHash, newBlockHash, int64(ancestorHeight+1), 1)\n\ttestAddBlockVerbose(newBlockHash, ancestorHash, 1, ancestorHeight+1)\n\ttime.Sleep(blockPollDelay)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error after reorg to lower block: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"Expected zero confirmations after reorg to lower block, found %d\", confs)\n\t}\n}", "func TestCountBasic(t *testing.T) {\n\t_o = opts{\n\t\t\"./input.txt\",\n\t\ttrue,\n\t}\n\tgot := valueByInput(_o.filePath)\n\twant := 4\n\n\tif got != want {\n\t\tt.Errorf(\"Count orbits = %d; want %d\", got, want)\n\t}\n}", "func runTest1(n int) []int64 {\n\tcreateBlockchain()\n\tt := []int64{}\n\tif verbose {\n\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tnewTransaction(10) // Send 10\n\t\ttxs := prepareTXs()\n\t\tt0 := time.Now()\n\t\t_, err := chain.MineBlock(txs)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn nil\n\t\t}\n\t\tt = append(t, time.Now().Sub(t0).Milliseconds())\n\t\tutxos.Update(txs)\n\t\tif verbose {\n\t\t\tbalance1, _ := utxos.FindSpendableOutputs(HashPubKey(wallet1.PublicKey), 9999999)\n\t\t\tbalance2, _ := utxos.FindSpendableOutputs(HashPubKey(wallet2.PublicKey), 9999999)\n\t\t\tfmt.Printf(\"%d %d %d\\n\", len(chain.blocks), balance1, balance2)\n\t\t}\n\t\ttxBuffer = []*Transaction{}\n\t}\n\n\treturn t\n}", "func testSplitFunds(ctx isc.Sandbox) dict.Dict {\n\taddr, ok := isc.AddressFromAgentID(ctx.Caller())\n\tctx.Requiref(ok, \"caller must have L1 address\")\n\t// claim 1Mi base tokens from allowance at a time\n\tbaseTokensToTransfer := 1 * isc.Million\n\tfor !ctx.AllowanceAvailable().IsEmpty() && ctx.AllowanceAvailable().BaseTokens >= baseTokensToTransfer {\n\t\t// send back to caller's address\n\t\t// depending on the amount of base tokens, it will exceed number of outputs or not\n\t\tctx.TransferAllowedFunds(ctx.AccountID(), isc.NewAssets(baseTokensToTransfer, nil))\n\t\tctx.Send(\n\t\t\tisc.RequestParameters{\n\t\t\t\tTargetAddress: addr,\n\t\t\t\tAssets: isc.NewAssetsBaseTokens(baseTokensToTransfer),\n\t\t\t},\n\t\t)\n\t}\n\treturn nil\n}", "func testFlowTunnel(t *testing.T, tunnelType string) {\n\tts := NewTestStorage()\n\n\taa := helper.NewAgentAnalyzerWithConfig(t, confAgentAnalyzer, ts)\n\taa.Start()\n\tdefer aa.Stop()\n\n\tclient, err := api.NewCrudClientFromConfig(&http.AuthenticationOpts{})\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tcapture1 := api.NewCapture(\"G.V().Has('Name', 'tunnel-vm1').Out().Has('Name', 'tunnel')\", \"\")\n\tif err := client.Create(\"capture\", capture1); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tcapture2 := api.NewCapture(\"G.V().Has('Name', 'tunnel-vm2-eth0')\", \"\")\n\tif err := client.Create(\"capture\", capture2); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\ttime.Sleep(1 * time.Second)\n\n\tsetupCmds := []helper.Cmd{\n\t\t{\"sudo ovs-vsctl add-br br-tunnel\", true},\n\n\t\t{\"sudo ip netns add tunnel-vm1\", true},\n\t\t{\"sudo ip link add tunnel-vm1-eth0 type veth peer name eth0 netns tunnel-vm1\", true},\n\t\t{\"sudo ip link set tunnel-vm1-eth0 up\", true},\n\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip address add 172.16.0.1/24 dev eth0\", true},\n\n\t\t{\"sudo ip netns add tunnel-vm2\", true},\n\t\t{\"sudo ip link add tunnel-vm2-eth0 type veth peer name eth0 netns tunnel-vm2\", true},\n\t\t{\"sudo ip link set tunnel-vm2-eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip address add 172.16.0.2/24 dev eth0\", true},\n\n\t\t{\"sudo ovs-vsctl add-port br-tunnel tunnel-vm1-eth0\", true},\n\t\t{\"sudo ovs-vsctl add-port br-tunnel tunnel-vm2-eth0\", true}}\n\n\ttunnelAdd := \"\"\n\tif tunnelType == \"gre\" {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm1 ip tunnel add tunnel mode gre remote 172.16.0.2 local 172.16.0.1 ttl 255\"\n\t} else {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm1 ip link add tunnel type vxlan id 10 remote 172.16.0.2 local 172.16.0.1 ttl 255 dev eth0 dstport 4789\"\n\t}\n\tsetupCmds = append(setupCmds, []helper.Cmd{\n\t\t{tunnelAdd, true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set tunnel up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link add name dummy0 type dummy\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set dummy0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip a add 192.168.0.1/32 dev dummy0\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip r add 192.168.0.0/24 dev tunnel\", true}}...)\n\n\tif tunnelType == \"gre\" {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm2 ip tunnel add tunnel mode gre remote 172.16.0.1 local 172.16.0.2 ttl 255\"\n\t} else {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm2 ip link add tunnel type vxlan id 10 remote 172.16.0.1 local 172.16.0.2 ttl 255 dev eth0 dstport 4789\"\n\t}\n\tsetupCmds = append(setupCmds, []helper.Cmd{\n\t\t{tunnelAdd, true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set tunnel up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link add name dummy0 type dummy\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set dummy0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip a add 192.168.0.2/32 dev dummy0\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip r add 192.168.0.0/24 dev tunnel\", true},\n\t\t{\"sleep 10\", false},\n\t\t{\"sudo ip netns exec tunnel-vm1 ping -c 5 -I 192.168.0.1 192.168.0.2\", false}}...)\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{\"ip netns del tunnel-vm1\", true},\n\t\t{\"ip netns del tunnel-vm2\", true},\n\t\t{\"ovs-vsctl del-br br-tunnel\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tgh := helper.NewGremlinQueryHelper(&http.AuthenticationOpts{})\n\n\tflowsInnerTunnel := gh.GetFlowsFromGremlinReply(t, `G.V().Has('Name', 'tunnel-vm1').Out().Has('Name', 'tunnel').Flows()`)\n\tflowsBridge := gh.GetFlowsFromGremlinReply(t, `G.V().Has('Name', 'tunnel-vm2-eth0').Flows()`)\n\n\tvar TrackID string\n\tfor _, flow := range flowsInnerTunnel {\n\t\t// A vxlan innerpacket contains Ethernet while gre\n\t\t// innerpacket does not\n\t\tif strings.Contains(flow.LayersPath, \"IPv4/ICMPv4/Payload\") {\n\t\t\tif TrackID != \"\" {\n\t\t\t\tt.Errorf(\"We should only found one ICMPv4 flow in the tunnel %v\", flowsInnerTunnel)\n\t\t\t}\n\t\t\tTrackID = flow.TrackingID\n\t\t}\n\t}\n\n\tsuccess := false\n\tfor _, f := range flowsBridge {\n\t\tif TrackID == f.TrackingID && strings.Contains(f.LayersPath, \"ICMPv4/Payload\") && f.Network != nil && f.Network.Protocol == flow.FlowProtocol_IPV4 {\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !success {\n\t\tt.Errorf(\"TrackingID not found in %s tunnel: leaving the interface(%v) == seen in the tunnel(%v)\", tunnelType, flowsInnerTunnel, flowsBridge)\n\t}\n\n\tclient.Delete(\"capture\", capture1.ID())\n\tclient.Delete(\"capture\", capture2.ID())\n}", "func (s *Suite) TestChainingTwoStep(c *check.C) {\n\tvar (\n\t\tone, two coordinate.WorkSpec\n\t\tworker coordinate.Worker\n\t\tattempts []coordinate.Attempt\n\t\tunits map[string]coordinate.WorkUnit\n\t\tunit coordinate.WorkUnit\n\t\tdata map[string]interface{}\n\t\tpriority float64\n\t\tok bool\n\t\terr error\n\t)\n\n\tone, err = s.Namespace.SetWorkSpec(map[string]interface{}{\n\t\t\"name\": \"one\",\n\t\t\"then\": \"two\",\n\t})\n\tc.Assert(err, check.IsNil)\n\n\ttwo, err = s.Namespace.SetWorkSpec(map[string]interface{}{\n\t\t\"name\": \"two\",\n\t})\n\tc.Assert(err, check.IsNil)\n\n\tworker, err = s.Namespace.Worker(\"worker\")\n\tc.Assert(err, check.IsNil)\n\n\t_, err = one.AddWorkUnit(\"a\", map[string]interface{}{}, 0.0)\n\tc.Assert(err, check.IsNil)\n\n\tattempts, err = worker.RequestAttempts(coordinate.AttemptRequest{})\n\tc.Assert(err, check.IsNil)\n\tc.Assert(attempts, check.HasLen, 1)\n\n\terr = attempts[0].Renew(time.Duration(900)*time.Second,\n\t\tmap[string]interface{}{\n\t\t\t\"output\": []interface{}{\n\t\t\t\t[]byte{1, 2, 3, 4},\n\t\t\t\tcborrpc.PythonTuple{Items: []interface{}{\n\t\t\t\t\t[]byte{1, 2, 3, 4},\n\t\t\t\t\tmap[interface{}]interface{}{},\n\t\t\t\t\tmap[interface{}]interface{}{\n\t\t\t\t\t\t\"priority\": 0,\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t})\n\tc.Assert(err, check.IsNil)\n\n\terr = attempts[0].Finish(nil)\n\n\tunits, err = two.WorkUnits(coordinate.WorkUnitQuery{})\n\tc.Assert(err, check.IsNil)\n\tc.Check(units, HasKeys, []string{\"\\x01\\x02\\x03\\x04\"})\n\tif unit, ok = units[\"\\x01\\x02\\x03\\x04\"]; ok {\n\t\tdata, err = unit.Data()\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Check(data, check.DeepEquals, map[string]interface{}{})\n\n\t\tpriority, err = unit.Priority()\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Check(priority, check.Equals, 0.0)\n\t}\n}", "func TestCreateTransfer(t *testing.T) {\n\ttesttrans := []byte(`{\"To\": \"[email protected]\",\"Status\": \"pending\"}`)\n\n\treq, _ := http.NewRequest(\"POST\", \"/certificates/c001/transfers/create\", bytes.NewBuffer(testtrans))\n\treq.SetBasicAuth(\"rr01\", \"rrejh3294\")\n\tresponse := executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusCreated, response.Code)\n\n\tif certs[0].Transfer.Status != \"pending\" {\n\t\tt.Errorf(\"Expected certificate transfer to be pending. Got '%v'\", certs[0].Transfer.Status)\n\t}\n\n}", "func TestTraitorCommanderNumSuccess(t *testing.T) {\n\tnumTrials := 100\n\trand.Seed(time.Now().UnixNano())\n\t// m is the number of traitors.\n\tfor m := 0; m <= 50; m++ {\n\t\t// The number of lieutenants (not including the commander), must be greater than 3*m.\n\t\tn := 3*m + 1\n\t\t// Keeps track of the number of successful trials.\n\t\tnumSuccess := 0\n\t\tfor r := 0; r < numTrials; r++ {\n\t\t\t// The command that will be sent by the commander, randomly generated.\n\t\t\tcommand := rand.Intn(2) == 0\n\t\t\tgenerals := make([]bool, n+1)\n\t\t\tgenerals[0] = false // commander is a traitor\n\t\t\tfor i := 1; i <= n; i++ {\n\t\t\t\tgenerals[i] = true\n\t\t\t}\n\n\t\t\tperm := rand.Perm(n) // returns a permutation of the numbers [0, n)\n\t\t\t// For the first m values in the permutation, assign those generals to be traitors.\n\t\t\tfor i := 0; i < m; i++ {\n\t\t\t\tgenerals[perm[i]+1] = false\n\t\t\t}\n\n\t\t\tcommands := runGenerals(m, generals, command)\n\n\t\t\t// Verify all loyal lieutenants agree on the same value.\n\t\t\tfirstLoyal := false\n\t\t\tloyalCommand := false\n\t\t\tagreement := true\n\t\t\tfor i := 1; i <= n; i++ {\n\t\t\t\tif generals[i] == true {\n\t\t\t\t\tif firstLoyal == false {\n\t\t\t\t\t\tfirstLoyal = true\n\t\t\t\t\t\tloyalCommand = commands[i]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif commands[i] != loyalCommand {\n\t\t\t\t\t\t\tagreement = false\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif agreement {\n\t\t\t\tnumSuccess++\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"%0.2f%% trials successful for m = %d, n = %d\\n\", 100*(float64(numSuccess)/float64(numTrials)), m, n)\n\t}\n}", "func TestCoinChange(t *testing.T) {\n\ttest(t, coinChange)\n}", "func TestIATBHISODestinationCurrencyCode(t *testing.T) {\n\ttestIATBHISODestinationCurrencyCode(t)\n}", "func TestCreditEAIIsDeterministic2(t *testing.T) {\n\t// set up accounts\n\ttype account struct {\n\t\taddress address.Address\n\t\tprivate signature.PrivateKey\n\t\tpublic signature.PublicKey\n\t}\n\n\tmakeAccount := func() account {\n\t\tpublic, private, err := signature.Generate(signature.Ed25519, nil)\n\t\trequire.NoError(t, err)\n\t\taddr, err := address.Generate(address.KindUser, public.KeyBytes())\n\t\trequire.NoError(t, err)\n\t\treturn account{\n\t\t\taddress: addr,\n\t\t\tprivate: private,\n\t\t\tpublic: public,\n\t\t}\n\t}\n\n\taccts := make([]account, 5)\n\tfor i := range accts {\n\t\taccts[i] = makeAccount()\n\t}\n\n\t// part of the point of the test is to exclude \"solutions\" in which\n\t// two otherwise-equivalent account pairs experience different behavior\n\t// depending on the relative ordering of their addresses. That sort of\n\t// thing would be deterministic, but it wouldn't be fair. Therefore,\n\t// we need to sort the accounts by address to ensure that we have one\n\t// account whose rewards are redirected to another one after it,\n\t// and one whose rewards are redirected to another one before it.\n\t// Therefore, we need to sort these accounts.\n\tsort.Slice(accts, func(i, j int) bool {\n\t\treturn accts[i].address.String() < accts[j].address.String()\n\t})\n\n\ta := accts[0]\n\tb := accts[1]\n\tc := accts[2]\n\td := accts[3]\n\tnode := accts[4]\n\n\t// set up app preconditions\n\tapp, _ := initApp(t)\n\n\tvar txs []tx.Transactable\n\n\tdelegate := func(from account) {\n\t\ttxs = append(txs,\n\t\t\tNewDelegate(from.address, node.address, 1, from.private),\n\t\t)\n\t}\n\n\tredirect := func(from, to account) {\n\t\ttxs = append(txs,\n\t\t\tNewSetRewardsDestination(\n\t\t\t\tfrom.address,\n\t\t\t\tto.address,\n\t\t\t\t2,\n\t\t\t\tfrom.private,\n\t\t\t),\n\t\t)\n\t}\n\n\tsetup := func(acct account, balance math.Ndau, redirectTo *account) {\n\t\tmodify(t, acct.address.String(), app, func(ad *backing.AccountData) {\n\t\t\tad.LastEAIUpdate = 0\n\t\t\tad.LastWAAUpdate = 0\n\t\t\tad.WeightedAverageAge = 0\n\t\t\tad.Balance = balance * constants.NapuPerNdau\n\t\t\t// normally it's enforced that a validation key can't match the\n\t\t\t// ownership key for the account, but it's not important for the\n\t\t\t// behavior under test, and this is simpler instead of having\n\t\t\t// to generate even more keys\n\t\t\tad.ValidationKeys = []signature.PublicKey{acct.public}\n\t\t})\n\t\tif acct.address.String() != node.address.String() {\n\t\t\tdelegate(acct)\n\t\t}\n\t\tif redirectTo != nil {\n\t\t\tredirect(acct, *redirectTo)\n\t\t}\n\t}\n\n\tsetup(a, 1000, &b)\n\tsetup(d, 1000, &c)\n\tsetup(node, 10, nil)\n\tapp.UpdateStateImmediately(func(stI metast.State) (metast.State, error) {\n\t\tst := stI.(*backing.State)\n\t\tst.Nodes[node.address.String()] = backing.Node{\n\t\t\tActive: true,\n\t\t}\n\t\treturn st, nil\n\t})\n\n\tresps, _ := deliverTxsContext(t, app, txs, ddc(t).at(math.Timestamp(math.Year)))\n\tfor _, resp := range resps {\n\t\trequire.Equal(t, code.OK, code.ReturnCode(resp.Code))\n\t}\n\n\tt.Logf(\"a: %s\", a.address)\n\tt.Logf(\"b: %s\", b.address)\n\tt.Logf(\"c: %s\", c.address)\n\tt.Logf(\"d: %s\", d.address)\n\tt.Logf(\"node: %s\", node.address)\n\n\tequiv := func(a, b backing.AccountData) {\n\t\trequire.Equal(t, a.Balance, b.Balance)\n\t\trequire.Equal(t, a.LastEAIUpdate, b.LastEAIUpdate)\n\t\trequire.Equal(t, a.LastWAAUpdate, b.LastWAAUpdate)\n\t\trequire.Equal(t, a.WeightedAverageAge, b.WeightedAverageAge)\n\t}\n\n\tcheckState := func() {\n\t\t// given the exact same circumstances, each account data pair must\n\t\t// be identical\n\t\tA, _ := app.getAccount(a.address)\n\t\tB, _ := app.getAccount(b.address)\n\t\tC, _ := app.getAccount(c.address)\n\t\tD, _ := app.getAccount(d.address)\n\n\t\tequiv(A, D)\n\t\tequiv(B, C)\n\t}\n\n\t// we must have set up the initial state of the accounts identically\n\tcheckState()\n\n\t// perform tests\n\t// note: we do _not_ wish to run each iteration here as an independent\n\t// subtest, which is a little unusual. However, the intent here is that\n\t// we don't actually vary the conditions within each test instance; we just\n\t// want some measure of reassurance that we're not just getting lucky\n\t// with random map iteration order.\n\tts := math.Timestamp(math.Year + math.Month)\n\tfor i := uint64(0); i < 128; i++ {\n\t\t// perform a CreditEAI tx\n\t\ttx := NewCreditEAI(node.address, i+5, node.private)\n\n\t\tresp := deliverTxAt(\n\t\t\tt,\n\t\t\tapp,\n\t\t\ttx,\n\t\t\tts,\n\t\t)\n\t\trequire.Equal(t, code.OK, code.ReturnCode(resp.Code))\n\n\t\t// state must still be identical here\n\t\tcheckState()\n\t}\n}", "func TestWebsocketOrigins(t *testing.T) {\n\ttests := []originTest{\n\t\t{\n\t\t\tspec: \"*\", // allow all\n\t\t\texpOk: []string{\"\", \"http://test\", \"https://test\", \"http://test:8540\", \"https://test:8540\",\n\t\t\t\t\"http://test.com\", \"https://foo.test\", \"http://testa\", \"http://atestb:8540\", \"https://atestb:8540\"},\n\t\t},\n\t\t{\n\t\t\tspec: \"test\",\n\t\t\texpOk: []string{\"http://test\", \"https://test\", \"http://test:8540\", \"https://test:8540\"},\n\t\t\texpFail: []string{\"http://test.com\", \"https://foo.test\", \"http://testa\", \"http://atestb:8540\", \"https://atestb:8540\"},\n\t\t},\n\t\t// scheme tests\n\t\t{\n\t\t\tspec: \"https://test\",\n\t\t\texpOk: []string{\"https://test\", \"https://test:9999\"},\n\t\t\texpFail: []string{\n\t\t\t\t\"test\", // no scheme, required by spec\n\t\t\t\t\"http://test\", // wrong scheme\n\t\t\t\t\"http://test.foo\", \"https://a.test.x\", // subdomain variatoins\n\t\t\t\t\"http://testx:8540\", \"https://xtest:8540\"},\n\t\t},\n\t\t// ip tests\n\t\t{\n\t\t\tspec: \"https://12.34.56.78\",\n\t\t\texpOk: []string{\"https://12.34.56.78\", \"https://12.34.56.78:8540\"},\n\t\t\texpFail: []string{\n\t\t\t\t\"http://12.34.56.78\", // wrong scheme\n\t\t\t\t\"http://12.34.56.78:443\", // wrong scheme\n\t\t\t\t\"http://1.12.34.56.78\", // wrong 'domain name'\n\t\t\t\t\"http://12.34.56.78.a\", // wrong 'domain name'\n\t\t\t\t\"https://87.65.43.21\", \"http://87.65.43.21:8540\", \"https://87.65.43.21:8540\"},\n\t\t},\n\t\t// port tests\n\t\t{\n\t\t\tspec: \"test:8540\",\n\t\t\texpOk: []string{\"http://test:8540\", \"https://test:8540\"},\n\t\t\texpFail: []string{\n\t\t\t\t\"http://test\", \"https://test\", // spec says port required\n\t\t\t\t\"http://test:8541\", \"https://test:8541\", // wrong port\n\t\t\t\t\"http://bad\", \"https://bad\", \"http://bad:8540\", \"https://bad:8540\"},\n\t\t},\n\t\t// scheme and port\n\t\t{\n\t\t\tspec: \"https://test:8540\",\n\t\t\texpOk: []string{\"https://test:8540\"},\n\t\t\texpFail: []string{\n\t\t\t\t\"https://test\", // missing port\n\t\t\t\t\"http://test\", // missing port, + wrong scheme\n\t\t\t\t\"http://test:8540\", // wrong scheme\n\t\t\t\t\"http://test:8541\", \"https://test:8541\", // wrong port\n\t\t\t\t\"http://bad\", \"https://bad\", \"http://bad:8540\", \"https://bad:8540\"},\n\t\t},\n\t\t// several allowed origins\n\t\t{\n\t\t\tspec: \"localhost,http://127.0.0.1\",\n\t\t\texpOk: []string{\"localhost\", \"http://localhost\", \"https://localhost:8443\",\n\t\t\t\t\"http://127.0.0.1\", \"http://127.0.0.1:8080\"},\n\t\t\texpFail: []string{\n\t\t\t\t\"https://127.0.0.1\", // wrong scheme\n\t\t\t\t\"http://bad\", \"https://bad\", \"http://bad:8540\", \"https://bad:8540\"},\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tsrv := createAndStartServer(t, &httpConfig{}, true, &wsConfig{Origins: splitAndTrim(tc.spec)})\n\t\turl := fmt.Sprintf(\"ws://%v\", srv.listenAddr())\n\t\tfor _, origin := range tc.expOk {\n\t\t\tif err := wsRequest(t, url, origin); err != nil {\n\t\t\t\tt.Errorf(\"spec '%v', origin '%v': expected ok, got %v\", tc.spec, origin, err)\n\t\t\t}\n\t\t}\n\t\tfor _, origin := range tc.expFail {\n\t\t\tif err := wsRequest(t, url, origin); err == nil {\n\t\t\t\tt.Errorf(\"spec '%v', origin '%v': expected not to allow, got ok\", tc.spec, origin)\n\t\t\t}\n\t\t}\n\t\tsrv.stop()\n\t}\n}", "func TestAuthenticateMultipleAPsUplinkTraffic(t *testing.T) {\n\tfmt.Println(\"\\nRunning TestAuthenticateMultipleAPsUplinkTraffic...\")\n\ttr := NewTestRunner(t)\n\tassert.NoError(t, usePCRFMockDriver())\n\tdefer func() {\n\t\t// Clear hss, ocs, and pcrf\n\t\tassert.NoError(t, clearPCRFMockDriver())\n\t\tassert.NoError(t, tr.CleanUp())\n\t}()\n\n\tues, err := tr.ConfigUEs(1)\n\tassert.NoError(t, err)\n\n\timsi := ues[0].GetImsi()\n\tusageMonitorInfo := getUsageInformation(\"mkey1\", 2*MegaBytes)\n\tinitRequest := protos.NewGxCCRequest(imsi, protos.CCRequestType_INITIAL)\n\tinitAnswer := protos.NewGxCCAnswer(diam.Success).\n\t\tSetDynamicRuleInstall(getPassAllRuleDefinition(\"dynamic-pass-all\", \"mkey1\", nil, 100)).\n\t\tSetUsageMonitorInfo(usageMonitorInfo)\n\tinitExpectation := protos.NewGxCreditControlExpectation().Expect(initRequest).Return(initAnswer)\n\t// return success with credit on unexpected requests\n\tdefaultAnswer := protos.NewGxCCAnswer(2001).SetUsageMonitorInfo(usageMonitorInfo)\n\tassert.NoError(t, setPCRFExpectations([]*protos.GxCreditControlExpectation{initExpectation}, defaultAnswer))\n\n\tCalledStationIDs := getCalledStationIDs()\n\ttr.AuthenticateWithCalledIDAndAssertSuccess(imsi, CalledStationIDs[0])\n\n\treq := &cwfprotos.GenTrafficRequest{\n\t\tImsi: imsi,\n\t\tVolume: &wrappers.StringValue{Value: \"1M\"},\n\t\tBitrate: &wrappers.StringValue{Value: \"60M\"},\n\t\tTimeout: 30,\n\t}\n\t_, err = tr.GenULTraffic(req)\n\tassert.NoError(t, err)\n\n\ttr.AuthenticateWithCalledIDAndAssertSuccess(imsi, CalledStationIDs[1])\n\n\t_, err = tr.GenULTraffic(req)\n\tassert.NoError(t, err)\n\n\ttr.AssertAllGxExpectationsMetNoError()\n\n\t_, err = tr.Disconnect(imsi, CalledStationIDs[1])\n\tassert.NoError(t, err)\n\ttr.AssertEventuallyAllRulesRemovedAfterDisconnect(imsi)\n}", "func TestConnection(t *testing.T) {\n\tif !haveArchive {\n\t\treturn\n\t}\n\n\t// PollForErrorEvents should be safe\n\tfor i := 0; i < 10; i++ {\n\t\tcount, err := archive.PollForErrorResponse()\n\t\tif err != nil {\n\t\t\tt.Logf(\"PollforErrorRespose() recieved %d responses, err is %s\", count, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tidler := idlestrategy.Sleeping{SleepFor: time.Millisecond * 100}\n\t\tidler.Idle(0)\n\t}\n\n}", "func (_Erc20Mock *Erc20MockFilterer) FilterTransfer(opts *bind.FilterOpts, from []common.Address, to []common.Address) (*Erc20MockTransferIterator, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\tvar toRule []interface{}\n\tfor _, toItem := range to {\n\t\ttoRule = append(toRule, toItem)\n\t}\n\n\tlogs, sub, err := _Erc20Mock.contract.FilterLogs(opts, \"Transfer\", fromRule, toRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Erc20MockTransferIterator{contract: _Erc20Mock.contract, event: \"Transfer\", logs: logs, sub: sub}, nil\n}", "func RecursiveCountOrbits(node *Node, counter *int) {\n\t*counter += (*node).getOrbitCount()\n\tfor _, child := range node.Children {\n\t\tRecursiveCountOrbits(child, counter)\n\t}\n}", "func TestTransitionSystem_UnionOfStates2(t *testing.T) {\n\n\t// Constants\n\tx0 := TransitionSystemState{Name: \"Steven\"}\n\tx1 := TransitionSystemState{Name: \"Gabe\"}\n\tx2 := TransitionSystemState{Name: \"Nosa\"}\n\tx3 := TransitionSystemState{Name: \"Desnor\"}\n\tx4 := TransitionSystemState{Name: \"Nailah\"}\n\n\tslice1 := []TransitionSystemState{x0, x1, x2}\n\tslice2 := []TransitionSystemState{x2, x3, x4}\n\n\t// Algorithm\n\tslice3 := UnionOfStates(slice1, slice2)\n\n\tif len(slice3) != 5 {\n\t\tt.Errorf(\"slice3 is empty!\")\n\t}\n\n\tif !x0.In(slice3) {\n\t\tt.Errorf(\"x0 not found in slice3!\")\n\t}\n\n\tif !x1.In(slice3) {\n\t\tt.Errorf(\"x1 not found in slice3!\")\n\t}\n\n\tif !x2.In(slice3) {\n\t\tt.Errorf(\"x2 not found in slice3!\")\n\t}\n\n}", "func TstCheckWithdrawalStatusMatches(t *testing.T, s1, s2 WithdrawalStatus) {\n\tif s1.Fees() != s2.Fees() {\n\t\tt.Fatalf(\"Wrong amount of network fees; want %d, got %d\", s1.Fees(), s2.Fees())\n\t}\n\n\tif !reflect.DeepEqual(s1.Sigs(), s2.Sigs()) {\n\t\tt.Fatalf(\"Wrong tx signatures; got %x, want %x\", s1.Sigs(), s2.Sigs())\n\t}\n\n\tif !reflect.DeepEqual(s1.NextInputAddr(), s2.NextInputAddr()) {\n\t\tt.Fatalf(\"Wrong NextInputAddr; got %v, want %v\", s1.NextInputAddr(), s2.NextInputAddr())\n\t}\n\n\tif !reflect.DeepEqual(s1.NextChangeAddr(), s2.NextChangeAddr()) {\n\t\tt.Fatalf(\"Wrong NextChangeAddr; got %v, want %v\", s1.NextChangeAddr(), s2.NextChangeAddr())\n\t}\n\n\tif !reflect.DeepEqual(s1.Outputs(), s2.Outputs()) {\n\t\tt.Fatalf(\"Wrong WithdrawalOutputs; got %v, want %v\", s1.Outputs(), s2.Outputs())\n\t}\n\n\tif !reflect.DeepEqual(s1.transactions, s2.transactions) {\n\t\tt.Fatalf(\"Wrong transactions; got %v, want %v\", s1.transactions, s2.transactions)\n\t}\n\n\t// The above checks could be replaced by this one, but when they fail the\n\t// failure msg wouldn't give us much clue as to what is not equal, so we do\n\t// the individual checks above and use this one as a catch-all check in case\n\t// we forget to check any of the individual fields.\n\tif !reflect.DeepEqual(s1, s2) {\n\t\tt.Fatalf(\"Wrong WithdrawalStatus; got %v, want %v\", s1, s2)\n\t}\n}", "func TestLayerUploadTokens(t *testing.T) {\n\tsecret := hmacKey(\"supersecret\")\n\n\tfor _, tc := range blobUploadStates {\n\t\ttoken, err := secret.packUploadState(tc)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tlus, err := secret.unpackUploadState(token)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tassertBlobUploadStateEquals(t, tc, lus)\n\t}\n}", "func TestCurrentTraffic(t *testing.T) {\n\tvar (\n\t\tbackoff = time.Hour * 5\n\t\twithinBackoff = testTime.Add(time.Hour * -1)\n\t\toutsideBackoff = testTime.Add(backoff * -2)\n\n\t\tsuccess = []*loopdb.LoopEvent{\n\t\t\t{\n\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\tState: loopdb.StateSuccess,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tfailedInBackoff = []*loopdb.LoopEvent{\n\t\t\t{\n\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\tState: loopdb.StateFailOffchainPayments,\n\t\t\t\t},\n\t\t\t\tTime: withinBackoff,\n\t\t\t},\n\t\t}\n\n\t\tfailedOutsideBackoff = []*loopdb.LoopEvent{\n\t\t\t{\n\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\tState: loopdb.StateFailOffchainPayments,\n\t\t\t\t},\n\t\t\t\tTime: outsideBackoff,\n\t\t\t},\n\t\t}\n\n\t\tfailedTimeoutInBackoff = []*loopdb.LoopEvent{\n\t\t\t{\n\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\tState: loopdb.StateFailTimeout,\n\t\t\t\t},\n\t\t\t\tTime: withinBackoff,\n\t\t\t},\n\t\t}\n\n\t\tfailedTimeoutOutsideBackoff = []*loopdb.LoopEvent{\n\t\t\t{\n\t\t\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\t\t\tState: loopdb.StateFailTimeout,\n\t\t\t\t},\n\t\t\t\tTime: outsideBackoff,\n\t\t\t},\n\t\t}\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\tloopOut []*loopdb.LoopOut\n\t\tloopIn []*loopdb.LoopIn\n\t\texpected *swapTraffic\n\t}{\n\t\t{\n\t\t\tname: \"completed swaps ignored\",\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: success,\n\t\t\t\t\t},\n\t\t\t\t\tContract: &loopdb.LoopOutContract{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tloopIn: []*loopdb.LoopIn{\n\t\t\t\t{\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: success,\n\t\t\t\t\t},\n\t\t\t\t\tContract: &loopdb.LoopInContract{},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: newSwapTraffic(),\n\t\t},\n\t\t{\n\t\t\t// No events indicates that the swap is still pending.\n\t\t\tname: \"pending swaps included\",\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopOutContract{\n\t\t\t\t\t\tOutgoingChanSet: []uint64{\n\t\t\t\t\t\t\tchanID1.ToUint64(),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tloopIn: []*loopdb.LoopIn{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopInContract{\n\t\t\t\t\t\tLastHop: &peer2,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: &swapTraffic{\n\t\t\t\tongoingLoopOut: map[lnwire.ShortChannelID]bool{\n\t\t\t\t\tchanID1: true,\n\t\t\t\t},\n\t\t\t\tongoingLoopIn: map[route.Vertex]bool{\n\t\t\t\t\tpeer2: true,\n\t\t\t\t},\n\t\t\t\t// Make empty maps so that we can assert equal.\n\t\t\t\tfailedLoopOut: make(\n\t\t\t\t\tmap[lnwire.ShortChannelID]time.Time,\n\t\t\t\t),\n\t\t\t\tfailedLoopIn: make(map[route.Vertex]time.Time),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"failure backoff included\",\n\t\t\tloopOut: []*loopdb.LoopOut{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopOutContract{\n\t\t\t\t\t\tOutgoingChanSet: []uint64{\n\t\t\t\t\t\t\tchanID1.ToUint64(),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: failedInBackoff,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopOutContract{\n\t\t\t\t\t\tOutgoingChanSet: []uint64{\n\t\t\t\t\t\t\tchanID2.ToUint64(),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: failedOutsideBackoff,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tloopIn: []*loopdb.LoopIn{\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopInContract{\n\t\t\t\t\t\tLastHop: &peer1,\n\t\t\t\t\t},\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: failedTimeoutInBackoff,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tContract: &loopdb.LoopInContract{\n\t\t\t\t\t\tLastHop: &peer2,\n\t\t\t\t\t},\n\t\t\t\t\tLoop: loopdb.Loop{\n\t\t\t\t\t\tEvents: failedTimeoutOutsideBackoff,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: &swapTraffic{\n\t\t\t\tongoingLoopOut: make(\n\t\t\t\t\tmap[lnwire.ShortChannelID]bool,\n\t\t\t\t),\n\t\t\t\tongoingLoopIn: make(map[route.Vertex]bool),\n\t\t\t\tfailedLoopOut: map[lnwire.ShortChannelID]time.Time{\n\t\t\t\t\tchanID1: withinBackoff,\n\t\t\t\t},\n\t\t\t\tfailedLoopIn: map[route.Vertex]time.Time{\n\t\t\t\t\tpeer1: withinBackoff,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, testCase := range tests {\n\t\tcfg, _ := newTestConfig()\n\t\tm := NewManager(cfg)\n\n\t\tparams := m.GetParameters()\n\t\tparams.FailureBackOff = backoff\n\t\trequire.NoError(t, m.setParameters(context.Background(), params))\n\n\t\tactual := m.currentSwapTraffic(testCase.loopOut, testCase.loopIn)\n\t\trequire.Equal(t, testCase.expected, actual)\n\t}\n}", "func (a *Auditor) CheckTransferRequests(inputs [][]*AuditableToken, outputsFromTransfer [][]*AuditableToken, txID string) error {\n\n\tfor k, transferred := range outputsFromTransfer {\n\t\terr := a.InspectOutputs(transferred)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"audit of %d th transfer in tx [%s] failed\", k, txID)\n\t\t}\n\t}\n\n\tfor k, i := range inputs {\n\t\terr := a.InspectInputs(i)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"audit of %d th transfer in tx [%s] failed\", k, txID)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Test_OtpTestHotpAtCount(t *testing.T) {\n\thotp := testGetHotp(t)\n\tcounterOffset := []int64{0, -1, 1, 12345}\n\n\tfor _, offset := range counterOffset {\n\t\tfor _, data := range referenceRunsHotp {\n\t\t\tsetStateHotp(hotp, data)\n\t\t\tval, err := data.hotp.AtCount(data.counter + offset)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"Test fail before running, illigal parameters:\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif offset == 0 {\n\t\t\t\tif val != data.result {\n\t\t\t\t\tt.Error(\"OTP did not change after incrementing the counter even though all other parameters, including the seed counter, are identical:\", data,\n\t\t\t\t\t\t\"original seed -\", data.counter, \", curent seed -\", data.counter+offset,\n\t\t\t\t\t\t\"but the OTP -\", data.result, \"is different from the resultant OPT -\", val)\n\t\t\t\t} else {\n\t\t\t\t\tt.Log(\"OTP calculated value for the same seed stays the same (as expected)\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif offset != 0 {\n\t\t\t\tif val == data.result {\n\t\t\t\t\tt.Error(\"OTP value did not change when the seed counter changed (all other parameters remained identical) :\", data,\n\t\t\t\t\t\t\"original seed -\", data.counter, \", curent seed -\", data.counter+offset,\n\t\t\t\t\t\t\"but the OTP calculated value was the same\", val)\n\t\t\t\t} else {\n\t\t\t\t\tt.Log(\"OTP calculated value for different seed changed (as expected)\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func TestDirectConnectionFlags(t *testing.T) {\n // Test with the equivalent of a single IP address in the -d arg: -d 1.2.3.4\n gDirects = \"1.2.3.4\"\n dirFuncs := buildDirectors(gDirects)\n director = getDirector(dirFuncs)\n \n ipv4 := \"1.2.3.4\"\n wentDirect,_ := director(ipv4)\n if wentDirect == false {\n t.Errorf(\"The IP address %s should have been sent direct, but instead was proxied\", ipv4)\n }\n\n // now make sure an address that should be proxied still works\n ipv4 = \"4.5.6.7\"\n wentDirect,_ = director(ipv4)\n if wentDirect == true {\n t.Errorf(\"The IP address %s should have been sent to an upstream proxy, but instead was sent directly\", ipv4)\n }\n\n\n // Test with the equivalent of a multiple IP addresses in the -d arg: -d 1.2.3.4,2.3.4.5\n gDirects = \"1.2.3.4,2.3.4.5\"\n dirFuncs = buildDirectors(gDirects)\n director = getDirector(dirFuncs)\n \n addrsToTest := []string{\"1.2.3.4\", \"2.3.4.5\"}\n for _,ipv4 = range addrsToTest {\n wentDirect,_ := director(ipv4)\n if wentDirect == false {\n t.Errorf(\"The IP address %s should have been sent direct, but instead was proxied\", ipv4)\n }\n }\n\n // now make sure an address that should be proxied still works\n ipv4 = \"4.5.6.7\"\n wentDirect,_ = director(ipv4)\n if wentDirect == true {\n t.Errorf(\"The IP address %s should have been sent to an upstream proxy, but instead was sent directly\", ipv4)\n }\n\n\n // Test with the equivalent of multiple IP address specs in the -d arg: -d 1.2.3.0/24,2.3.4.0/25,4.4.4.4\"\n gDirects = \"1.2.3.0/24,2.3.4.0/25,4.4.4.4\"\n dirFuncs = buildDirectors(gDirects)\n director = getDirector(dirFuncs)\n \n addrsToTest = []string{\"1.2.3.4\", \"1.2.3.254\", \"2.3.4.5\", \"4.4.4.4\"}\n for _,ipv4 = range addrsToTest {\n wentDirect,_ := director(ipv4)\n if wentDirect == false {\n t.Errorf(\"The IP address %s should have been sent direct, but instead was proxied\", ipv4)\n }\n }\n\n // now make sure an address that should be proxied still works\n addrsToTest = []string{\"4.5.6.7\", \"2.3.4.254\"}\n for _,ipv4 = range addrsToTest {\n wentDirect,_ = director(ipv4)\n if wentDirect == true {\n t.Errorf(\"The IP address %s should have been sent to an upstream proxy, but instead was sent directly\", ipv4)\n }\n }\n}", "func (s *TestSuite) TestTransaction(t *testing.T) {\n\tconst (\n\t\tvalue1 = \"test-motd-banner\"\n\t\tpath1 = \"/system/config/motd-banner\"\n\t\tvalue2 = \"test-login-banner\"\n\t\tpath2 = \"/system/config/login-banner\"\n\t\tinitValue1 = \"1\"\n\t\tinitValue2 = \"2\"\n\t)\n\n\tvar (\n\t\tpaths = []string{path1, path2}\n\t\tvalues = []string{value1, value2}\n\t\tinitialValues = []string{initValue1, initValue2}\n\t)\n\n\t// Get the configured targets from the environment.\n\ttarget1 := gnmiutils.CreateSimulator(t)\n\tdefer gnmiutils.DeleteSimulator(t, target1)\n\n\t// Wait for config to connect to the targets\n\tgnmiutils.WaitForTargetAvailable(t, topo.ID(target1.Name()), time.Minute)\n\n\ttarget2 := gnmiutils.CreateSimulator(t)\n\tdefer gnmiutils.DeleteSimulator(t, target2)\n\n\t// Wait for config to connect to the targets\n\tgnmiutils.WaitForTargetAvailable(t, topo.ID(target2.Name()), time.Minute)\n\n\ttargets := make([]string, 2)\n\ttargets[0] = target1.Name()\n\ttargets[1] = target2.Name()\n\n\t// Make a GNMI client to use for requests\n\tgnmiClient := gnmiutils.GetGNMIClientOrFail(t)\n\ttargetPathsForGet := gnmiutils.GetTargetPaths(targets, paths)\n\n\t// Set initial values\n\ttargetPathsForInit := gnmiutils.GetTargetPathsWithValues(targets, paths, initialValues)\n\t_, _ = gnmiutils.SetGNMIValueOrFail(t, gnmiClient, targetPathsForInit, gnmiutils.NoPaths, gnmiutils.NoExtensions)\n\tgnmiutils.CheckGNMIValues(t, gnmiClient, targetPathsForGet, initialValues, 0, \"Query after initial set returned the wrong value\")\n\n\t// Create a change that can be rolled back\n\ttargetPathsForSet := gnmiutils.GetTargetPathsWithValues(targets, paths, values)\n\t_, transactionIndex := gnmiutils.SetGNMIValueOrFail(t, gnmiClient, targetPathsForSet, gnmiutils.NoPaths, gnmiutils.SyncExtension(t))\n\n\t// Check that the values were set correctly\n\texpectedValues := []string{value1, value2}\n\tgnmiutils.CheckGNMIValues(t, gnmiClient, targetPathsForGet, expectedValues, 0, \"Query after set returned the wrong value\")\n\n\t// Check that the values are set on the targets\n\ttarget1GnmiClient := gnmiutils.GetTargetGNMIClientOrFail(t, target1)\n\ttarget2GnmiClient := gnmiutils.GetTargetGNMIClientOrFail(t, target2)\n\n\tgnmiutils.CheckTargetValue(t, target1GnmiClient, targetPathsForGet[0:1], value1)\n\tgnmiutils.CheckTargetValue(t, target1GnmiClient, targetPathsForGet[1:2], value2)\n\tgnmiutils.CheckTargetValue(t, target2GnmiClient, targetPathsForGet[2:3], value1)\n\tgnmiutils.CheckTargetValue(t, target2GnmiClient, targetPathsForGet[3:4], value2)\n\n\t// Now rollback the change\n\tadminClient, err := gnmiutils.NewAdminServiceClient()\n\tassert.NoError(t, err)\n\trollbackResponse, rollbackError := adminClient.RollbackTransaction(\n\t\tcontext.Background(), &admin.RollbackRequest{Index: transactionIndex})\n\n\tassert.NoError(t, rollbackError, \"Rollback returned an error\")\n\tassert.NotNil(t, rollbackResponse, \"Response for rollback is nil\")\n\n\t// Check that the values were really rolled back in onos-config\n\texpectedValuesAfterRollback := []string{initValue1, initValue2}\n\tgnmiutils.CheckGNMIValues(t, gnmiClient, targetPathsForGet, expectedValuesAfterRollback, 0, \"Query after rollback returned the wrong value\")\n\n\t// Check that the values were rolled back on the targets\n\tgnmiutils.CheckTargetValue(t, target1GnmiClient, targetPathsForGet[0:1], initValue1)\n\tgnmiutils.CheckTargetValue(t, target1GnmiClient, targetPathsForGet[1:2], initValue2)\n\tgnmiutils.CheckTargetValue(t, target2GnmiClient, targetPathsForGet[2:3], initValue1)\n\tgnmiutils.CheckTargetValue(t, target2GnmiClient, targetPathsForGet[3:4], initValue2)\n}", "func TestCreditEAIIsDeterministic(t *testing.T) {\n\t// set up accounts\n\ttype account struct {\n\t\taddress address.Address\n\t\tprivate signature.PrivateKey\n\t\tpublic signature.PublicKey\n\t}\n\n\tmakeAccount := func() account {\n\t\tpublic, private, err := signature.Generate(signature.Ed25519, nil)\n\t\trequire.NoError(t, err)\n\t\taddr, err := address.Generate(address.KindUser, public.KeyBytes())\n\t\trequire.NoError(t, err)\n\t\treturn account{\n\t\t\taddress: addr,\n\t\t\tprivate: private,\n\t\t\tpublic: public,\n\t\t}\n\t}\n\n\taccts := make([]account, 5)\n\tfor i := range accts {\n\t\taccts[i] = makeAccount()\n\t}\n\n\t// part of the point of the test is to exclude \"solutions\" in which\n\t// two otherwise-equivalent account pairs experience different behavior\n\t// depending on the relative ordering of their addresses. That sort of\n\t// thing would be deterministic, but it wouldn't be fair. Therefore,\n\t// we need to sort the accounts by address to ensure that we have one\n\t// account whose rewards are redirected to another one after it,\n\t// and one whose rewards are redirected to another one before it.\n\t// Therefore, we need to sort these accounts.\n\tsort.Slice(accts, func(i, j int) bool {\n\t\treturn accts[i].address.String() < accts[j].address.String()\n\t})\n\n\ta := accts[0]\n\tb := accts[1]\n\tc := accts[2]\n\td := accts[3]\n\tnode := accts[4]\n\n\t// set up app preconditions\n\tapp, _ := initApp(t)\n\n\tvar txs []tx.Transactable\n\n\tdelegate := func(from account) {\n\t\ttxs = append(txs,\n\t\t\tNewDelegate(from.address, node.address, 1, from.private),\n\t\t)\n\t}\n\n\tredirect := func(from, to account) {\n\t\ttxs = append(txs,\n\t\t\tNewSetRewardsDestination(\n\t\t\t\tfrom.address,\n\t\t\t\tto.address,\n\t\t\t\t2,\n\t\t\t\tfrom.private,\n\t\t\t),\n\t\t)\n\t}\n\n\tsetup := func(acct account, balance math.Ndau, redirectTo *account) {\n\t\tmodify(t, acct.address.String(), app, func(ad *backing.AccountData) {\n\t\t\tad.LastEAIUpdate = 0\n\t\t\tad.LastWAAUpdate = 0\n\t\t\tad.WeightedAverageAge = 0\n\t\t\tad.Balance = balance * constants.NapuPerNdau\n\t\t\t// normally it's enforced that a validation key can't match the\n\t\t\t// ownership key for the account, but it's not important for the\n\t\t\t// behavior under test, and this is simpler instead of having\n\t\t\t// to generate even more keys\n\t\t\tad.ValidationKeys = []signature.PublicKey{acct.public}\n\t\t})\n\t\tif acct.address.String() != node.address.String() {\n\t\t\tdelegate(acct)\n\t\t}\n\t\tif redirectTo != nil {\n\t\t\tredirect(acct, *redirectTo)\n\t\t}\n\t}\n\n\tsetup(a, 1000, &b)\n\tsetup(b, 100, nil)\n\tsetup(c, 100, nil)\n\tsetup(d, 1000, &c)\n\tsetup(node, 10, nil)\n\tapp.UpdateStateImmediately(func(stI metast.State) (metast.State, error) {\n\t\tst := stI.(*backing.State)\n\t\tst.Nodes[node.address.String()] = backing.Node{\n\t\t\tActive: true,\n\t\t}\n\t\treturn st, nil\n\t})\n\n\tresps, _ := deliverTxsContext(t, app, txs, ddc(t).at(math.Timestamp(math.Year)))\n\tfor _, resp := range resps {\n\t\trequire.Equal(t, code.OK, code.ReturnCode(resp.Code))\n\t}\n\n\tt.Logf(\"a: %s\", a.address)\n\tt.Logf(\"b: %s\", b.address)\n\tt.Logf(\"c: %s\", c.address)\n\tt.Logf(\"d: %s\", d.address)\n\tt.Logf(\"node: %s\", node.address)\n\n\tequiv := func(a, b backing.AccountData) {\n\t\trequire.Equal(t, a.Balance, b.Balance)\n\t\trequire.Equal(t, a.LastEAIUpdate, b.LastEAIUpdate)\n\t\trequire.Equal(t, a.LastWAAUpdate, b.LastWAAUpdate)\n\t\trequire.Equal(t, a.WeightedAverageAge, b.WeightedAverageAge)\n\t}\n\n\tcheckState := func() {\n\t\t// given the exact same circumstances, each account data pair must\n\t\t// be identical\n\t\tA, _ := app.getAccount(a.address)\n\t\tB, _ := app.getAccount(b.address)\n\t\tC, _ := app.getAccount(c.address)\n\t\tD, _ := app.getAccount(d.address)\n\n\t\tequiv(A, D)\n\t\tequiv(B, C)\n\t}\n\n\t// we must have set up the initial state of the accounts identically\n\tcheckState()\n\n\t// perform tests\n\t// note: we do _not_ wish to run each iteration here as an independent\n\t// subtest, which is a little unusual. However, the intent here is that\n\t// we don't actually vary the conditions within each test instance; we just\n\t// want some measure of reassurance that we're not just getting lucky\n\t// with random map iteration order.\n\tts := math.Timestamp(math.Year + math.Month)\n\tfor i := uint64(0); i < 128; i++ {\n\t\t// perform a CreditEAI tx\n\t\ttx := NewCreditEAI(node.address, i+5, node.private)\n\n\t\tresp := deliverTxAt(\n\t\t\tt,\n\t\t\tapp,\n\t\t\ttx,\n\t\t\tts,\n\t\t)\n\t\trequire.Equal(t, code.OK, code.ReturnCode(resp.Code))\n\n\t\t// state must still be identical here\n\t\tcheckState()\n\t}\n}", "func testSpendValidation(t *testing.T, tweakless bool) {\n\t// We generate a fake output, and the corresponding txin. This output\n\t// doesn't need to exist, as we'll only be validating spending from the\n\t// transaction that references this.\n\ttxid, err := chainhash.NewHash(testHdSeed.CloneBytes())\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create txid: %v\", err)\n\t}\n\tfundingOut := &wire.OutPoint{\n\t\tHash: *txid,\n\t\tIndex: 50,\n\t}\n\tfakeFundingTxIn := wire.NewTxIn(fundingOut, nil, nil)\n\n\tconst channelBalance = btcutil.Amount(1 * 10e8)\n\tconst csvTimeout = 5\n\n\t// We also set up set some resources for the commitment transaction.\n\t// Each side currently has 1 BTC within the channel, with a total\n\t// channel capacity of 2BTC.\n\taliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(\n\t\tbtcec.S256(), testWalletPrivKey,\n\t)\n\tbobKeyPriv, bobKeyPub := btcec.PrivKeyFromBytes(\n\t\tbtcec.S256(), bobsPrivKey,\n\t)\n\n\trevocationPreimage := testHdSeed.CloneBytes()\n\tcommitSecret, commitPoint := btcec.PrivKeyFromBytes(\n\t\tbtcec.S256(), revocationPreimage,\n\t)\n\trevokePubKey := input.DeriveRevocationPubkey(bobKeyPub, commitPoint)\n\n\taliceDelayKey := input.TweakPubKey(aliceKeyPub, commitPoint)\n\n\t// Bob will have the channel \"force closed\" on him, so for the sake of\n\t// our commitments, if it's tweakless, his key will just be his regular\n\t// pubkey.\n\tbobPayKey := input.TweakPubKey(bobKeyPub, commitPoint)\n\tchannelType := channeldb.SingleFunderBit\n\tif tweakless {\n\t\tbobPayKey = bobKeyPub\n\t\tchannelType = channeldb.SingleFunderTweaklessBit\n\t}\n\n\taliceCommitTweak := input.SingleTweakBytes(commitPoint, aliceKeyPub)\n\tbobCommitTweak := input.SingleTweakBytes(commitPoint, bobKeyPub)\n\n\taliceSelfOutputSigner := &input.MockSigner{\n\t\tPrivkeys: []*btcec.PrivateKey{aliceKeyPriv},\n\t}\n\n\taliceChanCfg := &channeldb.ChannelConfig{\n\t\tChannelConstraints: channeldb.ChannelConstraints{\n\t\t\tDustLimit: DefaultDustLimit(),\n\t\t\tCsvDelay: csvTimeout,\n\t\t},\n\t}\n\n\tbobChanCfg := &channeldb.ChannelConfig{\n\t\tChannelConstraints: channeldb.ChannelConstraints{\n\t\t\tDustLimit: DefaultDustLimit(),\n\t\t\tCsvDelay: csvTimeout,\n\t\t},\n\t}\n\n\t// With all the test data set up, we create the commitment transaction.\n\t// We only focus on a single party's transactions, as the scripts are\n\t// identical with the roles reversed.\n\t//\n\t// This is Alice's commitment transaction, so she must wait a CSV delay\n\t// of 5 blocks before sweeping the output, while bob can spend\n\t// immediately with either the revocation key, or his regular key.\n\tkeyRing := &CommitmentKeyRing{\n\t\tToLocalKey: aliceDelayKey,\n\t\tRevocationKey: revokePubKey,\n\t\tToRemoteKey: bobPayKey,\n\t}\n\tcommitmentTx, err := CreateCommitTx(\n\t\tchannelType, *fakeFundingTxIn, keyRing, aliceChanCfg,\n\t\tbobChanCfg, channelBalance, channelBalance, 0,\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create commitment transaction: %v\", nil)\n\t}\n\n\tdelayOutput := commitmentTx.TxOut[0]\n\tregularOutput := commitmentTx.TxOut[1]\n\n\t// We're testing an uncooperative close, output sweep, so construct a\n\t// transaction which sweeps the funds to a random address.\n\ttargetOutput, err := input.CommitScriptUnencumbered(aliceKeyPub)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create target output: %v\", err)\n\t}\n\tsweepTx := wire.NewMsgTx(2)\n\tsweepTx.AddTxIn(wire.NewTxIn(&wire.OutPoint{\n\t\tHash: commitmentTx.TxHash(),\n\t\tIndex: 0,\n\t}, nil, nil))\n\tsweepTx.AddTxOut(&wire.TxOut{\n\t\tPkScript: targetOutput,\n\t\tValue: 0.5 * 10e8,\n\t})\n\n\t// First, we'll test spending with Alice's key after the timeout.\n\tdelayScript, err := input.CommitScriptToSelf(\n\t\tcsvTimeout, aliceDelayKey, revokePubKey,\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate alice delay script: %v\", err)\n\t}\n\tsweepTx.TxIn[0].Sequence = input.LockTimeToSequence(false, csvTimeout)\n\tsignDesc := &input.SignDescriptor{\n\t\tWitnessScript: delayScript,\n\t\tKeyDesc: keychain.KeyDescriptor{\n\t\t\tPubKey: aliceKeyPub,\n\t\t},\n\t\tSingleTweak: aliceCommitTweak,\n\t\tSigHashes: txscript.NewTxSigHashes(sweepTx),\n\t\tOutput: &wire.TxOut{\n\t\t\tValue: int64(channelBalance),\n\t\t},\n\t\tHashType: txscript.SigHashAll,\n\t\tInputIndex: 0,\n\t}\n\taliceWitnessSpend, err := input.CommitSpendTimeout(\n\t\taliceSelfOutputSigner, signDesc, sweepTx,\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate delay commit spend witness: %v\", err)\n\t}\n\tsweepTx.TxIn[0].Witness = aliceWitnessSpend\n\tvm, err := txscript.NewEngine(delayOutput.PkScript,\n\t\tsweepTx, 0, txscript.StandardVerifyFlags, nil,\n\t\tnil, int64(channelBalance))\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create engine: %v\", err)\n\t}\n\tif err := vm.Execute(); err != nil {\n\t\tt.Fatalf(\"spend from delay output is invalid: %v\", err)\n\t}\n\n\tbobSigner := &input.MockSigner{Privkeys: []*btcec.PrivateKey{bobKeyPriv}}\n\n\t// Next, we'll test bob spending with the derived revocation key to\n\t// simulate the scenario when Alice broadcasts this commitment\n\t// transaction after it's been revoked.\n\tsignDesc = &input.SignDescriptor{\n\t\tKeyDesc: keychain.KeyDescriptor{\n\t\t\tPubKey: bobKeyPub,\n\t\t},\n\t\tDoubleTweak: commitSecret,\n\t\tWitnessScript: delayScript,\n\t\tSigHashes: txscript.NewTxSigHashes(sweepTx),\n\t\tOutput: &wire.TxOut{\n\t\t\tValue: int64(channelBalance),\n\t\t},\n\t\tHashType: txscript.SigHashAll,\n\t\tInputIndex: 0,\n\t}\n\tbobWitnessSpend, err := input.CommitSpendRevoke(bobSigner, signDesc,\n\t\tsweepTx)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to generate revocation witness: %v\", err)\n\t}\n\tsweepTx.TxIn[0].Witness = bobWitnessSpend\n\tvm, err = txscript.NewEngine(delayOutput.PkScript,\n\t\tsweepTx, 0, txscript.StandardVerifyFlags, nil,\n\t\tnil, int64(channelBalance))\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create engine: %v\", err)\n\t}\n\tif err := vm.Execute(); err != nil {\n\t\tt.Fatalf(\"revocation spend is invalid: %v\", err)\n\t}\n\n\t// In order to test the final scenario, we modify the TxIn of the sweep\n\t// transaction to instead point to the regular output (non delay)\n\t// within the commitment transaction.\n\tsweepTx.TxIn[0] = &wire.TxIn{\n\t\tPreviousOutPoint: wire.OutPoint{\n\t\t\tHash: commitmentTx.TxHash(),\n\t\t\tIndex: 1,\n\t\t},\n\t}\n\n\t// Finally, we test bob sweeping his output as normal in the case that\n\t// Alice broadcasts this commitment transaction.\n\tbobScriptP2WKH, err := input.CommitScriptUnencumbered(bobPayKey)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create bob p2wkh script: %v\", err)\n\t}\n\tsignDesc = &input.SignDescriptor{\n\t\tKeyDesc: keychain.KeyDescriptor{\n\t\t\tPubKey: bobKeyPub,\n\t\t},\n\t\tWitnessScript: bobScriptP2WKH,\n\t\tSigHashes: txscript.NewTxSigHashes(sweepTx),\n\t\tOutput: &wire.TxOut{\n\t\t\tValue: int64(channelBalance),\n\t\t\tPkScript: bobScriptP2WKH,\n\t\t},\n\t\tHashType: txscript.SigHashAll,\n\t\tInputIndex: 0,\n\t}\n\tif !tweakless {\n\t\tsignDesc.SingleTweak = bobCommitTweak\n\t}\n\tbobRegularSpend, err := input.CommitSpendNoDelay(\n\t\tbobSigner, signDesc, sweepTx, tweakless,\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create bob regular spend: %v\", err)\n\t}\n\tsweepTx.TxIn[0].Witness = bobRegularSpend\n\tvm, err = txscript.NewEngine(\n\t\tregularOutput.PkScript,\n\t\tsweepTx, 0, txscript.StandardVerifyFlags, nil,\n\t\tnil, int64(channelBalance),\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to create engine: %v\", err)\n\t}\n\tif err := vm.Execute(); err != nil {\n\t\tt.Fatalf(\"bob p2wkh spend is invalid: %v\", err)\n\t}\n}", "func (_IUniswapV2Pair *IUniswapV2PairFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *IUniswapV2PairTransfer, from []common.Address, to []common.Address) (event.Subscription, error) {\r\n\r\n\tvar fromRule []interface{}\r\n\tfor _, fromItem := range from {\r\n\t\tfromRule = append(fromRule, fromItem)\r\n\t}\r\n\tvar toRule []interface{}\r\n\tfor _, toItem := range to {\r\n\t\ttoRule = append(toRule, toItem)\r\n\t}\r\n\r\n\tlogs, sub, err := _IUniswapV2Pair.contract.WatchLogs(opts, \"Transfer\", fromRule, toRule)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\r\n\t\tdefer sub.Unsubscribe()\r\n\t\tfor {\r\n\t\t\tselect {\r\n\t\t\tcase log := <-logs:\r\n\t\t\t\t// New log arrived, parse the event and forward to the user\r\n\t\t\t\tevent := new(IUniswapV2PairTransfer)\r\n\t\t\t\tif err := _IUniswapV2Pair.contract.UnpackLog(event, \"Transfer\", log); err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t\tevent.Raw = log\r\n\r\n\t\t\t\tselect {\r\n\t\t\t\tcase sink <- event:\r\n\t\t\t\tcase err := <-sub.Err():\r\n\t\t\t\t\treturn err\r\n\t\t\t\tcase <-quit:\r\n\t\t\t\t\treturn nil\r\n\t\t\t\t}\r\n\t\t\tcase err := <-sub.Err():\r\n\t\t\t\treturn err\r\n\t\t\tcase <-quit:\r\n\t\t\t\treturn nil\r\n\t\t\t}\r\n\t\t}\r\n\t}), nil\r\n}", "func TestTransitionSystem_UnionOfStates3(t *testing.T) {\n\n\t// Constants\n\tx0 := TransitionSystemState{Name: \"Steven\"}\n\tx1 := TransitionSystemState{Name: \"Gabe\"}\n\tx2 := TransitionSystemState{Name: \"Nosa\"}\n\tx3 := TransitionSystemState{Name: \"Desnor\"}\n\tx4 := TransitionSystemState{Name: \"Nailah\"}\n\tx5 := TransitionSystemState{Name: \"Elon Musk\"}\n\tx6 := TransitionSystemState{Name: \"Jeff Bezos\"}\n\n\tslice1 := []TransitionSystemState{x0, x1, x2}\n\tslice2 := []TransitionSystemState{x2, x3, x4}\n\tslice3 := []TransitionSystemState{x0, x3, x4, x5, x6}\n\n\t// Algorithm\n\tslice4 := UnionOfStates(slice1, slice2, slice3)\n\n\tif len(slice4) != 7 {\n\t\tt.Errorf(\"slice4 does not contain the proper number of elements!\")\n\t}\n\n\tif !x0.In(slice4) {\n\t\tt.Errorf(\"x0 not found in slice4!\")\n\t}\n\n\tif !x1.In(slice4) {\n\t\tt.Errorf(\"x1 not found in slice4!\")\n\t}\n\n\tif !x2.In(slice4) {\n\t\tt.Errorf(\"x2 not found in slice4!\")\n\t}\n\n}", "func TestCount(t *testing.T) {\n\toutputFile, err := ioutil.TempFile(\"\", \"joincap_output_\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\toutputFile.Close()\n\tdefer os.Remove(outputFile.Name())\n\n\terr = joincap([]string{\"joincap\",\n\t\t\"-v\", \"-w\", outputFile.Name(),\n\t\tokPcap, okPcap})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif packetCount(t, outputFile.Name()) != packetCount(t, okPcap)*2 {\n\t\tt.Fatal(\"error counting\")\n\t}\n}", "func (node Node) getOrbitCount() int {\n\tif node.Parent == nil {\n\t\treturn 0\n\t}\n\n\tif (*node.Parent).Name == \"COM\" {\n\t\treturn 1\n\t}\n\n\treturn 1 + (*node.Parent).getOrbitCount()\n}", "func bitcompare(origin []byte, target []byte, bitlen int64) (bool, error) {\n\tvar merchant int64 = bitlen / 8\n\tvar remainder int64 = bitlen % 8\n\t//fmt.Println(\"merchant is \",merchant)\n\t//fmt.Println(\"remainder is \",remainder)\n\tif merchant > 0 {\n\t\tvar iter int64\n\t\tfor iter = 0; iter < merchant; iter++ {\n\t\t\t//fmt.Println(\"origin[\",iter,\"] is \",origin[iter])\n\t\t\t//fmt.Println(\"target[\",iter,\"] is \",target[iter])\n\t\t\tif origin[iter] != target[iter] {\n\t\t\t\treturn false, fmt.Errorf(\"not equal\")\n\t\t\t}\n\t\t}\n\t}\n\tif remainder > 0 {\n\t\t//fmt.Println(\"origin[\",merchant,\"] is \",biu.ByteToBinaryString(origin[merchant]))\n\t\t//fmt.Println(\"target[\",merchant,\"] is \",biu.ByteToBinaryString(target[merchant]))\n\t\tvar aaa byte = origin[merchant] >> (8 - remainder)\n\t\tvar bbb byte = target[merchant] >> (8 - remainder)\n\t\t//fmt.Println(\"aaa is \",biu.ByteToBinaryString(aaa))\n\t\t//fmt.Println(\"bbb is \",biu.ByteToBinaryString(bbb))\n\t\tif aaa != bbb {\n\t\t\treturn false, fmt.Errorf(\"not equal\")\n\t\t}\n\t}\n\treturn true, fmt.Errorf(\"equal\")\n}", "func Test_OtpTestHotpAccuracy(t *testing.T) {\n\thotp := testGetHotp(t)\n\tshift := int64(5)\n\n\tfor _, data := range referenceRunsHotp {\n\t\tdata.hotp.Count = data.hotp.Count - shift - 1\n\t\tsetStateHotp(hotp, data)\n\t\tfor i := -shift; i < shift+1; i++ {\n\t\t\tval, err := data.hotp.Next()\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"Test fail before running, illigal parameters:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i != 0 && val == data.result {\n\t\t\t\tt.Error(\"OTP value did not change when the seed counter changed\",\n\t\t\t\t\t\"(all other parameters remained identical) :\", data,\n\t\t\t\t\t\"but the OTP calculated value was the same:\", val)\n\t\t\t}\n\t\t\tif i == 0 && val != data.result {\n\t\t\t\tt.Error(\"OTP value modified even though all parameters\",\n\t\t\t\t\t\"as well as the counter value and seed counter are identical: \", data,\n\t\t\t\t\t\"OTP\", val, \"is different from the result OTP:\", data.result)\n\t\t\t}\n\t\t}\n\t}\n}", "func (bobsMap BobsMap) TestRoute(steps []int) float64 {\n\tcount := len(steps)\n\tcurrentPos := utils.New(bobsMap.startX, bobsMap.startY)\n\tfor index := 0; index < count; index++ {\n\t\tcurrentPos = move(bobsMap.bobMap, currentPos, steps[index])\n\t}\n\treturn bobsMap.calcFitness(currentPos)\n}", "func TestWIFToBech32(t *testing.T) {\n\n\tvar tests = []struct {\n\t\tassetSymbol string\n\t\twif string\n\t\tbech32address string\n\t}{\n\t\t{assetSymbol: \"via\", wif: \"WXJxG7n4FcWE6shiMN6fedUwMqEFZXWuupGg5P96iYxgmcxCtxoT\", bech32address: \"via1qkh4zuddx9laq8qmerajmkxj42tugjyrccktclf\"}, // viacoin\n\t\t//{assetSymbol: \"ltc\", addressPrefix: \"L\", wif: \"T8VERgAiBcUnRXmWxgVzp6AaH1hKwPQQQeghi3n9ZY6nF59GuTJf\", compressedPublicKey: \"LV7LV7Z4bWDEjYkfx9dQo6k6RjGbXsg6hS\"}, // litecoin\n\t}\n\n\tfor _, pair := range tests {\n\t\tasset, _ := bcoins.SelectAsset(pair.assetSymbol)\n\t\twif, _ := FromWIF(pair.wif)\n\n\t\tbech32Address := WIFToBech32(wif, asset.Network.Bech32HRPSegwit)\n\n\t\tif bech32Address != pair.bech32address {\n\t\t\tt.Errorf(\"For %s expected %s got %s\", asset.Name, pair.bech32address, bech32Address)\n\t\t}\n\t}\n}", "func TestCountInputFile(t *testing.T) {\n\t_o = opts{\n\t\t\"./final.txt\",\n\t\tfalse,\n\t}\n\tgot := valueByInput(_o.filePath)\n\twant := 484\n\n\tif got != want {\n\t\tt.Errorf(\"Count orbits = %d; want %d\", got, want)\n\t}\n}", "func TestPrepareFaucet(t *testing.T) {\n\tprevPoWDiff := framework.ParaPoWDifficulty\n\tprevFaucetPreparedOutputsCount := framework.ParaFaucetPreparedOutputsCount\n\tframework.ParaPoWDifficulty = 0\n\tframework.ParaFaucetPreparedOutputsCount = 10\n\tdefer func() {\n\t\tframework.ParaPoWDifficulty = prevPoWDiff\n\t\tframework.ParaFaucetPreparedOutputsCount = prevFaucetPreparedOutputsCount\n\t}()\n\tn, err := f.CreateNetwork(\"faucet_testPrepareGenesis\", 0, 0, framework.CreateNetworkConfig{Faucet: true})\n\trequire.NoError(t, err)\n\tdefer tests.ShutdownNetwork(t, n)\n\n\tfaucet, err := n.CreatePeer(framework.GoShimmerConfig{\n\t\tSeed: \"3YX6e7AL28hHihZewKdq6CMkEYVsTJBLgRiprUNiNq5E\",\n\t\tFaucet: true,\n\t\tMana: true,\n\t\tActivityPlugin: true,\n\t})\n\trequire.NoError(t, err)\n\ttime.Sleep(5 * time.Second)\n\n\t// Tests genesis output is split into 10 outputs. [1,2,...10] and balance,\n\tconst genesisBalance = int64(1000000000000000)\n\tvar totalSplit int64\n\tvar i uint64\n\tfor i = 1; i <= 10; i++ {\n\t\taddr := faucet.Seed.Address(i).Address().Base58()\n\t\toutputs, err := faucet.GetUnspentOutputs([]string{addr})\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, framework.ParaFaucetTokensPerRequest, outputs.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\t\ttotalSplit += framework.ParaFaucetTokensPerRequest\n\t}\n\tbalance := genesisBalance - totalSplit\n\tfaucetAddr := faucet.Seed.Address(0).Address().Base58()\n\toutputs, err := faucet.GetUnspentOutputs([]string{faucetAddr})\n\trequire.NoError(t, err)\n\tassert.Equal(t, balance, outputs.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\n\t// add 1 node to the network\n\tpeer, err := n.CreatePeer(framework.GoShimmerConfig{\n\t\tMana: true,\n\t\tActivityPlugin: true,\n\t})\n\trequire.NoError(t, err)\n\n\terr = n.WaitForAutopeering(1)\n\trequire.NoError(t, err)\n\ttime.Sleep(5 * time.Second)\n\n\t// issue 9 requests to consume the 1st 9 faucet prepared outputs.\n\tfor i = 0; i < 9; i++ {\n\t\taddr := peer.Address(i).Address()\n\t\ttests.SendFaucetRequest(t, peer, addr)\n\t}\n\ttime.Sleep(5 * time.Second)\n\n\t// 1 prepared output is left on the 10th address.\n\tlastPreparedOutputAddress := faucet.Seed.Address(10).Address().Base58()\n\tlastPreparedOutput, err := faucet.GetUnspentOutputs([]string{lastPreparedOutputAddress})\n\trequire.NoError(t, err)\n\tassert.Equal(t, framework.ParaFaucetTokensPerRequest, lastPreparedOutput.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\n\t// check balance is untouched\n\tbalanceOutputAddress := faucet.Seed.Address(0).Address().Base58()\n\tbalanceOutput, err := faucet.GetUnspentOutputs([]string{balanceOutputAddress})\n\trequire.NoError(t, err)\n\tassert.Equal(t, genesisBalance-(10*framework.ParaFaucetTokensPerRequest), balanceOutput.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\n\t// issue 2 more request to split the remainder balance.\n\taddr := peer.Seed.Address(10).Address()\n\ttests.SendFaucetRequest(t, peer, addr)\n\taddr = peer.Seed.Address(11).Address()\n\ttests.SendFaucetRequest(t, peer, addr)\n\ttime.Sleep(2 * time.Second)\n\n\t// check split of balance [0] to [11...20]\n\t_addr := faucet.Seed.Address(0).Address().Base58()\n\toutputs, err = faucet.GetUnspentOutputs([]string{_addr})\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, len(outputs.UnspentOutputs[0].OutputIDs)) // 1 output is unspent.\n\tassert.Equal(t, genesisBalance-20*framework.ParaFaucetTokensPerRequest, outputs.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\n\tfor i := 11; i < 21; i++ {\n\t\t_addr := faucet.Seed.Address(uint64(i)).Address().Base58()\n\t\toutputs, err = faucet.GetUnspentOutputs([]string{_addr})\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, framework.ParaFaucetTokensPerRequest, outputs.UnspentOutputs[0].OutputIDs[0].Balances[0].Value)\n\t}\n\n}", "func TestOperationMaps(t *testing.T) {\n\n\t// Test OperationValue map\n\tfor opName, opValue := range goHamlib.VFOOperationValue {\n\t\t_, ok := goHamlib.VFOOperationName[opValue]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Operation %d does not exist in OperationName map\", opValue)\n\t\t}\n\t\tif opName != goHamlib.VFOOperationName[opValue] {\n\t\t\tt.Fatalf(\"Name of Operation inconsisted: %s\", opName)\n\t\t}\n\t}\n\n\t// Test OperationName map\n\tfor opValue, opName := range goHamlib.VFOOperationName {\n\t\t_, ok := goHamlib.VFOOperationValue[opName]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Operation %s does not exist in OperationValue map\", opName)\n\t\t}\n\t\tif opValue != goHamlib.VFOOperationValue[opName] {\n\t\t\tt.Fatalf(\"Value of Operation inconsisted: %s\", opName)\n\t\t}\n\t}\n}", "func TestCopyRedownload(t *testing.T) {\n\tctx := context.Background()\n\tr := fstest.NewRun(t)\n\tfile1 := r.WriteObject(ctx, \"sub dir/hello world\", \"hello world\", t1)\n\tr.CheckRemoteItems(t, file1)\n\n\terr := CopyDir(ctx, r.Flocal, r.Fremote, false)\n\trequire.NoError(t, err)\n\n\t// Test with combined precision of local and remote as we copied it there and back\n\tr.CheckLocalListing(t, []fstest.Item{file1}, nil)\n}" ]
[ "0.564611", "0.5462996", "0.534616", "0.52163875", "0.517318", "0.50357795", "0.5010304", "0.5008597", "0.48869094", "0.486768", "0.4847041", "0.48416877", "0.4822357", "0.4819212", "0.48114702", "0.48098993", "0.47887498", "0.4779793", "0.47781554", "0.47707003", "0.4744534", "0.47345686", "0.47260123", "0.47055373", "0.46875143", "0.46851876", "0.46758604", "0.46531954", "0.4649877", "0.4606659", "0.45655513", "0.45564246", "0.4555164", "0.45481557", "0.45421645", "0.4539696", "0.45287248", "0.45236462", "0.45196685", "0.45148122", "0.45121458", "0.45085034", "0.44980693", "0.44975463", "0.4495451", "0.44929713", "0.44891816", "0.4488343", "0.44851512", "0.44751343", "0.4462556", "0.44587883", "0.44442168", "0.44383842", "0.440331", "0.4401428", "0.4398556", "0.4398427", "0.4393108", "0.43855286", "0.43840694", "0.43777922", "0.4377346", "0.4368991", "0.43671584", "0.4362274", "0.43614247", "0.435715", "0.43489537", "0.43450168", "0.43441057", "0.43378517", "0.43375295", "0.43359098", "0.43356097", "0.4322724", "0.43171987", "0.43167806", "0.43158904", "0.43067232", "0.4306389", "0.4299842", "0.4298744", "0.42969123", "0.4293967", "0.42932087", "0.42903778", "0.42852804", "0.42778498", "0.42748228", "0.4273856", "0.4272915", "0.42713854", "0.42692855", "0.4266016", "0.42639998", "0.42637372", "0.42632183", "0.4262695", "0.42611605" ]
0.7883621
0
genKubeconfig used to genearte kube config file we can provide multiple contexts as well
func genKubeconfig(contexts ...string) string { var sb strings.Builder sb.WriteString(`--- apiVersion: v1 kind: Config clusters: `) for _, ctx := range contexts { sb.WriteString(`- cluster: server: ` + ctx + ` name: ` + ctx + ` `) } sb.WriteString("contexts:\n") for _, ctx := range contexts { sb.WriteString(`- context: cluster: ` + ctx + ` user: ` + ctx + ` name: ` + ctx + ` `) } sb.WriteString("users:\n") for _, ctx := range contexts { sb.WriteString(`- name: ` + ctx + ` `) } sb.WriteString("preferences: {}\n") if len(contexts) > 0 { sb.WriteString("current-context: " + contexts[0] + "\n") } return sb.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GenerateKubeconfig(restConfig *rest.Config) (clientcmdapi.Config, error) {\n\tconst defaultID = \"default\"\n\n\tvar (\n\t\tcaData = restConfig.TLSClientConfig.CAData\n\t\tcertData = restConfig.TLSClientConfig.CertData\n\t\tkeyData = restConfig.TLSClientConfig.KeyData\n\n\t\tbearerToken = restConfig.BearerToken\n\t)\n\tif len(restConfig.TLSClientConfig.CAFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.CAFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read ca from %q: %w\", restConfig.TLSClientConfig.CAFile, err)\n\t\t}\n\t\tcaData = data\n\t}\n\tif len(restConfig.TLSClientConfig.CertFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.CertFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read cert from %q: %w\", restConfig.TLSClientConfig.CertFile, err)\n\t\t}\n\t\tcertData = data\n\t}\n\tif len(restConfig.TLSClientConfig.KeyFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.KeyFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read key from %q: %w\", restConfig.TLSClientConfig.KeyFile, err)\n\t\t}\n\t\tkeyData = data\n\t}\n\tif len(restConfig.BearerTokenFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.BearerTokenFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read bearer token from %q: %w\", restConfig.BearerTokenFile, err)\n\t\t}\n\t\tbearerToken = string(data)\n\t}\n\n\tcfg := clientcmdapi.Config{\n\t\tAPIVersion: \"v1\",\n\t\tKind: \"Config\",\n\t\tCurrentContext: defaultID,\n\t\tContexts: map[string]*clientcmdapi.Context{\n\t\t\tdefaultID: {\n\t\t\t\tCluster: defaultID,\n\t\t\t\tAuthInfo: defaultID,\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{\n\t\t\tdefaultID: {\n\t\t\t\tToken: bearerToken,\n\n\t\t\t\tUsername: restConfig.Username,\n\t\t\t\tPassword: restConfig.Password,\n\n\t\t\t\tClientCertificateData: certData,\n\t\t\t\tClientKeyData: keyData,\n\t\t\t},\n\t\t},\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\tdefaultID: {\n\t\t\t\tServer: restConfig.Host + restConfig.APIPath,\n\t\t\t\tCertificateAuthorityData: caData,\n\t\t\t\tInsecureSkipTLSVerify: restConfig.Insecure,\n\t\t\t},\n\t\t},\n\t}\n\treturn cfg, nil\n}", "func createKubeconfig(clusterName, username, clusterControlPlaceAddress, caBasebase64, crtBase64, privateKeyBase64 string) (kubeconfigYAML string) {\n\tcertificate_tpl := `---\napiVersion: v1\nkind: Config\ncurrent-context: %s\nclusters:\n - name: %s\n cluster:\n server: %s\n certificate-authority-data: %s\ncontexts:\n - context:\n cluster: %s\n user: %s\n name: %s@%s\nusers:\n - name: %s\n user:\n client-certificate-data: %s\n client-key-data: %s`\n\n\treturn fmt.Sprintf(certificate_tpl,\n\t\tclusterName,\n\t\tclusterName,\n\t\tclusterControlPlaceAddress,\n\t\tcaBasebase64,\n\t\tclusterName,\n\t\tusername,\n\t\tusername,\n\t\tclusterName,\n\t\tusername,\n\t\tcrtBase64,\n\t\tprivateKeyBase64,\n\t)\n}", "func GenerateConfig(w http.ResponseWriter, r *http.Request) {\n\terr, auth := basicAuth(r)\n\n\tif err != nil {\n\t\tutils.Log.Info().Err(err)\n\t\tutils.Log.Info().Msg(err.Error())\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tio.WriteString(w, \"Basic Auth: Invalid credentials\")\n\n\t}\n\n\ttoken, err := baseGenerateToken(*auth)\n\tif err == nil {\n\t\tutils.Log.Info().Msgf(\"Granting token for user %v\", auth.Username)\n\t} else {\n\t\tutils.Log.Error().Msgf(\"Granting token fail for user %v\", auth.Username)\n\t}\n\n\tif err != nil {\n\t\tutils.Log.Info().Err(err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tconfig := &types.KubeConfig{\n\t\tApiVersion: \"v1\",\n\t\tKind: \"Config\",\n\t\tClusters: []types.KubeConfigCluster{\n\t\t\t{\n\t\t\t\tName: \"kubernetes\",\n\t\t\t\tCluster: types.KubeConfigClusterData{\n\t\t\t\t\tServer: utils.Config.PublicApiServerURL,\n\t\t\t\t\tCertificateData: utils.Config.KubeCa,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCurrentContext: \"kubernetes\" + \"-\" + auth.Username,\n\t\tContexts: []types.KubeConfigContext{\n\t\t\t{\n\t\t\t\tName: \"kubernetes\" + \"-\" + auth.Username,\n\t\t\t\tContext: types.KubeConfigContextData{\n\t\t\t\t\tCluster: \"kubernetes\",\n\t\t\t\t\tUser: auth.Username,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tUsers: []types.KubeConfigUser{\n\t\t\t{\n\t\t\t\tUser: types.KubeConfigUserToken{Token: *token},\n\t\t\t\tName: auth.Username},\n\t\t},\n\t}\n\n\tyml, err := yaml.Marshal(config)\n\n\tutils.Log.Error().Err(err)\n\tw.WriteHeader(http.StatusCreated)\n\tw.Header().Set(\"Content-Type\", \"text/x-yaml; charset=utf-8\")\n\tw.Write(yml)\n\n}", "func writeKubeconfig(kubeconfig []byte, contextName string, path string) error {\n\n\tyamlConfig := models.Kubeconfig{}\n\terr := yaml.Unmarshal(kubeconfig, &yamlConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tyamlConfig.CurrentContext = contextName\n\n\td, err := yaml.Marshal(yamlConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(path, d, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetupKubeconfig(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n kubeconfig := terraform.Output(t, terraformOptions, \"kubeconfig\")\n kubeconfigFile := CreateTempFile(t, []byte(kubeconfig))\n kubectlOptions := k8s.NewKubectlOptions(\"\", kubeconfigFile.Name(), \"default\")\n test_structure.SaveKubectlOptions(t, terraformDir, kubectlOptions)\n}", "func getKubeConfigSubCommands(out io.Writer, outDir, defaultKubernetesVersion string) []*cobra.Command {\n\n\tcfg := &kubeadmapiv1alpha3.InitConfiguration{}\n\n\t// Default values for the cobra help text\n\tkubeadmscheme.Scheme.Default(cfg)\n\n\tvar cfgPath, token, clientName string\n\tvar organizations []string\n\tvar subCmds []*cobra.Command\n\n\tsubCmdProperties := []struct {\n\t\tuse string\n\t\tshort string\n\t\tlong string\n\t\texamples string\n\t\tcmdFunc func(outDir string, cfg *kubeadmapi.InitConfiguration) error\n\t}{\n\t\t{\n\t\t\tuse: \"all\",\n\t\t\tshort: \"Generates all kubeconfig files necessary to establish the control plane and the admin kubeconfig file\",\n\t\t\tlong: allKubeconfigLongDesc,\n\t\t\texamples: allKubeconfigExample,\n\t\t\tcmdFunc: kubeconfigphase.CreateInitKubeConfigFiles,\n\t\t},\n\t\t{\n\t\t\tuse: \"admin\",\n\t\t\tshort: \"Generates a kubeconfig file for the admin to use and for kubeadm itself\",\n\t\t\tlong: adminKubeconfigLongDesc,\n\t\t\tcmdFunc: kubeconfigphase.CreateAdminKubeConfigFile,\n\t\t},\n\t\t{\n\t\t\tuse: \"kubelet\",\n\t\t\tshort: \"Generates a kubeconfig file for the kubelet to use. Please note that this should be used *only* for bootstrapping purposes\",\n\t\t\tlong: kubeletKubeconfigLongDesc,\n\t\t\tcmdFunc: kubeconfigphase.CreateKubeletKubeConfigFile,\n\t\t},\n\t\t{\n\t\t\tuse: \"controller-manager\",\n\t\t\tshort: \"Generates a kubeconfig file for the controller manager to use\",\n\t\t\tlong: controllerManagerKubeconfigLongDesc,\n\t\t\tcmdFunc: kubeconfigphase.CreateControllerManagerKubeConfigFile,\n\t\t},\n\t\t{\n\t\t\tuse: \"scheduler\",\n\t\t\tshort: \"Generates a kubeconfig file for the scheduler to use\",\n\t\t\tlong: schedulerKubeconfigLongDesc,\n\t\t\tcmdFunc: kubeconfigphase.CreateSchedulerKubeConfigFile,\n\t\t},\n\t\t{\n\t\t\tuse: \"user\",\n\t\t\tshort: \"Outputs a kubeconfig file for an additional user\",\n\t\t\tlong: userKubeconfigLongDesc,\n\t\t\texamples: userKubeconfigExample,\n\t\t\tcmdFunc: func(outDir string, cfg *kubeadmapi.InitConfiguration) error {\n\t\t\t\tif clientName == \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"missing required argument --client-name\")\n\t\t\t\t}\n\n\t\t\t\t// if the kubeconfig file for an additional user has to use a token, use it\n\t\t\t\tif token != \"\" {\n\t\t\t\t\treturn kubeconfigphase.WriteKubeConfigWithToken(out, cfg, clientName, token)\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, write a kubeconfig file with a generate client cert\n\t\t\t\treturn kubeconfigphase.WriteKubeConfigWithClientCert(out, cfg, clientName, organizations)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, properties := range subCmdProperties {\n\t\t// Creates the UX Command\n\t\tcmd := &cobra.Command{\n\t\t\tUse: properties.use,\n\t\t\tShort: properties.short,\n\t\t\tLong: properties.long,\n\t\t\tExample: properties.examples,\n\t\t\tRun: runCmdPhase(properties.cmdFunc, &outDir, &cfgPath, cfg, defaultKubernetesVersion),\n\t\t}\n\n\t\t// Add flags to the command\n\t\tif properties.use != \"user\" {\n\t\t\tcmd.Flags().StringVar(&cfgPath, \"config\", cfgPath, \"Path to kubeadm config file. WARNING: Usage of a configuration file is experimental\")\n\t\t}\n\t\tcmd.Flags().StringVar(&cfg.CertificatesDir, \"cert-dir\", cfg.CertificatesDir, \"The path where certificates are stored\")\n\t\tcmd.Flags().StringVar(&cfg.APIEndpoint.AdvertiseAddress, \"apiserver-advertise-address\", cfg.APIEndpoint.AdvertiseAddress, \"The IP address the API server is accessible on\")\n\t\tcmd.Flags().Int32Var(&cfg.APIEndpoint.BindPort, \"apiserver-bind-port\", cfg.APIEndpoint.BindPort, \"The port the API server is accessible on\")\n\t\tcmd.Flags().StringVar(&outDir, \"kubeconfig-dir\", outDir, \"The path where to save the kubeconfig file\")\n\t\tif properties.use == \"all\" || properties.use == \"kubelet\" {\n\t\t\tcmd.Flags().StringVar(&cfg.NodeRegistration.Name, \"node-name\", cfg.NodeRegistration.Name, `The node name that should be used for the kubelet client certificate`)\n\t\t}\n\t\tif properties.use == \"user\" {\n\t\t\tcmd.Flags().StringVar(&token, \"token\", token, \"The token that should be used as the authentication mechanism for this kubeconfig, instead of client certificates\")\n\t\t\tcmd.Flags().StringVar(&clientName, \"client-name\", clientName, \"The name of user. It will be used as the CN if client certificates are created\")\n\t\t\tcmd.Flags().StringSliceVar(&organizations, \"org\", organizations, \"The orgnizations of the client certificate. It will be used as the O if client certificates are created\")\n\t\t}\n\n\t\tsubCmds = append(subCmds, cmd)\n\t}\n\n\treturn subCmds\n}", "func GenerateKubeconfigFromTokenSecret(clusterName string, contextNamespace string, apiServerHost string, secret *corev1.Secret) ([]byte, error) {\n\tif apiServerHost == \"\" {\n\t\treturn nil, errors.New(\"api server host is required\")\n\t}\n\n\tmatched, _ := regexp.MatchString(`^https:\\/\\/localhost:\\d{1,5}$`, apiServerHost)\n\tif matched {\n\t\tapiServerHost = \"https://kubernetes.default.svc.cluster.local\"\n\t}\n\n\ttoken, ok := secret.Data[corev1.ServiceAccountTokenKey]\n\tif !ok {\n\t\treturn nil, errors.New(\"no \" + corev1.ServiceAccountTokenKey + \" found on secret\")\n\t}\n\n\tkubeConfig := &clientcmdv1.Config{\n\t\tAPIVersion: \"v1\",\n\t\tKind: \"Config\",\n\t\tPreferences: clientcmdv1.Preferences{\n\t\t\tColors: false,\n\t\t},\n\t\tClusters: []clientcmdv1.NamedCluster{\n\t\t\t{\n\t\t\t\tName: clusterName,\n\t\t\t\tCluster: clientcmdv1.Cluster{\n\t\t\t\t\tServer: apiServerHost,\n\t\t\t\t\tInsecureSkipTLSVerify: false,\n\t\t\t\t\tCertificateAuthorityData: secret.Data[corev1.ServiceAccountRootCAKey],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tAuthInfos: []clientcmdv1.NamedAuthInfo{\n\t\t\t{\n\t\t\t\tName: clusterName,\n\t\t\t\tAuthInfo: clientcmdv1.AuthInfo{\n\t\t\t\t\tToken: string(token),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tContexts: []clientcmdv1.NamedContext{\n\t\t\t{\n\t\t\t\tName: clusterName,\n\t\t\t\tContext: clientcmdv1.Context{\n\t\t\t\t\tCluster: clusterName,\n\t\t\t\t\tAuthInfo: clusterName,\n\t\t\t\t\tNamespace: contextNamespace,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCurrentContext: clusterName,\n\t}\n\n\treturn yaml.Marshal(kubeConfig)\n}", "func GenerateKubectlConfig(apiVersion string, kubeAPI string, kubeCA string, environment string, user *KubectlUser) *KubectlConfig {\n\tcluster := &KubectlCluster{\n\t\tName: environment,\n\t\tCluster: &KubectlClusterData{\n\t\t\tServer: kubeAPI,\n\t\t\tCertificateAuthorityData: kubeCA,\n\t\t},\n\t}\n\tcontext := &KubectlContext{\n\t\tName: cluster.Name,\n\t\tContext: &KubectlContextData{\n\t\t\tCluster: cluster.Name,\n\t\t\tUser: user.Name,\n\t\t},\n\t}\n\treturn &KubectlConfig{\n\t\tAPIVersion: apiVersion,\n\t\tClusters: []*KubectlCluster{cluster},\n\t\tContexts: []*KubectlContext{context},\n\t\tCurrentContext: cluster.Name,\n\t\tKind: \"Config\",\n\t\tUsers: []*KubectlUser{user},\n\t}\n}", "func writeKubeconfig(cfg *rest.Config) {\n\ttemplate := `# Kubeconfig file for Calico CNI plugin. Installed by calico/node.\napiVersion: v1\nkind: Config\nclusters:\n- name: local\n cluster:\n server: %s\n certificate-authority-data: \"%s\"\nusers:\n- name: calico\n user:\n token: %s\ncontexts:\n- name: calico-context\n context:\n cluster: local\n user: calico\ncurrent-context: calico-context`\n\n\t// Replace the placeholders.\n\tdata := fmt.Sprintf(template, cfg.Host, string(base64.StdEncoding.EncodeToString(cfg.CAData)), cfg.BearerToken)\n\n\t// Write the filled out config to disk.\n\tif err := ioutil.WriteFile(kubeconfigPath, []byte(data), 0600); err != nil {\n\t\tlogrus.WithError(err).Error(\"Failed to write CNI plugin kubeconfig file\")\n\t\treturn\n\t}\n\tlogrus.WithField(\"path\", kubeconfigPath).Info(\"Wrote updated CNI kubeconfig file.\")\n}", "func createKubeConfig(esvc EKSAPI, ssvc STSAPI, secsvc SecretsManagerAPI, cluster *string, kubeconfig *string, customKubeconfig []byte) error {\n\tswitch {\n\tcase cluster != nil && kubeconfig != nil:\n\t\treturn errors.New(\"both ClusterID or KubeConfig can not be specified\")\n\tcase cluster != nil:\n\t\tdefaultConfig := api.NewConfig()\n\t\tc, err := getClusterDetails(esvc, *cluster)\n\t\tif err != nil {\n\t\t\treturn genericError(\"Getting Cluster details\", err)\n\t\t}\n\t\tdefaultConfig.Clusters[*cluster] = &api.Cluster{\n\t\t\tServer: c.endpoint,\n\t\t\tCertificateAuthorityData: []byte(c.CAData),\n\t\t}\n\t\ttoken, err := generateKubeToken(ssvc, cluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefaultConfig.AuthInfos[\"aws\"] = &api.AuthInfo{\n\t\t\tToken: *token,\n\t\t}\n\t\tdefaultConfig.Contexts[\"aws\"] = &api.Context{\n\t\t\tCluster: *cluster,\n\t\t\tAuthInfo: \"aws\",\n\t\t}\n\t\tdefaultConfig.CurrentContext = \"aws\"\n\t\tlog.Printf(\"Writing kubeconfig file to %s\", KubeConfigLocalPath)\n\n\t\terr = clientcmd.WriteToFile(*defaultConfig, KubeConfigLocalPath)\n\t\tif err != nil {\n\t\t\treturn genericError(\"Write file: \", err)\n\t\t}\n\t\treturn nil\n\tcase kubeconfig != nil:\n\t\ts, err := getSecretsManager(secsvc, kubeconfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"Writing kubeconfig file to %s\", KubeConfigLocalPath)\n\t\terr = ioutil.WriteFile(KubeConfigLocalPath, s, 0600)\n\t\tif err != nil {\n\t\t\treturn genericError(\"Write file: \", err)\n\t\t}\n\t\treturn nil\n\tcase customKubeconfig != nil:\n\t\tlog.Printf(\"Writing kubeconfig file to %s\", KubeConfigLocalPath)\n\t\terr := ioutil.WriteFile(KubeConfigLocalPath, customKubeconfig, 0600)\n\t\tif err != nil {\n\t\t\treturn genericError(\"Write file: \", err)\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"either ClusterID or KubeConfig must be specified\")\n\t}\n}", "func newKubeClientConfig() (*client.Config, error) {\n\tvar (\n\t\tconfig *client.Config\n\t\terr error\n\t\tapiServerURL string\n\t)\n\t// If the user specified --kube-apiserver-url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tapiServerURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif apiServerURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube-apiserver-url was provided.\n\t\tconfig = &client.Config{\n\t\t\tHost: apiServerURL,\n\t\t\tVersion: \"v1\",\n\t\t}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube-apiserver-url and --kubecfg-file\n\t\t// 2) just --kubecfg-file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &clientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = apiServerURL // might be \"\", but that is OK\n\t\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tglog.Infof(\"Using %s for kubernetes API server\", config.Host)\n\tglog.Infof(\"Using kubernetes API version %s\", config.Version)\n\n\treturn config, nil\n}", "func GenerateKubeconfigFromRestConfig(cfg *rest.Config, name string) ([]byte, error) {\n\tvalues := map[string]interface{}{\n\t\t\"APIServerURL\": cfg.Host,\n\t\t\"CACertificate\": utils.EncodeBase64(cfg.TLSClientConfig.CAData),\n\t\t\"ClientCertificate\": utils.EncodeBase64(cfg.TLSClientConfig.CertData),\n\t\t\"ClientKey\": utils.EncodeBase64(cfg.TLSClientConfig.KeyData),\n\t\t\"ClusterName\": name,\n\t}\n\n\tif cfg.Username != \"\" && cfg.Password != \"\" {\n\t\tvalues[\"BasicAuthUsername\"] = cfg.Username\n\t\tvalues[\"BasicAuthPassword\"] = cfg.Password\n\t}\n\n\treturn utils.RenderLocalTemplate(kubeconfigTemplate, values)\n}", "func KubeletConfigGenerator() gopter.Gen {\n\tif kubeletConfigGenerator != nil {\n\t\treturn kubeletConfigGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tAddIndependentPropertyGeneratorsForKubeletConfig(generators)\n\tkubeletConfigGenerator = gen.Struct(reflect.TypeOf(KubeletConfig{}), generators)\n\n\treturn kubeletConfigGenerator\n}", "func (kcm *KubeConfigBuilder) GenerateKubeConfig(credential Credential, server, user string) (*string, error) {\n\n\tcertificateBase64 := kcm.generateBase64(credential.certificatePEM)\n\tclientKeyBase64 := kcm.generateBase64(credential.clientKeyPEM)\n\tcaBase64 := kcm.generateBase64(credential.certificateAuthority)\n\n\ttemplate, err := template.New(\"kubeconfig\").Parse(kubeConfigTemplate)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar kubeConfigBuffer bytes.Buffer\n\n\tkubeConfigData := struct {\n\t\tCA string\n\t\tServer string\n\t\tClusterName string\n\t\tUser string\n\t\tClientCertificate string\n\t\tClientKey string\n\t}{\n\t\tCA: caBase64,\n\t\tServer: server,\n\t\tClusterName: credential.clusterName,\n\t\tUser: user,\n\t\tClientCertificate: certificateBase64,\n\t\tClientKey: clientKeyBase64,\n\t}\n\n\terr = template.Execute(&kubeConfigBuffer, kubeConfigData)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeConfig := kubeConfigBuffer.String()\n\n\treturn &kubeConfig, nil\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func KubeConfigFn(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar path, clusterCtxName string\n\tvar provider *starlarkstruct.Struct\n\n\tif err := starlark.UnpackArgs(\n\t\tidentifiers.kubeCfg, args, kwargs,\n\t\t\"cluster_context?\", &clusterCtxName,\n\t\t\"path?\", &path,\n\t\t\"capi_provider?\", &provider,\n\t); err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"%s: %s\", identifiers.kubeCfg, err)\n\t}\n\n\t// check if only one of the two options are present\n\tif (len(path) == 0 && provider == nil) || (len(path) != 0 && provider != nil) {\n\t\treturn starlark.None, errors.New(\"need either path or capi_provider\")\n\t}\n\n\tif len(path) == 0 {\n\t\tval := provider.Constructor()\n\t\tif constructor, ok := val.(starlark.String); ok {\n\t\t\tconstStr := constructor.GoString()\n\t\t\tif constStr != identifiers.capvProvider && constStr != identifiers.capaProvider {\n\t\t\t\treturn starlark.None, errors.New(\"unknown capi provider\")\n\t\t\t}\n\t\t}\n\n\t\tpathVal, err := provider.Attr(\"kube_config\")\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"could not find the kubeconfig attribute\")\n\t\t}\n\t\tpathStr, ok := pathVal.(starlark.String)\n\t\tif !ok {\n\t\t\treturn starlark.None, errors.New(\"could not fetch kubeconfig\")\n\t\t}\n\t\tpath = pathStr.GoString()\n\t}\n\n\tpath, err := util.ExpandPath(path)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tstructVal := starlarkstruct.FromStringDict(starlark.String(identifiers.kubeCfg), starlark.StringDict{\n\t\t\"cluster_context\": starlark.String(clusterCtxName),\n\t\t\"path\": starlark.String(path),\n\t})\n\n\treturn structVal, nil\n}", "func genConfig() ([]byte, error) {\n\t// Using genflags.getConfig() instead of config.New() because\n\t// it will include any defaults we have on the command line such\n\t// as default plugin selection. We didn't want to wire this into\n\t// the `config` package, but it will be a default value the CLI\n\t// users expect.\n\tc := genflags.resolveConfig()\n\tb, err := json.Marshal(c)\n\treturn b, errors.Wrap(err, \"unable to marshal configuration\")\n}", "func initKubeConfig(kcLocation string) *rest.Config {\n\n\tif kcLocation != \"\" {\n\t\tkubeConfig, err := clientcmd.BuildConfigFromFlags(\"\", kcLocation)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"unable to build rest config based on provided path to kubeconfig file %s\", err.Error())\n\t\t}\n\t\treturn kubeConfig\n\t}\n\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tglog.Fatal(\"cannot find Service Account in pod to build in-cluster rest config\")\n\t}\n\n\treturn kubeConfig\n}", "func (k *K8sutil) generateConfig(configDir, certsDir, namespace, clusterName string) error {\n\tcaConfig := caconfig{\n\t\tSigning: configSigning{\n\t\t\tDefault: configDefault{\n\t\t\t\tUsages: []string{\n\t\t\t\t\t\"signing\",\n\t\t\t\t\t\"key encipherment\",\n\t\t\t\t\t\"server auth\",\n\t\t\t\t\t\"client auth\",\n\t\t\t\t},\n\t\t\t\tExpiry: \"8760h\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcaCSR := csr{\n\t\tHosts: []string{\n\t\t\t\"localhost\",\n\t\t\tfmt.Sprintf(\"elasticsearch-%s\", clusterName),\n\t\t\tfmt.Sprintf(\"%s.%s\", fmt.Sprintf(\"elasticsearch-%s\", clusterName), namespace),\n\t\t\tfmt.Sprintf(\"%s.%s.svc.cluster.local\", fmt.Sprintf(\"elasticsearch-%s\", clusterName), namespace),\n\t\t},\n\t\tKey: key{\n\t\t\tAlgo: \"rsa\",\n\t\t\tSize: 2048,\n\t\t},\n\t\tNames: []names{\n\t\t\tnames{\n\t\t\t\tC: \"US\",\n\t\t\t\tL: \"Pittsburgh\",\n\t\t\t\tO: \"elasticsearch-operator\",\n\t\t\t\tOU: \"k8s\",\n\t\t\t\tST: \"Pennsylvania\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcaConfigJSON, err := json.Marshal(caConfig)\n\tif err != nil {\n\t\tlogrus.Error(\"json Marshal error : \", err)\n\t\treturn err\n\t}\n\tf, err := os.Create(fmt.Sprintf(\"%s/ca-config.json\", configDir))\n\t_, err = f.Write(caConfigJSON)\n\tif err != nil {\n\t\tlogrus.Error(\"Error creating ca-config.json: \", err)\n\t\treturn err\n\t}\n\n\treqCACSRJSON, _ := json.Marshal(caCSR)\n\tf, err = os.Create(fmt.Sprintf(\"%s/ca-csr.json\", configDir))\n\t_, err = f.Write(reqCACSRJSON)\n\tif err != nil {\n\t\tlogrus.Error(\"Error creating ca-csr.json: \", err)\n\t\treturn err\n\t}\n\n\tfor k, v := range map[string]string{\n\t\t\"node\": \"req-node-csr.json\",\n\t\t\"sgadmin\": \"req-sgadmin-csr.json\",\n\t\t\"kibana\": \"req-kibana-csr.json\",\n\t\t\"cerebro\": \"req-cerebro-csr.json\",\n\t} {\n\n\t\treq := csr{\n\t\t\tCN: k,\n\t\t\tHosts: []string{\n\t\t\t\t\"localhost\",\n\t\t\t\tfmt.Sprintf(\"%s-%s\", k, clusterName),\n\t\t\t\tfmt.Sprintf(\"%s.%s\", fmt.Sprintf(\"%s-%s\", k, clusterName), namespace),\n\t\t\t\tfmt.Sprintf(\"%s.%s.svc.cluster.local\", fmt.Sprintf(\"%s-%s\", k, clusterName), namespace),\n\t\t\t\tfmt.Sprintf(\"elasticsearch-%s\", clusterName),\n\t\t\t},\n\t\t\tKey: key{\n\t\t\t\tAlgo: \"rsa\",\n\t\t\t\tSize: 2048,\n\t\t\t},\n\t\t\tNames: []names{\n\t\t\t\tnames{\n\t\t\t\t\tO: \"autogenerated\",\n\t\t\t\t\tOU: \"elasticsearch cluster\",\n\t\t\t\t\tL: \"operator\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tconfigJSON, _ := json.Marshal(req)\n\t\tf, err := os.Create(fmt.Sprintf(\"%s/%s\", configDir, v))\n\t\t_, err = f.Write(configJSON)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *Botanist) GenerateKubeLegoConfig() (map[string]interface{}, error) {\n\tvar (\n\t\tenabled = b.Shoot.KubeLegoEnabled()\n\t\tvalues map[string]interface{}\n\t)\n\n\tif enabled {\n\t\tvalues = map[string]interface{}{\n\t\t\t\"config\": map[string]interface{}{\n\t\t\t\t\"LEGO_EMAIL\": b.Shoot.Info.Spec.Addons.KubeLego.Mail,\n\t\t\t},\n\t\t}\n\t}\n\n\treturn common.GenerateAddonConfig(values, enabled), nil\n}", "func Main() {\n\n\tif KubeServer == \"\" {\n\t\tlogger.Error(\"param server is null\")\n\t\treturn\n\t}\n\tif KubeToken == \"\" {\n\t\tlogger.Error(\"param token is null\")\n\t\treturn\n\t}\n\tif KubeUser == \"\" {\n\t\tlogger.Error(\"param user is null\")\n\t\treturn\n\t}\n\tvar kubeconfig = tools.KubeConfigExists()\n\tvar envMap = make(map[string]string, 4)\n\tenvMap[\"KubeServer\"] = KubeServer\n\tenvMap[\"KubeUser\"] = KubeUser\n\tenvMap[\"KubeToken\"] = KubeToken\n\ttmpl, err := template.New(\"configToken\").Parse(templateText)\n\tif err != nil {\n\t\tlogger.Error(\"template parse failed:\", err)\n\t\treturn\n\t}\n\tvar buffer bytes.Buffer\n\t_ = tmpl.Execute(&buffer, envMap)\n\tlogger.Debug(&buffer)\n\t//write file\n\t_ = ioutil.WriteFile(kubeconfig, buffer.Bytes(), 0755)\n}", "func GenerateKubeconfigBytes(restConfig *rest.Config) ([]byte, error) {\n\tclientConfig, err := GenerateKubeconfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientcmd.Write(clientConfig)\n}", "func writeConfig(o options, clientset kubernetes.Interface) error {\n\t// kubeconfig is a kubernetes config.\n\tvar kubeconfig []byte\n\n\tdir, file := filepath.Split(o.output)\n\n\terr := os.MkdirAll(dir, os.ModePerm)\n\tif err != nil {\n\t\treturn &util.ExitError{Message: fmt.Sprintf(\"unable to create output directory %v: %v.\", dir, err), Code: 1}\n\t}\n\n\tif o.certificate {\n\t\tif kubeconfig, err = certificate.CreateKubeConfigWithCertificateCredentials(clientset, o.name); err != nil {\n\t\t\treturn &util.ExitError{Message: fmt.Sprintf(\"unable to create kubeconfig file with cert and key for %v: %v.\", o.name, err), Code: 1}\n\t\t}\n\t} else {\n\t\t// Service account credentials are the default if unspecified.\n\t\tif kubeconfig, err = serviceaccount.CreateKubeConfigWithServiceAccountCredentials(clientset, o.name); err != nil {\n\t\t\treturn &util.ExitError{Message: fmt.Sprintf(\"unable to create kubeconfig file with service account for %v: %v.\", o.name, err), Code: 1}\n\t\t}\n\t}\n\n\tif !o.overwrite && util.FileExists(o.output) {\n\t\tif kubeconfig, err = mergeConfigs(o, kubeconfig); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err = ioutil.WriteFile(o.output, kubeconfig, 0644); err != nil {\n\t\treturn &util.ExitError{Message: fmt.Sprintf(\"unable to write to file %v: %v.\", file, err), Code: 1}\n\t}\n\n\treturn nil\n}", "func Kubeconfig() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"kubeconfig\",\n\t\tShort: \"Download credentials for the Kubernetes cluster selected via 'okteto context'\",\n\t\tArgs: utils.NoArgsAccepted(\"https://okteto.com/docs/reference/cli/#kubeconfig\"),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\terr := contextCMD.UpdateKubeconfigCMD().RunE(cmd, args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n\treturn cmd\n}", "func (edge EdgeClusterServiceDetail) GetKubeConfig() *rest.Config {\n\tvar kubeconfig string\n\n\t//get hoem directory path\n\thomeDir := microbusiness.GetHomeDirectoryPath()\n\tlog.Print(homeDir)\n\n\tif homeDir != \"\" {\n\t\tflag.StringVar(&kubeconfig, \"kubeconfig\", filepath.Join(homeDir, \".kube\", edge.ConfigName), \"(optional) path to config file\")\n\t} else {\n\t\tflag.StringVar(&kubeconfig, \"kubeconfig\", \"\", \"path to kube config file\")\n\t}\n\n\tlog.Println(\"building config ...\")\n\n\tconfigContext, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\n\tmicrobusiness.HandleError(err)\n\n\treturn configContext\n}", "func getK8sConfig(context string) clientcmd.ClientConfig {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif context != \"\" {\n\t\toverrides.CurrentContext = context\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n}", "func buildKubeConfigUpdate(cf *CLIConf, kubeStatus *kubernetesStatus) (*kubeconfig.Values, error) {\n\tv := &kubeconfig.Values{\n\t\tClusterAddr: kubeStatus.clusterAddr,\n\t\tTeleportClusterName: kubeStatus.teleportClusterName,\n\t\tCredentials: kubeStatus.credentials,\n\t\tProxyAddr: cf.Proxy,\n\t\tTLSServerName: kubeStatus.tlsServerName,\n\t}\n\n\tif cf.executablePath == \"\" {\n\t\t// Don't know tsh path.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\treturn v, nil\n\t}\n\n\tif len(kubeStatus.kubeClusters) == 0 {\n\t\t// If there are no registered k8s clusters, we may have an older teleport cluster.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\tlog.Debug(\"Disabling exec plugin mode for kubeconfig because this Teleport cluster has no Kubernetes clusters.\")\n\t\treturn v, nil\n\t}\n\n\tclusterNames := kubeClustersToStrings(kubeStatus.kubeClusters)\n\tv.Exec = &kubeconfig.ExecValues{\n\t\tTshBinaryPath: cf.executablePath,\n\t\tTshBinaryInsecure: cf.InsecureSkipVerify,\n\t\tKubeClusters: clusterNames,\n\t\tEnv: make(map[string]string),\n\t}\n\n\tif cf.HomePath != \"\" {\n\t\tv.Exec.Env[types.HomeEnvVar] = cf.HomePath\n\t}\n\n\t// Only switch the current context if kube-cluster is explicitly set on the command line.\n\tif cf.KubernetesCluster != \"\" {\n\t\tif !apiutils.SliceContainsStr(clusterNames, cf.KubernetesCluster) {\n\t\t\treturn nil, trace.BadParameter(\"Kubernetes cluster %q is not registered in this Teleport cluster; you can list registered Kubernetes clusters using 'tsh kube ls'.\", cf.KubernetesCluster)\n\t\t}\n\t\tv.Exec.SelectCluster = cf.KubernetesCluster\n\t}\n\treturn v, nil\n}", "func (h *handler) clientConfig(kubeconfig []byte, contextName string) (*rest.Config, error) {\n\tif len(kubeconfig) > 0 {\n\t\tccfg, err := clientcmd.Load(kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif contextName != \"\" {\n\t\t\tccfg.CurrentContext = contextName\n\t\t}\n\t\terr = writeKubeconfig(kubeconfig, contextName, h.kubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn clientcmd.NewDefaultClientConfig(*ccfg, &clientcmd.ConfigOverrides{}).ClientConfig()\n\t}\n\treturn rest.InClusterConfig()\n}", "func generateConfigFile(context *clusterd.Context, clusterInfo *ClusterInfo, pathRoot, keyringPath string, globalConfig *CephConfig, clientSettings map[string]string) (string, error) {\n\n\t// create the config directory\n\tif err := os.MkdirAll(pathRoot, 0744); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create config directory at %q\", pathRoot)\n\t}\n\n\tconfigFile, err := createGlobalConfigFileSection(context, clusterInfo, globalConfig)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to create global config section\")\n\t}\n\n\tif err := mergeDefaultConfigWithRookConfigOverride(context, clusterInfo, configFile); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to merge global config with %q\", k8sutil.ConfigOverrideName)\n\t}\n\n\tqualifiedUser := getQualifiedUser(clusterInfo.CephCred.Username)\n\tif err := addClientConfigFileSection(configFile, qualifiedUser, keyringPath, clientSettings); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to add admin client config section\")\n\t}\n\n\t// write the entire config to disk\n\tfilePath := getConfFilePath(pathRoot, clusterInfo.Namespace)\n\tlogger.Infof(\"writing config file %s\", filePath)\n\tif err := configFile.SaveTo(filePath); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to save config file %s\", filePath)\n\t}\n\n\treturn filePath, nil\n}", "func initKubeConfig(t *testing.T) {\n\tdirectoryKubeConfig := \"/tmp/.kube\"\n\tdefaultKubeConfigPath = directoryKubeConfig + \"/config\"\n\n\terr := os.MkdirAll(directoryKubeConfig, os.ModePerm)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfile, err := os.Create(defaultKubeConfigPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tdir, _ := os.Getwd()\n\tconfigFile := dir + \"/../../../internal/test/forwarder/kubernetes/config\"\n\n\tfrom, err := os.OpenFile(configFile, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer from.Close()\n\n\t_, err = io.Copy(file, from)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func WriteKubeConfig(configRaw *clientcmdapi.Config) (string, error) {\n\tdata, err := clientcmd.Write(*configRaw)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Create temp file\n\ttempFile, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create temp file\")\n\t}\n\n\t// Write to temp file\n\t_, err = tempFile.Write(data)\n\tif err != nil {\n\t\tos.Remove(tempFile.Name())\n\t\treturn \"\", errors.Wrap(err, \"write temp file\")\n\t}\n\n\t// Close temp file\n\ttempFile.Close()\n\n\t// Okay sometimes the file is written so quickly that helm somehow\n\t// cannot read it immediately which causes errors\n\t// so we wait here till the file is ready\n\tnow := time.Now()\n\tfor time.Since(now) < time.Minute {\n\t\t_, err = os.Stat(tempFile.Name())\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tos.Remove(tempFile.Name())\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tbreak\n\t}\n\n\treturn tempFile.Name(), nil\n}", "func updateKubeConfig(cf *CLIConf, tc *client.TeleportClient, path string) error {\n\t// Fetch proxy's advertised ports to check for k8s support.\n\tif _, err := tc.Ping(cf.Context); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif tc.KubeProxyAddr == \"\" {\n\t\t// Kubernetes support disabled, don't touch kubeconfig.\n\t\treturn nil\n\t}\n\n\tkubeStatus, err := fetchKubeStatus(cf.Context, tc)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tvalues, err := buildKubeConfigUpdate(cf, kubeStatus)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif path == \"\" {\n\t\tpath = kubeconfig.PathFromEnv()\n\t}\n\n\t// If this is a profile specific kubeconfig, we only need\n\t// to put the selected kube cluster into the kubeconfig.\n\tisKubeConfig, err := keypaths.IsProfileKubeConfigPath(path)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif isKubeConfig {\n\t\tif !strings.Contains(path, cf.KubernetesCluster) {\n\t\t\treturn trace.BadParameter(\"profile specific kubeconfig is in use, run 'eval $(tsh env --unset)' to switch contexts to another kube cluster\")\n\t\t}\n\t\tvalues.Exec.KubeClusters = []string{cf.KubernetesCluster}\n\t}\n\n\treturn trace.Wrap(kubeconfig.Update(path, *values))\n}", "func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\n\tvar cc config.ClusterConfig\n\n\t// networkPlugin cni deprecation warning\n\tchosenNetworkPlugin := viper.GetString(networkPlugin)\n\tif chosenNetworkPlugin == \"cni\" {\n\t\tout.WarningT(\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\")\n\t}\n\n\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \"\" {\n\t\tout.WarningT(\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\")\n\t}\n\n\tcheckNumaCount(k8sVersion)\n\n\tcheckExtraDiskOptions(cmd, drvName)\n\n\tcc = config.ClusterConfig{\n\t\tName: ClusterFlagValue(),\n\t\tKeepContext: viper.GetBool(keepContext),\n\t\tEmbedCerts: viper.GetBool(embedCerts),\n\t\tMinikubeISO: viper.GetString(isoURL),\n\t\tKicBaseImage: viper.GetString(kicBaseImage),\n\t\tNetwork: getNetwork(drvName),\n\t\tSubnet: viper.GetString(subnet),\n\t\tMemory: getMemorySize(cmd, drvName),\n\t\tCPUs: getCPUCount(drvName),\n\t\tDiskSize: getDiskSize(),\n\t\tDriver: drvName,\n\t\tListenAddress: viper.GetString(listenAddress),\n\t\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\n\t\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\n\t\tNFSShare: viper.GetStringSlice(nfsShare),\n\t\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\n\t\tDockerEnv: config.DockerEnv,\n\t\tDockerOpt: config.DockerOpt,\n\t\tInsecureRegistry: insecureRegistry,\n\t\tRegistryMirror: registryMirror,\n\t\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\n\t\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\n\t\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\n\t\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\n\t\tKVMNetwork: viper.GetString(kvmNetwork),\n\t\tKVMQemuURI: viper.GetString(kvmQemuURI),\n\t\tKVMGPU: viper.GetBool(kvmGPU),\n\t\tKVMHidden: viper.GetBool(kvmHidden),\n\t\tKVMNUMACount: viper.GetInt(kvmNUMACount),\n\t\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\n\t\tUUID: viper.GetString(uuid),\n\t\tNoVTXCheck: viper.GetBool(noVTXCheck),\n\t\tDNSProxy: viper.GetBool(dnsProxy),\n\t\tHostDNSResolver: viper.GetBool(hostDNSResolver),\n\t\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\n\t\tNatNicType: viper.GetString(natNicType),\n\t\tStartHostTimeout: viper.GetDuration(waitTimeout),\n\t\tExposedPorts: viper.GetStringSlice(ports),\n\t\tSSHIPAddress: viper.GetString(sshIPAddress),\n\t\tSSHUser: viper.GetString(sshSSHUser),\n\t\tSSHKey: viper.GetString(sshSSHKey),\n\t\tSSHPort: viper.GetInt(sshSSHPort),\n\t\tExtraDisks: viper.GetInt(extraDisks),\n\t\tCertExpiration: viper.GetDuration(certExpiration),\n\t\tMount: viper.GetBool(createMount),\n\t\tMountString: viper.GetString(mountString),\n\t\tMount9PVersion: viper.GetString(mount9PVersion),\n\t\tMountGID: viper.GetString(mountGID),\n\t\tMountIP: viper.GetString(mountIPFlag),\n\t\tMountMSize: viper.GetInt(mountMSize),\n\t\tMountOptions: viper.GetStringSlice(mountOptions),\n\t\tMountPort: uint16(viper.GetUint(mountPortFlag)),\n\t\tMountType: viper.GetString(mountTypeFlag),\n\t\tMountUID: viper.GetString(mountUID),\n\t\tBinaryMirror: viper.GetString(binaryMirror),\n\t\tDisableOptimizations: viper.GetBool(disableOptimizations),\n\t\tDisableMetrics: viper.GetBool(disableMetrics),\n\t\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\n\t\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\n\t\tSocketVMnetPath: detect.SocketVMNetPath(),\n\t\tStaticIP: viper.GetString(staticIP),\n\t\tKubernetesConfig: config.KubernetesConfig{\n\t\t\tKubernetesVersion: k8sVersion,\n\t\t\tClusterName: ClusterFlagValue(),\n\t\t\tNamespace: viper.GetString(startNamespace),\n\t\t\tAPIServerName: viper.GetString(apiServerName),\n\t\t\tAPIServerNames: apiServerNames,\n\t\t\tAPIServerIPs: apiServerIPs,\n\t\t\tDNSDomain: viper.GetString(dnsDomain),\n\t\t\tFeatureGates: viper.GetString(featureGates),\n\t\t\tContainerRuntime: rtime,\n\t\t\tCRISocket: viper.GetString(criSocket),\n\t\t\tNetworkPlugin: chosenNetworkPlugin,\n\t\t\tServiceCIDR: viper.GetString(serviceCIDR),\n\t\t\tImageRepository: getRepository(cmd, k8sVersion),\n\t\t\tExtraOptions: getExtraOptions(),\n\t\t\tShouldLoadCachedImages: viper.GetBool(cacheImages),\n\t\t\tCNI: getCNIConfig(cmd),\n\t\t\tNodePort: viper.GetInt(apiServerPort),\n\t\t},\n\t\tMultiNodeRequested: viper.GetInt(nodes) > 1,\n\t}\n\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\n\t\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\n\t}\n\n\tif driver.IsKIC(drvName) {\n\t\tsi, err := oci.CachedDaemonInfo(drvName)\n\t\tif err != nil {\n\t\t\texit.Message(reason.Usage, \"Ensure your {{.driver_name}} is running and is healthy.\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\tif si.Rootless {\n\t\t\tout.Styled(style.Notice, \"Using rootless {{.driver_name}} driver\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\n\t\t\t\texit.Message(reason.Usage, \"--container-runtime must be set to \\\"containerd\\\" or \\\"cri-o\\\" for rootless\")\n\t\t\t}\n\t\t\t// KubeletInUserNamespace feature gate is essential for rootless driver.\n\t\t\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\n\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"KubeletInUserNamespace=true\")\n\t\t} else {\n\t\t\tif oci.IsRootlessForced() {\n\t\t\t\tif driver.IsDocker(drvName) {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\")\n\t\t\t\t} else {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless driver was required, but the current driver does not seem rootless\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Styled(style.Notice, \"Using {{.driver_name}} driver with root privileges\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\n\t\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\n\t\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\n\t\tif si.StorageDriver == \"btrfs\" {\n\t\t\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\"1.25.0-beta.0\")) {\n\t\t\t\tklog.Info(\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\")\n\t\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"LocalStorageCapacityIsolation=false\")\n\t\t\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\"kubelet.localStorageCapacityIsolation=false\") {\n\t\t\t\tif err := cc.KubernetesConfig.ExtraOptions.Set(\"kubelet.localStorageCapacityIsolation=false\"); err != nil {\n\t\t\t\t\texit.Error(reason.InternalConfigSet, \"failed to set extra option\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif runtime.GOOS == \"linux\" && si.DockerOS == \"Docker Desktop\" {\n\t\t\tout.WarningT(\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\")\n\t\t}\n\t}\n\n\treturn cc\n}", "func restclientConfig(kubeContext string) (*clientcmdapi.Config, error) {\n\tLogf(\">>> kubeConfig: %s\", TestContext.KubeConfig)\n\tif TestContext.KubeConfig == \"\" {\n\t\treturn nil, fmt.Errorf(\"KubeConfig must be specified to load client config\")\n\t}\n\tc, err := clientcmd.LoadFromFile(TestContext.KubeConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading KubeConfig: %v\", err.Error())\n\t}\n\tif kubeContext != \"\" {\n\t\tLogf(\">>> kubeContext: %s\", kubeContext)\n\t\tc.CurrentContext = kubeContext\n\t}\n\treturn c, nil\n}", "func genConfigCobra(cmd *cobra.Command, args []string) {\n\ts, err := genConfig()\n\tif err != nil {\n\t\terrlog.LogError(err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(string(s))\n}", "func registerCertGen(app *kingpin.Application) (*kingpin.CmdClause, *certgenConfig) {\n\tvar certgenConfig certgenConfig\n\tcertgenApp := app.Command(\"certgen\", \"Generate new TLS certs for bootstrapping gRPC over TLS.\")\n\tcertgenApp.Arg(\"outputdir\", \"Directory to write output files into (default \\\"certs\\\").\").Default(\"certs\").StringVar(&certgenConfig.OutputDir)\n\n\t// NOTE: --certificate-lifetime can be used to accept Duration string once certificate rotation is supported.\n\tcertgenApp.Flag(\"certificate-lifetime\", \"Generated certificate lifetime (in days).\").Default(strconv.Itoa(certs.DefaultCertificateLifetime)).UintVar(&certgenConfig.Lifetime)\n\tcertgenApp.Flag(\"incluster\", \"Use in cluster configuration.\").BoolVar(&certgenConfig.InCluster)\n\tcertgenApp.Flag(\"kube\", \"Apply the generated certs directly to the current Kubernetes cluster.\").BoolVar(&certgenConfig.OutputKube)\n\tcertgenApp.Flag(\"kubeconfig\", \"Path to kubeconfig (if not in running inside a cluster).\").Default(filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")).StringVar(&certgenConfig.KubeConfig)\n\tcertgenApp.Flag(\"namespace\", \"Kubernetes namespace, used for Kube objects.\").Default(certs.DefaultNamespace).Envar(\"CONTOUR_NAMESPACE\").StringVar(&certgenConfig.Namespace)\n\tcertgenApp.Flag(\"overwrite\", \"Overwrite existing files or Secrets.\").BoolVar(&certgenConfig.Overwrite)\n\tcertgenApp.Flag(\"pem\", \"Render the generated certs as individual PEM files to the current directory.\").BoolVar(&certgenConfig.OutputPEM)\n\tcertgenApp.Flag(\"secrets-format\", \"Specify how to format the generated Kubernetes Secrets.\").Default(\"legacy\").StringVar(&certgenConfig.Format)\n\tcertgenApp.Flag(\"secrets-name-suffix\", \"Specify a suffix to be appended to the generated Kubernetes secrets' names.\").StringVar(&certgenConfig.NameSuffix)\n\tcertgenApp.Flag(\"yaml\", \"Render the generated certs as Kubernetes Secrets in YAML form to the current directory.\").BoolVar(&certgenConfig.OutputYAML)\n\n\treturn certgenApp, &certgenConfig\n}", "func buildConfig(log logrus.FieldLogger, masterURL, kubeConfig string) (*rest.Config, error) {\n\tif os.Getenv(\"KUBERNETES_SERVICE_HOST\") != \"\" && os.Getenv(\"KUBERNETES_SERVICE_PORT\") != \"\" {\n\t\t// If these env vars are set, we can build an in-cluster config.\n\t\tlog.Debug(\"Creating in-cluster client\")\n\t\treturn rest.InClusterConfig()\n\t}\n\n\tif masterURL != \"\" || kubeConfig != \"\" {\n\t\tlog.Debug(\"Creating cluster-external client from provided masterURL or kubeconfig\")\n\t\treturn clientcmd.BuildConfigFromFlags(masterURL, kubeConfig)\n\t}\n\n\treturn nil, fmt.Errorf(\"could not create client: missing masterURL or kubeConfig\")\n}", "func BuildConfig(kubecfgPath string, ctx string) (*rest.Config, error) {\n\tif kubecfgPath != \"\" {\n\t\tinfo, err := os.Stat(kubecfgPath)\n\t\tif err != nil || info.Size() == 0 {\n\t\t\t// If the specified kube config file doesn't exist / empty file / any other error\n\t\t\t// from file stat, fall back to default\n\t\t\tkubecfgPath = \"\"\n\t\t}\n\t}\n\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig\n\tloadingRules.ExplicitPath = kubecfgPath\n\tconfigOverrides := &clientcmd.ConfigOverrides{\n\t\tClusterDefaults: clientcmd.ClusterDefaults,\n\t\tCurrentContext: ctx,\n\t}\n\tcfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides).ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsetDefaults(cfg)\n\treturn cfg, nil\n}", "func CreateConfig(serviceAccount *corev1.ServiceAccount) string {\n\tclientset, err := authorization.CreateClientSet()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tpanic(err.Error())\n\t}\n\t// To find out the secret name to use\n\taccountSecretName := \"\"\n\tfor _, accountSecret := range serviceAccount.Secrets {\n\t\tmatch, _ := regexp.MatchString(\"([a-z0-9]+)-token-([a-z0-9]+)\", accountSecret.Name)\n\t\tif match {\n\t\t\taccountSecretName = accountSecret.Name\n\t\t\tbreak\n\t\t}\n\t}\n\t// If there is no matching secret terminate this function as generating kubeconfig file is not possible\n\tif accountSecretName == \"\" {\n\t\tlog.Printf(\"Serviceaccount %s in %s doesn't have a serviceaccount token\", serviceAccount.GetName(), serviceAccount.GetNamespace())\n\t\treturn fmt.Sprintf(\"Serviceaccount %s doesn't have a serviceaccount token\\n\", serviceAccount.GetName())\n\t}\n\tsecret, err := clientset.CoreV1().Secrets(serviceAccount.GetNamespace()).Get(accountSecretName, metav1.GetOptions{})\n\tif errors.IsNotFound(err) {\n\t\tlog.Printf(\"Secret for %s in %s not found\", serviceAccount.GetName(), serviceAccount.GetNamespace())\n\t\treturn fmt.Sprintf(\"Secret %s not found\\n\", serviceAccount.GetName())\n\t} else if statusError, isStatus := err.(*errors.StatusError); isStatus {\n\t\tlog.Printf(\"Error getting secret %s in %s: %v\", serviceAccount.GetName(), serviceAccount.GetNamespace(), statusError.ErrStatus)\n\t\treturn fmt.Sprintf(\"Error getting secret %s: %v\\n\", serviceAccount.GetName(), statusError.ErrStatus)\n\t} else if err != nil {\n\t\tlog.Println(err.Error())\n\t\tpanic(err.Error())\n\t}\n\t// Define the cluster and server by taking advantage of the current config file\n\tcluster, server, err := custconfig.GetClusterServerOfCurrentContext()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn fmt.Sprintf(\"Err: %s\", err)\n\t}\n\t// Put the collected data into new kubeconfig file\n\tnewKubeConfig := kubeconfigutil.CreateWithToken(server, cluster, serviceAccount.GetName(), secret.Data[\"ca.crt\"], string(secret.Data[\"token\"]))\n\tnewKubeConfig.Contexts[newKubeConfig.CurrentContext].Namespace = serviceAccount.GetNamespace()\n\tkubeconfigutil.WriteToDisk(fmt.Sprintf(\"../../assets/kubeconfigs/edgenet-%s-%s.cfg\", serviceAccount.GetNamespace(), serviceAccount.GetName()), newKubeConfig)\n\t// Check whether the creation process is completed\n\tdat, err := ioutil.ReadFile(fmt.Sprintf(\"../../assets/kubeconfigs/edgenet-%s-%s.cfg\", serviceAccount.GetNamespace(), serviceAccount.GetName()))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn fmt.Sprintf(\"Err: %s\", err)\n\t}\n\treturn string(dat)\n}", "func FactoryFromKubeConfig(path, context string, opts ...ClientOption) cmdutil.Factory {\n\tkf := genericclioptions.NewConfigFlags(false)\n\tkf.KubeConfig = &path\n\tkf.Context = &context\n\tfor _, o := range opts {\n\t\to(kf)\n\t}\n\n\treturn cmdutil.NewFactory(cmdutil.NewMatchVersionFlags(&factory.CachingRESTClientGetter{\n\t\tDelegate: kf,\n\t}))\n}", "func (k *kubelet) configFile() (string, error) {\n\tconfig := &kubeletconfig.KubeletConfiguration{\n\t\tTypeMeta: v1.TypeMeta{\n\t\t\tKind: \"KubeletConfiguration\",\n\t\t\tAPIVersion: kubeletconfig.SchemeGroupVersion.String(),\n\t\t},\n\t\t// Enables TLS certificate rotation, which is good from security point of view.\n\t\tRotateCertificates: true,\n\t\t// Request HTTPS server certs from API as well, so kubelet does not generate self-signed certificates.\n\t\tServerTLSBootstrap: true,\n\t\t// If Docker is configured to use systemd as a cgroup driver and Docker is used as container\n\t\t// runtime, this needs to be set to match Docker.\n\t\t// TODO pull that information dynamically based on what container runtime is configured.\n\t\tCgroupDriver: k.config.CgroupDriver,\n\t\t// Address where kubelet should listen on.\n\t\tAddress: k.config.Address,\n\t\t// Disable healht port for now, since we don't use it.\n\t\t// TODO check how to use it and re-enable it.\n\t\tHealthzPort: &[]int32{0}[0],\n\t\t// Set up cluster domain. Without this, there is no 'search' field in /etc/resolv.conf in containers, so\n\t\t// short-names resolution like mysvc.myns.svc does not work.\n\t\tClusterDomain: \"cluster.local\",\n\t\t// Authenticate clients using CA file.\n\t\tAuthentication: kubeletconfig.KubeletAuthentication{\n\t\t\tX509: kubeletconfig.KubeletX509Authentication{\n\t\t\t\tClientCAFile: \"/etc/kubernetes/pki/ca.crt\",\n\t\t\t},\n\t\t},\n\n\t\t// This defines where should pods cgroups be created, like /kubepods and /kubepods/burstable.\n\t\t// Also when specified, it suppresses a lot message about it.\n\t\tCgroupRoot: \"/\",\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'system-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with SystemReservedCgroup.\n\t\tSystemReserved: k.config.SystemReserved,\n\n\t\t// Used for calculating node allocatable resources.\n\t\t// If EnforceNodeAllocatable has 'kube-reserved' set, those limits will be enforced on cgroup specified\n\t\t// with KubeReservedCgroup.\n\t\tKubeReserved: k.config.KubeReserved,\n\n\t\tClusterDNS: k.config.ClusterDNSIPs,\n\n\t\tHairpinMode: k.config.HairpinMode,\n\t}\n\n\tkubelet, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"serializing to YAML: %w\", err)\n\t}\n\n\treturn string(kubelet), nil\n}", "func GetKubeConfig(clusterName string, region string) (*rest.Config, error) {\n\tif clusterName == \"\" {\n\t\terr := errors.New(\"Cluster name is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\tif region == \"\" {\n\t\terr := errors.New(\"Region is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\ts, err := session.NewSession(&aws.Config{Region: aws.String(region)})\n\tsvc := eks.New(s)\n\tinput := &eks.DescribeClusterInput{\n\t\tName: aws.String(clusterName),\n\t}\n\n\tclusterInfo, err := svc.DescribeCluster(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tlog.Error().Err(aerr).Str(\"code\", aerr.Code()).Msg(\"Failed to describe cluster\")\n\t\t} else {\n\t\t\tlog.Error().Err(err).Msg(\"Failed to describe cluster\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tca, err := base64.StdEncoding.DecodeString(*clusterInfo.Cluster.CertificateAuthority.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgen, err := token.NewGenerator(false, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttkn, err := gen.Get(*clusterInfo.Cluster.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rest.Config{\n\t\tHost: *clusterInfo.Cluster.Endpoint,\n\t\tBearerToken: tkn.Token,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tCAData: ca,\n\t\t},\n\t}, nil\n}", "func BuildKubeConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\tglog.V(2).Infof(\"kubeconfig file: %s\", kubeconfig)\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\tglog.V(2).Info(\"kubeconfig file: using InClusterConfig.\")\n\treturn rest.InClusterConfig()\n}", "func makeRESTConfig(fileName, contextName string) (*rest.Config, error) {\n\tif fileName == \"\" {\n\t\treturn nil, fmt.Errorf(\"kubeconfig file path required\")\n\t}\n\n\tif contextName != \"\" {\n\t\t// create the config object from k8s config path and context\n\t\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: fileName},\n\t\t\t&clientcmd.ConfigOverrides{\n\t\t\t\tCurrentContext: contextName,\n\t\t\t}).ClientConfig()\n\t}\n\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: fileName},\n\t\t&clientcmd.ConfigOverrides{},\n\t).ClientConfig()\n}", "func (d *dexterOIDChttp) showK8sConfig(w http.ResponseWriter, token *oauth2.Token) error {\n\tidToken := token.Extra(\"id_token\").(string)\n\n\tparsed, err := jwt.ParseSigned(idToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse token: %s\", err)\n\t}\n\n\tcustomClaim := &customClaim{}\n\tclaims := &jwt.Claims{}\n\n\terr = parsed.UnsafeClaimsWithoutVerification(claims, customClaim)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get user details from token: %s\", err)\n\t}\n\n\t// Use e-mail claim if configuration wasn't discovered in kubeconfig\n\tauthName := customClaim.Email\n\tif d.authName != \"\" {\n\t\tauthName = d.authName\n\t}\n\n\t// construct the authinfo struct\n\tauthInfo := &clientCmdApi.AuthInfo{\n\t\tAuthProvider: &clientCmdApi.AuthProviderConfig{\n\t\t\tName: \"oidc\",\n\t\t\tConfig: map[string]string{\n\t\t\t\t\"client-id\": d.clientID,\n\t\t\t\t\"client-secret\": d.clientSecret,\n\t\t\t\t\"id-token\": idToken,\n\t\t\t\t\"idp-issuer-url\": claims.Issuer,\n\t\t\t\t\"refresh-token\": token.RefreshToken,\n\t\t\t},\n\t\t},\n\t}\n\n\t// contruct the config snippet\n\tconfig := &clientCmdApi.Config{\n\t\tAuthInfos: map[string]*clientCmdApi.AuthInfo{authName: authInfo},\n\t}\n\n\tif d.kubeConfig != \"\" {\n\t\t// write the config\n\t\ttempKubeConfig, err := ioutil.TempFile(\"\", \"\")\n\t\tdefer os.Remove(tempKubeConfig.Name())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create tempfile: %s\", err)\n\t\t}\n\n\t\t// write snipped to temporary file\n\t\tclientcmd.WriteToFile(*config, tempKubeConfig.Name())\n\n\t\t// setup the order for the file load\n\t\tloadingRules := clientcmd.ClientConfigLoadingRules{\n\t\t\tPrecedence: []string{tempKubeConfig.Name(), d.kubeConfig},\n\t\t}\n\n\t\t// merge the configs\n\t\tconfig, err = loadingRules.Load()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to merge configurations: %s\", err)\n\t\t}\n\t}\n\n\t// create a JSON representation\n\tjson, err := k8sRuntime.Encode(clientCmdLatest.Codec, config)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to runtime encode config: %s\", err)\n\t}\n\n\tdata := strings.Replace(string(json), \"your-email\", authName, -1)\n\n\t// convert JSON to YAML\n\toutput, err := yaml.JSONToYAML([]byte(data))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert JSON to YAML: %s\", err)\n\t}\n\n\t// show the result\n\t//log.Infof(\"Here's the config snippet that would be merged with your config: \\n%v\", string(output))\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(output))\n\n\treturn nil\n}", "func GenerateKubeconfigJSONBytes(restConfig *rest.Config) ([]byte, error) {\n\tclientConfig, err := GenerateKubeconfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, err := clientcmd.Write(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn yaml.YAMLToJSON(data)\n}", "func kubeProxyConfiguration(pluginDefaults map[string]operv1.ProxyArgumentList, conf *operv1.NetworkSpec, pluginOverrides map[string]operv1.ProxyArgumentList) (string, error) {\n\tp := conf.KubeProxyConfig\n\n\targs := map[string]operv1.ProxyArgumentList{}\n\targs[\"bind-address\"] = []string{p.BindAddress}\n\tif len(conf.ClusterNetwork) == 1 {\n\t\targs[\"cluster-cidr\"] = []string{conf.ClusterNetwork[0].CIDR}\n\t}\n\targs[\"iptables-sync-period\"] = []string{p.IptablesSyncPeriod}\n\n\targs = k8sutil.MergeKubeProxyArguments(args, pluginDefaults)\n\targs = k8sutil.MergeKubeProxyArguments(args, p.ProxyArguments)\n\targs = k8sutil.MergeKubeProxyArguments(args, pluginOverrides)\n\n\treturn k8sutil.GenerateKubeProxyConfiguration(args)\n}", "func createKubeConfigFile(content string) (filePath string, err error) {\n\tfilePath = filepath.Join(getKdTempDir(), \"kube-config\")\n\n\t// Write the file to disk\n\tif err := ioutil.WriteFile(filePath, []byte(content), 0444); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filePath, nil\n}", "func (s *VarlinkInterface) GenerateKube(ctx context.Context, c VarlinkCall, name_ string, service_ bool) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.GenerateKube\")\n}", "func NewKubeConfigTmpl(clientID, clientSecret, k8sURL, dexURL string, k8sCA, dexCA []byte) *KubeConfigTmpl {\n\tencode := func(b []byte) string {\n\t\tif b == nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn base64.StdEncoding.EncodeToString(b)\n\t}\n\treturn &KubeConfigTmpl{\n\t\tclientID: clientID,\n\t\tclientSecret: clientSecret,\n\t\tk8sURL: k8sURL,\n\t\tdexURL: dexURL,\n\t\tk8sCAPEMBase64ed: encode(k8sCA),\n\t\tdexCAPEMBase64ed: encode(dexCA),\n\t}\n}", "func setupInClusterKubeconfig() error {\n\tconst certFp = \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\n\tconst tokenFp = \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\tkubeFp := os.ExpandEnv(\"$HOME/.kube\")\n\tkubeconfigFp := fmt.Sprintf(\"%s/config\", kubeFp)\n\n\tcert, err := waitForFile(certFp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open in-cluster ServiceAccount CA certificate\")\n\t}\n\ttoken, err := waitForFile(tokenFp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to open in-cluster ServiceAccount token\")\n\t}\n\n\t// Compute the kubeconfig using the cert and token.\n\ts := fmt.Sprintf(`\napiVersion: v1\nclusters:\n- cluster:\n certificate-authority-data: %s\n server: https://%s\n name: local\ncontexts:\n- context:\n cluster: local\n user: local\n name: local\ncurrent-context: local\nkind: Config\nusers:\n- name: local\n user:\n token: %s\n`, string(base64.StdEncoding.EncodeToString(cert)), os.ExpandEnv(\"$KUBERNETES_PORT_443_TCP_ADDR\"), string(token))\n\n\terr = os.Mkdir(os.ExpandEnv(kubeFp), 0755)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create .kube directory\")\n\t}\n\tfile, err := os.Create(os.ExpandEnv(kubeconfigFp))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create kubeconfig file\")\n\t}\n\treturn ioutil.WriteFile(file.Name(), []byte(s), 0644)\n}", "func getKubeConfig(configPath string, overrides clientcmd.ConfigOverrides) *rest.Config {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.ExplicitPath = configPath\n\tclientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, &overrides, os.Stdin)\n\n\trestConfig, err := clientConfig.ClientConfig()\n\tCheckError(err)\n\treturn restConfig\n}", "func main() {\n\tdir, _ := os.Getwd()\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"generator <bindir>\")\n\t\tlog.Fatal(\"missing bindir path\")\n\t}\n\tbindir = filepath.Join(dir, os.Args[1])\n\tif info, err := os.Stat(bindir); err != nil || !info.IsDir() {\n\t\tlog.Fatalf(\"bindir path %s is not a directory\", bindir)\n\t}\n\tuname, _ := exec.Command(\"uname\", \"-m\").Output()\n\tswitch string(bytes.TrimSuffix(uname, []byte(\"\\n\"))) {\n\tcase \"x86_64\":\n\t\tarch = \"amd64\"\n\tcase \"aarch64\":\n\t\tarch = \"arm64\"\n\tdefault:\n\t\tlog.Fatalf(\"could not resolve arch=%s\", uname)\n\t}\n\n\tfmt.Print(preamble)\n\tvar allKomponents []*komponent\n\tfor _, component := range k8sComponents {\n\t\tvar komponents []*komponent\n\t\tfor _, version := range k8sVersions {\n\t\t\tkomp := downloadKubeComponentAndExtractFlags(component, version)\n\t\t\tkomponents = append(komponents, komp)\n\t\t}\n\t\tmergedKomp := unionKomponents(komponents...)\n\t\tallKomponents = append(allKomponents, mergedKomp)\n\t\tfmt.Println(printKomponentCode(mergedKomp))\n\t}\n\n\t{\n\t\tvar komponents []*komponent\n\t\tfor _, version := range etcdVersions {\n\t\t\tkomp := downloadEtcdAndExtractFlags(version)\n\t\t\tkomponents = append(komponents, komp)\n\t\t}\n\t\tmergedKomp := unionKomponents(komponents...)\n\t\tallKomponents = append(allKomponents, mergedKomp)\n\t\tfmt.Println(printKomponentCode(mergedKomp))\n\t}\n\n\tvar knownFlagsClone []string\n\tknownFlagsClone = append(knownFlagsClone, knownFlags...)\n\tfor _, komponent := range allKomponents {\n\t\tfor _, conf := range komponent.confs {\n\t\t\ti := slices.Index(knownFlagsClone, \"--\"+conf.flagName)\n\t\t\tif i >= 0 {\n\t\t\t\tknownFlagsClone = append(knownFlagsClone[:i], knownFlagsClone[i+1:]...)\n\t\t\t}\n\t\t}\n\t}\n\tif len(knownFlagsClone) > 0 {\n\t\tpanic(fmt.Errorf(\"these flags were not found: %v\", knownFlagsClone))\n\t}\n}", "func extractKubeConfigAndContext(args []string) (string, string) {\n\tif len(args) <= 2 {\n\t\treturn \"\", \"\"\n\t}\n\n\tcommand := makeKubectlCobraCommand()\n\treturn extractKubeConfigAndContextFromCommand(command, args)\n}", "func getKubeConfig() (*rest.Config, error) {\n\t// Try to get in-cluster config first.\n\tconfig, err := rest.InClusterConfig()\n\tif err == nil {\n\t\treturn config, nil\n\t}\n\n\t// Try to get out-of-cluster config then, can be failed.\n\tconfigPath := os.Getenv(\"KUBECONFIG\")\n\tif configPath == \"\" {\n\t\tconfigPath = filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\")\n\t}\n\treturn clientcmd.BuildConfigFromFlags(\"\", configPath)\n}", "func generate(\n\tkustomization *types.Kustomization, overlay string, quayConfigFiles map[string][]byte,\n) ([]client.Object, error) {\n\tfSys := filesys.MakeEmptyDirInMemory()\n\tif err := filepath.Walk(\n\t\tkustomizeDir(),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tf, err := os.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn fSys.WriteFile(path, f)\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Write `kustomization.yaml` to filesystem\n\tkustomizationFile, err := yaml.Marshal(kustomization)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := fSys.WriteFile(\n\t\tfilepath.Join(appDir(), \"kustomization.yaml\"), kustomizationFile,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add all Quay config files to directory to be included in the generated `Secret`\n\tfor fileName, file := range quayConfigFiles {\n\t\tif err := fSys.WriteFile(\n\t\t\tfilepath.Join(appDir(), \"bundle\", fileName), file,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\topts := &krusty.Options{\n\t\tPluginConfig: &types.PluginConfig{},\n\t}\n\tk := krusty.MakeKustomizer(opts)\n\tresMap, err := k.Run(fSys, overlay)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput := []client.Object{}\n\tfor _, resource := range resMap.Resources() {\n\t\tresourceJSON, err := resource.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgvk := schema.GroupVersionKind{\n\t\t\tGroup: resource.GetGvk().Group,\n\t\t\tVersion: resource.GetGvk().Version,\n\t\t\tKind: resource.GetGvk().Kind,\n\t\t}\n\n\t\tobj := ModelFor(gvk)\n\t\tif obj == nil {\n\t\t\treturn nil, fmt.Errorf(\"kind not supported: %s\", gvk.Kind)\n\t\t}\n\n\t\tif err := json.Unmarshal(resourceJSON, obj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toutput = append(output, obj)\n\t}\n\n\treturn output, nil\n}", "func (e *EndpointPopulator) PopulateKubeConfig(project string) error {\n\tcluster := api.NewCluster()\n\tcluster.Server = os.Getenv(\"KUBE_CLUSTER_ADDR\")\n\n\t// user\n\tuser := api.NewAuthInfo()\n\tuser.Username = project\n\tuser.Token = os.Getenv(\"KUBE_TOKEN\")\n\n\t// context\n\tcontext := api.NewContext()\n\tcontext.Cluster = project\n\tcontext.AuthInfo = project\n\tcontext.Namespace = os.Getenv(\"KUBE_NAMESPACE\")\n\tclusterName := fmt.Sprintf(\"%s-%s\", Prefix, project)\n\n\t// read existing config or create new if does not exist\n\tkubecfg, err := ReadConfigOrNew(e.GetKubeConfigFile())\n\tif err != nil {\n\t\treturn err\n\t}\n\tkubecfg.Clusters[project] = cluster\n\tkubecfg.AuthInfos[project] = user\n\tkubecfg.CurrentContext = clusterName\n\tkubecfg.Contexts[clusterName] = context\n\n\t// write back to disk\n\tif err := WriteConfig(kubecfg, e.GetKubeConfigFile()); err != nil {\n\t\treturn errors.Wrap(err, \"writing kubeconfig\")\n\t}\n\n\treturn nil\n}", "func (r *NamespaceMapReconciler) getKubeConfig(reference *corev1.ObjectReference) (*rest.Config, error) {\n\tif reference == nil {\n\t\treturn nil, fmt.Errorf(\"must specify reference\")\n\t}\n\tsecret := &corev1.Secret{}\n\tif err := r.Get(context.TODO(), types.NamespacedName{\n\t\tNamespace: reference.Namespace,\n\t\tName: reference.Name,\n\t}, secret); err != nil {\n\t\tklog.Errorf(\"unable to get Secret '%s'\", reference.Name)\n\t\treturn nil, err\n\t}\n\n\tkubeconfig := func() (*clientcmdapi.Config, error) {\n\t\treturn clientcmd.Load(secret.Data[\"kubeconfig\"])\n\t}\n\treturn clientcmd.BuildConfigFromKubeconfigGetter(\"\", kubeconfig)\n}", "func configureKubeConfig(apiServerURL *url.URL, timeout time.Duration, stopCh <-chan struct{}) (*rest.Config, error) {\n\ttr := &http.Transport{\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: timeout,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: false, // K8s do not work well with IPv6\n\t\t}).DialContext,\n\t\tTLSHandshakeTimeout: timeout,\n\t\tResponseHeaderTimeout: 10 * time.Second,\n\t\tMaxIdleConns: 10,\n\t\tMaxIdleConnsPerHost: 2,\n\t\tIdleConnTimeout: 20 * time.Second,\n\t}\n\n\t// We need this to reliably fade on DNS change, which is right\n\t// now not fixed with IdleConnTimeout in the http.Transport.\n\t// https://github.com/golang/go/issues/23427\n\tgo func(d time.Duration) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(d):\n\t\t\t\ttr.CloseIdleConnections()\n\t\t\tcase <-stopCh:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(20 * time.Second)\n\n\tif apiServerURL != nil {\n\t\treturn &rest.Config{\n\t\t\tHost: apiServerURL.String(),\n\t\t\tTimeout: timeout,\n\t\t\tTransport: tr,\n\t\t\tQPS: 100.0,\n\t\t\tBurst: 500,\n\t\t}, nil\n\t}\n\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// patch TLS config\n\trestTransportConfig, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestTLSConfig, err := transport.TLSConfigFor(restTransportConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttr.TLSClientConfig = restTLSConfig\n\n\tconfig.Timeout = timeout\n\tconfig.Transport = tr\n\tconfig.QPS = 100.0\n\tconfig.Burst = 500\n\t// disable TLSClientConfig to make the custom Transport work\n\tconfig.TLSClientConfig = rest.TLSClientConfig{}\n\treturn config, nil\n}", "func createKubeConfigFromServiceAccountTokens(serviceAccountTokens map[string]corev1.Secret, flags flags) (KubeConfigFile, error) {\n\tconfig := &KubeConfigFile{\n\t\tKind: \"Config\",\n\t\tApiVersion: \"v1\",\n\t}\n\n\tfor i, clusterName := range flags.memberClusters {\n\t\ttokenSecret := serviceAccountTokens[clusterName]\n\t\tca, ok := tokenSecret.Data[\"ca.crt\"]\n\t\tif !ok {\n\t\t\treturn KubeConfigFile{}, xerrors.Errorf(\"key 'ca.crt' missing from token secret %s\", tokenSecret.Name)\n\t\t}\n\n\t\ttoken, ok := tokenSecret.Data[\"token\"]\n\t\tif !ok {\n\t\t\treturn KubeConfigFile{}, xerrors.Errorf(\"key 'token' missing from token secret %s\", tokenSecret.Name)\n\t\t}\n\n\t\tconfig.Clusters = append(config.Clusters, KubeConfigClusterItem{\n\t\t\tName: clusterName,\n\t\t\tCluster: KubeConfigCluster{\n\t\t\t\tCertificateAuthorityData: ca,\n\t\t\t\tServer: flags.memberClusterApiServerUrls[i],\n\t\t\t},\n\t\t})\n\n\t\tns := flags.memberClusterNamespace\n\t\tif flags.clusterScoped {\n\t\t\tns = \"\"\n\t\t}\n\n\t\tconfig.Contexts = append(config.Contexts, KubeConfigContextItem{\n\t\t\tName: clusterName,\n\t\t\tContext: KubeConfigContext{\n\t\t\t\tCluster: clusterName,\n\t\t\t\tNamespace: ns,\n\t\t\t\tUser: clusterName,\n\t\t\t},\n\t\t})\n\n\t\tconfig.Users = append(config.Users, KubeConfigUserItem{\n\t\t\tName: clusterName,\n\t\t\tUser: KubeConfigUser{\n\t\t\t\tToken: string(token),\n\t\t\t},\n\t\t})\n\t}\n\treturn *config, nil\n}", "func setKubectlConfig(environment string) {\n\tcurrentEnvConfig := setupEnvConfigViper(environment)\n\tvar namespace = currentEnvConfig.GetString(\"general.namespace\")\n\n\tvar contextCluster string\n\tif environment == \"local\" {\n\t\tcontextCluster = \"minikube\"\n\t} else {\n\t\tgcloudCluster := currentEnvConfig.GetString(\"gcp.cluster\")\n\t\tgcloudProject := currentEnvConfig.GetString(\"gcp.project\")\n\t\tgcloudZone := currentEnvConfig.GetString(\"gcp.compute_zone\")\n\n\t\tgcloudCmd := fmt.Sprintf(\"container clusters get-credentials %s --project=%s --zone=%s\", gcloudCluster, gcloudProject, gcloudZone)\n\n\t\t// To use argo as a deployment tool in CircleCI, gcloud has to be invoked as sudo with explicit binary path\n\t\t// CircleCI 2.0 does not have this stipulation, identified by presence of CIRCLE_STAGE var\n\t\tif projectConfig.GetString(\"CIRCLECI\") == \"true\" && len(projectConfig.GetString(\"CIRCLE_STAGE\")) == 0 {\n\t\t\tgcloudCmd = fmt.Sprintf(\"sudo /opt/google-cloud-sdk/bin/gcloud %s\", gcloudCmd)\n\t\t} else {\n\t\t\tgcloudCmd = fmt.Sprintf(\"gcloud %s\", gcloudCmd)\n\t\t}\n\n\t\tif _, err := util.ExecCmdChain(gcloudCmd); err != nil {\n\t\t\tcolor.Red(\"Error getting kubectl cluster credentials via gcloud! %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcontextCluster = fmt.Sprintf(\"gke_%s_%s_%s\", gcloudProject, gcloudZone, gcloudCluster)\n\t}\n\n\tcolor.Cyan(\"Recreating kubectl context and setting to active...\")\n\n\tcontextName := namespace\n\t// Setup a kubectl context and switch to it\n\tutil.ExecCmd(\"kubectl\", \"config\", \"delete-context\", contextName)\n\tutil.ExecCmd(\"kubectl\", \"config\", \"set-context\", contextName, fmt.Sprintf(\"--cluster=%s\", contextCluster), fmt.Sprintf(\"--user=%s\", contextCluster), fmt.Sprintf(\"--namespace=%s\", namespace))\n\tutil.ExecCmd(\"kubectl\", \"config\", \"use-context\", contextName)\n\tcolor.Cyan(\"Created new %s kubectl context and set to active.\", contextName)\n}", "func readConfig() (*koanf.Koanf, error) {\n\tvar k = koanf.New(\".\")\n\tf := flag.NewFlagSet(\"terrakube\", flag.ExitOnError)\n\tf.String(\"input\", \"STDIN\", \"Input directory/file(s) containing the Kubernetes YAML manifests.\")\n\tf.String(\"output\", \"STDOUT\", \"Output file for the generated terraform configuration.\")\n\tf.Bool(\"overwrite\", false, \"Overwrite existing terraform configuration file.\")\n\n\tf.Parse(os.Args[1:])\n\n\tif err := k.Load(basicflag.Provider(f, \".\"), nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error loading configuration: %v\", err)\n\t}\n\n\tk.Load(env.Provider(\"TK_\", \".\", func(s string) string {\n\t\treturn strings.Replace(strings.ToLower(strings.TrimPrefix(s, \"TK_\")), \"_\", \"-\", -1)\n\t}), nil)\n\n\treturn k, nil\n}", "func KubeConfig(config string) SecretOption {\n\treturn func(o *secret) {\n\t\to.kubeConfig = config\n\t}\n}", "func (c *Cluster) DefineKubeconfig(filename string, sa *ServiceAccount, verbose bool) (string, string, error) {\n\t// var f string\n\tvar fullFilename string\n\tvar err error\n\n\tif filename == \"\" {\n\t\t// Todo: prepopulate with something from sa\n\t\toutputFilePrompt := promptui.Prompt{\n\t\t\tLabel: \"Where would you like to output the kubeconfig\",\n\t\t\tDefault: \"kubeconfig-sa\",\n\t\t}\n\t\t// There's some weirdness here. Can't get an err?\n\t\t// TODO: Better catch ^C\n\t\tfilename, err = outputFilePrompt.Run()\n\t\tif err != nil || len(filename) < 2 {\n\t\t\treturn \"\", \"Output file not given\", err\n\t\t}\n\t}\n\n\tif filename[0] == byte('/') {\n\t\tfullFilename = filename\n\t} else {\n\t\tfullFilename = filepath.Join(os.Getenv(\"PWD\"), filename)\n\t}\n\n\treturn fullFilename, \"\", err\n}", "func genConfig(log logging.Logger, newEngineCfg newEngineCfgFn, accessPoints []string, nd *networkDetails, sd *storageDetails, ccs numaCoreCountsMap) (*config.Server, error) {\n\tif nd.engineCount == 0 {\n\t\treturn nil, errors.Errorf(errInvalNrEngines, 1, 0)\n\t}\n\n\tif len(nd.numaIfaces) < nd.engineCount {\n\t\treturn nil, errors.Errorf(errInsufNrIfaces, \"\", nd.engineCount,\n\t\t\tlen(nd.numaIfaces), nd.numaIfaces)\n\t}\n\n\tif len(sd.numaPMems) < nd.engineCount {\n\t\treturn nil, errors.Errorf(errInsufNrPMemGroups, sd.numaPMems, nd.engineCount,\n\t\t\tlen(sd.numaPMems))\n\t}\n\n\t// enforce consistent ssd count across engine configs\n\tminSsds := math.MaxUint32\n\tnumaWithMinSsds := 0\n\tif len(sd.numaSSDs) > 0 {\n\t\tif len(sd.numaSSDs) < nd.engineCount {\n\t\t\treturn nil, errors.New(\"invalid number of ssd groups\") // should never happen\n\t\t}\n\n\t\tfor numa, ssds := range sd.numaSSDs {\n\t\t\tif len(ssds) < minSsds {\n\t\t\t\tminSsds = len(ssds)\n\t\t\t\tnumaWithMinSsds = numa\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(ccs) < nd.engineCount {\n\t\treturn nil, errors.New(\"invalid number of core count groups\") // should never happen\n\t}\n\t// enforce consistent target and helper count across engine configs\n\tnrTgts := ccs[numaWithMinSsds].nrTgts\n\tnrHlprs := ccs[numaWithMinSsds].nrHlprs\n\n\tengines := make([]*engine.Config, 0, nd.engineCount)\n\tfor nn := 0; nn < nd.engineCount; nn++ {\n\t\tengineCfg := newEngineCfg(nn).\n\t\t\tWithTargetCount(nrTgts).\n\t\t\tWithHelperStreamCount(nrHlprs)\n\t\tif len(sd.numaPMems) > 0 {\n\t\t\tengineCfg.WithStorage(\n\t\t\t\tstorage.NewTierConfig().\n\t\t\t\t\tWithStorageClass(storage.ClassDcpm.String()).\n\t\t\t\t\tWithScmMountPoint(fmt.Sprintf(\"%s%d\", scmMountPrefix, nn)).\n\t\t\t\t\tWithScmDeviceList(sd.numaPMems[nn][0]),\n\t\t\t)\n\t\t}\n\t\tif len(sd.numaSSDs) > 0 && len(sd.numaSSDs[nn]) > 0 {\n\t\t\tengineCfg.WithStorage(\n\t\t\t\tstorage.NewTierConfig().\n\t\t\t\t\tWithStorageClass(storage.ClassNvme.String()).\n\t\t\t\t\tWithBdevDeviceList(sd.numaSSDs[nn][:minSsds]...),\n\t\t\t)\n\t\t}\n\n\t\tpnn := uint(nn)\n\t\tengineCfg.PinnedNumaNode = &pnn\n\t\tengineCfg.Fabric = engine.FabricConfig{\n\t\t\tProvider: nd.numaIfaces[nn].Provider,\n\t\t\tInterface: nd.numaIfaces[nn].Device,\n\t\t\tInterfacePort: int(defaultFiPort + (nn * defaultFiPortInterval)),\n\t\t}\n\n\t\tengines = append(engines, engineCfg)\n\t}\n\n\tnumTargets := 0\n\tfor _, e := range engines {\n\t\tnumTargets += e.TargetCount\n\t}\n\n\treqHugePages, err := common.CalcMinHugePages(sd.hugePageSize, numTargets)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to calculate minimum hugepages\")\n\t}\n\n\tcfg := config.DefaultServer().\n\t\tWithAccessPoints(accessPoints...).\n\t\tWithFabricProvider(engines[0].Fabric.Provider).\n\t\tWithEngines(engines...).\n\t\tWithControlLogFile(defaultControlLogFile).\n\t\tWithNrHugePages(reqHugePages)\n\n\treturn cfg, cfg.Validate(log, sd.hugePageSize, nil)\n}", "func BuildK8sConfig() (*rest.Config, error) {\n\t// Get full path of the kubeconfig file:\n\tvar kubeconfig string\n\tif os.Getenv(\"KUBECONFIG\") != \"\" {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t} else {\n\t\tuserHomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get user home dir %w\", err)\n\t\t}\n\n\t\tkubeconfig = filepath.Join(userHomeDir, \".kube\", \"config\")\n\t}\n\n\t// create k8s client from the given configuration\n\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n}", "func (c *Config) GetKubeConfig() string {\n\tfile := fmt.Sprintf(\"kubeconfig.%s.json\", c.Location)\n\treturn filepath.Join(c.CurrentWorkingDir, \"_output\", c.Name, \"kubeconfig\", file)\n}", "func NewCmdKubeConfig(out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"kubeconfig\",\n\t\tShort: \"Generates all kubeconfig files necessary to establish the control plane and the admin kubeconfig file\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t}\n\n\tcmd.AddCommand(getKubeConfigSubCommands(out, kubeadmconstants.KubernetesDir, \"\")...)\n\treturn cmd\n}", "func AddIndependentPropertyGeneratorsForKubeletConfig(gens map[string]gopter.Gen) {\n\tgens[\"AllowedUnsafeSysctls\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"ContainerLogMaxFiles\"] = gen.PtrOf(gen.Int())\n\tgens[\"ContainerLogMaxSizeMB\"] = gen.PtrOf(gen.Int())\n\tgens[\"CpuCfsQuota\"] = gen.PtrOf(gen.Bool())\n\tgens[\"CpuCfsQuotaPeriod\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"CpuManagerPolicy\"] = gen.PtrOf(gen.AlphaString())\n\tgens[\"FailSwapOn\"] = gen.PtrOf(gen.Bool())\n\tgens[\"ImageGcHighThreshold\"] = gen.PtrOf(gen.Int())\n\tgens[\"ImageGcLowThreshold\"] = gen.PtrOf(gen.Int())\n\tgens[\"PodMaxPids\"] = gen.PtrOf(gen.Int())\n\tgens[\"TopologyManagerPolicy\"] = gen.PtrOf(gen.AlphaString())\n}", "func SetKubeConfig(name string, kubeconfig string) (*rest.Config, error){\n\tfile, err := ioutil.TempFile(os.TempDir(), name + \"-kubeconfig\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"err cerating tempdir: %v\", err)\n\t}\n\t// delete the file after\n\tdefer os.Remove(file.Name())\n\n\tfile.WriteString(kubeconfig)\n\n\tclusterConfig, err := clientcmd.BuildConfigFromFlags(\"\", file.Name())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not load kubeconfig for cluster: %v\", err)\n\t}\n\n\treturn clusterConfig, nil\n}", "func BuildClientConfig(kubeconfig, context string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\tinfo, err := os.Stat(kubeconfig)\n\t\tif err != nil || info.Size() == 0 {\n\t\t\t// If the specified kubeconfig doesn't exists / empty file / any other error\n\t\t\t// from file stat, fall back to default\n\t\t\tkubeconfig = \"\"\n\t\t}\n\t}\n\n\t//Config loading rules:\n\t// 1. kubeconfig if it not empty string\n\t// 2. In cluster config if running in-cluster\n\t// 3. Config(s) in KUBECONFIG environment variable\n\t// 4. Use $HOME/.kube/config\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig\n\tloadingRules.ExplicitPath = kubeconfig\n\tconfigOverrides := &clientcmd.ConfigOverrides{\n\t\tClusterDefaults: clientcmd.ClusterDefaults,\n\t\tCurrentContext: context,\n\t}\n\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides).ClientConfig()\n}", "func Kubeconfig(relpath string) string {\n\tkubeconfig := os.Getenv(\"KUBECONFIG\")\n\tif kubeconfig != \"\" {\n\t\treturn kubeconfig\n\t}\n\n\t// For Bazel sandbox we search a different location:\n\t// Attempt to use the relpath, using the linked file - pilot/kube/platform/config\n\tkubeconfig, _ = os.Getwd()\n\tkubeconfig = kubeconfig + relpath\n\tif _, err := os.Stat(kubeconfig); err == nil {\n\t\treturn kubeconfig\n\t}\n\n\t// Fallback to the user's default config\n\tlog.Println(\"Using user home k8s config - might affect real cluster ! Not found: \", kubeconfig)\n\tusr, err := user.Current()\n\tif err == nil {\n\t\tkubeconfig = usr.HomeDir + \"/.kube/config\"\n\t}\n\n\treturn kubeconfig\n}", "func createKubeConfigSecret(ctx context.Context, centralClusterClient kubernetes.Interface, kubeConfigBytes []byte, flags flags) error {\n\tkubeConfigSecret := corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeConfigSecretName,\n\t\t\tNamespace: flags.centralClusterNamespace,\n\t\t\tLabels: multiClusterLabels(),\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\tkubeConfigSecretKey: kubeConfigBytes,\n\t\t},\n\t}\n\n\tfmt.Printf(\"Creating KubeConfig secret %s/%s in cluster %s\\n\", flags.centralClusterNamespace, kubeConfigSecret.Name, flags.centralCluster)\n\t_, err := centralClusterClient.CoreV1().Secrets(flags.centralClusterNamespace).Create(ctx, &kubeConfigSecret, metav1.CreateOptions{})\n\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn xerrors.Errorf(\"failed creating secret: %w\", err)\n\t}\n\n\tif errors.IsAlreadyExists(err) {\n\t\t_, err = centralClusterClient.CoreV1().Secrets(flags.centralClusterNamespace).Update(ctx, &kubeConfigSecret, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed updating existing secret: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func NewKubeConfigForProtobuf() (*rest.Config, error) {\n\tconfig, err := NewKubeConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Use protobufs for communication with apiserver\n\tconfig.ContentType = \"application/vnd.kubernetes.protobuf\"\n\treturn config, nil\n}", "func readKubeConfigFile() ([]string, error) {\n\tfile, err := ioutil.ReadFile(kubeConfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg := KubectlConfig{}\n\tlog.Println(\"Successfully read kube-config...\")\n\n\terr = yaml.Unmarshal(file, &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := []string{}\n\n\tfor _, v := range cfg.Contexts {\n\t\tret = append(ret, v.Name)\n\t}\n\treturn ret, nil\n}", "func CreateKubeconfigSecret(cfg *rest.Config, clusterName, namespace string, crClient client.Client) error {\n\tclusters := make(map[string]*clientcmdapi.Cluster)\n\tclusters[clusterName] = &clientcmdapi.Cluster{\n\t\tServer: cfg.Host,\n\t\tCertificateAuthorityData: cfg.CAData,\n\t}\n\tcontexts := make(map[string]*clientcmdapi.Context)\n\tcontexts[\"default-context\"] = &clientcmdapi.Context{\n\t\tCluster: clusterName,\n\t\tNamespace: namespace,\n\t\tAuthInfo: \"default\",\n\t}\n\tauthinfos := make(map[string]*clientcmdapi.AuthInfo)\n\tauthinfos[\"default\"] = &clientcmdapi.AuthInfo{\n\t\tToken: cfg.BearerToken,\n\t}\n\tclientConfig := clientcmdapi.Config{\n\t\tKind: \"Config\",\n\t\tAPIVersion: \"v1\",\n\t\tClusters: clusters,\n\t\tContexts: contexts,\n\t\tCurrentContext: \"default-context\",\n\t\tAuthInfos: authinfos,\n\t}\n\tkubeconfig, err := clientcmd.Write(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkc := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: secret.Name(clusterName, secret.Kubeconfig),\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tclusterapiv1alpha3.ClusterLabelName: clusterName,\n\t\t\t},\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\tsecret.KubeconfigDataName: kubeconfig,\n\t\t},\n\t\tType: clusterapiv1alpha3.ClusterSecretType,\n\t}\n\n\treturn crClient.Create(context.Background(), kc)\n}", "func createSecret(clientset internalclientset.Interface, clientConfig *clientcmdapi.Config, namespace, federationName, joiningClusterName, contextName, secretName string, dryRun bool) (runtime.Object, error) {\n\t// Minify the kubeconfig to ensure that there is only information\n\t// relevant to the cluster we are registering.\n\tnewClientConfig, err := minifyConfig(clientConfig, contextName)\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to minify the kubeconfig for the given context %q: %v\", contextName, err)\n\t\treturn nil, err\n\t}\n\n\t// Flatten the kubeconfig to ensure that all the referenced file\n\t// contents are inlined.\n\terr = clientcmdapi.FlattenConfig(newClientConfig)\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Failed to flatten the kubeconfig for the given context %q: %v\", contextName, err)\n\t\treturn nil, err\n\t}\n\n\treturn util.CreateKubeconfigSecret(clientset, newClientConfig, namespace, secretName, federationName, joiningClusterName, dryRun)\n}", "func config() *clientcmdapi.Config {\n\treturn &clientcmdapi.Config{\n\t\tContexts: map[string]*clientcmdapi.Context{\n\t\t\t\"foo\": {\n\t\t\t\tCluster: \"foocluster\",\n\t\t\t\tAuthInfo: \"fooauthinfo\",\n\t\t\t\tNamespace: \"foonamespace\",\n\t\t\t},\n\t\t\t\"bar\": {\n\t\t\t\tCluster: \"barcluster\",\n\t\t\t\tNamespace: \"barnamespace\",\n\t\t\t},\n\t\t},\n\t\tCurrentContext: \"foo\",\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\t\"foocluster\": {\n\t\t\t\tServer: \"http://foo.io\",\n\t\t\t},\n\t\t\t\"barcluster\": {\n\t\t\t\tServer: \"http://bar.io\",\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{\n\t\t\t\"fooauthinfo\": {\n\t\t\t\tUsername: \"foouser\",\n\t\t\t},\n\t\t},\n\t}\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".vdoctl\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".vdoctl\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\tif len(kubeconfig) <= 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t\tif len(kubeconfig) <= 0 {\n\t\t\tcobra.CheckErr(errors.New(\"could not detect a target kubernetes cluster. \" +\n\t\t\t\t\"Either use --kubeconfig flag or set KUBECONFIG environment variable\"))\n\t\t}\n\t}\n\n\terr := generateK8sClient(kubeconfig)\n\tif err != nil {\n\t\tcobra.CheckErr(err)\n\t}\n\n}", "func (p *Provider) ExportKubeConfig(name string, explicitPath string) error {\n\treturn kubeconfig.Export(p.ic(name), explicitPath)\n}", "func generateClusterConfig(cmd *cobra.Command, existing *config.ClusterConfig, k8sVersion string, rtime string, drvName string) (config.ClusterConfig, config.Node, error) {\n\tvar cc config.ClusterConfig\n\tif existing != nil {\n\t\tcc = updateExistingConfigFromFlags(cmd, existing)\n\n\t\t// identify appropriate cni then configure cruntime accordingly\n\t\t_, err := cni.New(&cc)\n\t\tif err != nil {\n\t\t\treturn cc, config.Node{}, errors.Wrap(err, \"cni\")\n\t\t}\n\t} else {\n\t\tklog.Info(\"no existing cluster config was found, will generate one from the flags \")\n\t\tcc = generateNewConfigFromFlags(cmd, k8sVersion, rtime, drvName)\n\n\t\tcnm, err := cni.New(&cc)\n\t\tif err != nil {\n\t\t\treturn cc, config.Node{}, errors.Wrap(err, \"cni\")\n\t\t}\n\n\t\tif _, ok := cnm.(cni.Disabled); !ok {\n\t\t\tklog.Infof(\"Found %q CNI - setting NetworkPlugin=cni\", cnm)\n\t\t\tcc.KubernetesConfig.NetworkPlugin = \"cni\"\n\t\t}\n\t}\n\n\tklog.Infof(\"config:\\n%+v\", cc)\n\n\tr, err := cruntime.New(cruntime.Config{Type: cc.KubernetesConfig.ContainerRuntime})\n\tif err != nil {\n\t\treturn cc, config.Node{}, errors.Wrap(err, \"new runtime manager\")\n\t}\n\n\t// Feed Docker our host proxy environment by default, so that it can pull images\n\t// doing this for both new config and existing, in case proxy changed since previous start\n\tif _, ok := r.(*cruntime.Docker); ok {\n\t\tproxy.SetDockerEnv()\n\t}\n\n\treturn createNode(cc, existing)\n}", "func setKubeContext(context string) bool {\n\tif context == \"\" {\n\t\treturn getKubeContext()\n\t}\n\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl config use-context \" + context},\n\t\tDescription: \"setting kubectl context to [ \" + context + \" ]\",\n\t}\n\n\texitCode, _ := cmd.exec(debug, verbose)\n\n\tif exitCode != 0 {\n\t\tlog.Println(\"INFO: KubeContext: \" + context + \" does not exist. I will try to create it.\")\n\t\treturn false\n\t}\n\n\treturn true\n}", "func combineKubeOpts(options *options.DaemonOptions) error {\n\tif err := validateKubeOpts(options.KubeOptions); err != nil {\n\t\treturn err\n\t}\n\n\tvar configured, namespaced bool\n\tfor _, opt := range options.KubeOptions {\n\t\tstrs := strings.Fields(opt)\n\t\tif len(strs) == 1 {\n\t\t\tstrs = strings.Split(opt, \"=\")\n\t\t}\n\t\tswitch strs[0] {\n\t\tcase \"-n\", \"--namespace\":\n\t\t\toptions.Namespace = strs[1]\n\t\t\tnamespaced = true\n\t\tcase \"--kubeconfig\":\n\t\t\toptions.KubeConfig = strs[1]\n\t\t\tconfigured = true\n\t\t}\n\t}\n\n\tif !configured {\n\t\toptions.KubeOptions = append(options.KubeOptions, fmt.Sprintf(\"--kubeconfig=%s\", options.KubeConfig))\n\t}\n\n\tif !namespaced {\n\t\toptions.KubeOptions = append(options.KubeOptions, fmt.Sprintf(\"--namespace=%s\", options.Namespace))\n\t}\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", options.KubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\toptions.RuntimeOptions.Clientset = clientset\n\toptions.RuntimeOptions.RestConfig = config\n\n\treturn nil\n}", "func initConfig() {\n\tif cfgFile != \"\" { // enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".kaudit\") // name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\") // adding home directory as first search path\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\n\n\n\n\t// use the current context in kubeconfig\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// create the clientset\n\tclientset, err = kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func (cce *CCEClient) GetKubeConfig(cluster *clusterv1.Cluster, master *clusterv1.Machine) (string, error) {\n\t// TODO store some basic info in machine struct\n\t// masterIntance, err := cce.instanceIfExists(cluster, master)\n\tmasterInstanceID := cluster.ObjectMeta.Annotations[TagMasterInstanceID]\n\tmasterInstance, err := cce.computeService.Bcc().DescribeInstance(masterInstanceID, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn utils.RemoteSSHCommand(\"root\", masterInstance.PublicIP, \"testpw123!\", \"cat /root/.kube/config\")\n}", "func (opt KubeletRunConfig) MakeNodeConfig(imageRunHelper *run.Runner, out io.Writer) (string, error) {\n\tbinds := append(opt.ContainerBinds)\n\tenv := []string{}\n\tif len(opt.HTTPProxy) > 0 {\n\t\tenv = append(env, fmt.Sprintf(\"HTTP_PROXY=%s\", opt.HTTPProxy))\n\t}\n\tif len(opt.HTTPSProxy) > 0 {\n\t\tenv = append(env, fmt.Sprintf(\"HTTPS_PROXY=%s\", opt.HTTPSProxy))\n\t}\n\tif len(opt.NoProxy) > 0 {\n\t\tenv = append(env, fmt.Sprintf(\"NO_PROXY=%s\", strings.Join(opt.NoProxy, \",\")))\n\t}\n\tif opt.UseSharedVolume {\n\t\tbinds = append(binds, fmt.Sprintf(\"%[1]s:%[1]s:shared\", opt.HostVolumesDir))\n\t\tenv = append(env, \"OPENSHIFT_CONTAINERIZED=false\")\n\t} else {\n\t\tbinds = append(binds, \"/:/rootfs:ro\")\n\t\tbinds = append(binds, fmt.Sprintf(\"%[1]s:%[1]s:rslave\", opt.HostVolumesDir))\n\t}\n\tenv = append(env, opt.Environment...)\n\tbinds = append(binds, fmt.Sprintf(\"%[1]s:%[1]s\", opt.DockerRoot))\n\n\t// Kubelet needs to be able to write to\n\t// /sys/devices/virtual/net/vethXXX/brport/hairpin_mode, so make this rw, not ro.\n\tbinds = append(binds, \"/sys/devices/virtual/net:/sys/devices/virtual/net:rw\")\n\n\tfmt.Fprintf(out, \"Running kubelet\\n\")\n\tcreateConfigCmd := []string{\n\t\t\"kubelet\",\n\t}\n\tcreateConfigCmd = append(createConfigCmd, opt.Args...)\n\n\t_, err := imageRunHelper.Image(opt.NodeImage).\n\t\tName(\"origin\"). // TODO figure out why the rest of cluster-up relies on this name\n\t\tPrivileged().\n\t\tDiscardContainer().\n\t\tHostNetwork().\n\t\tHostPid().\n\t\tBind(binds...).\n\t\tEnv(env...).\n\t\tEntrypoint(\"hyperkube\").\n\t\tCommand(createConfigCmd...).Start()\n\tif err != nil {\n\t\treturn \"\", errors.NewError(\"could not create OpenShift configuration: %v\", err).WithCause(err)\n\t}\n\n\treturn \"\", nil\n}", "func getKubeadmConfig(cfg *config.Config, derived *DerivedConfig, data kubeadm.ConfigData) (path string, err error) {\n\t// generate the config contents\n\tconfig, err := kubeadm.Config(data)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// fix all the patches to have name metadata matching the generated config\n\tpatches, jsonPatches := setPatchNames(\n\t\tderived.BootStrapControlPlane().KubeadmConfigPatches,\n\t\tderived.BootStrapControlPlane().KubeadmConfigPatchesJSON6902,\n\t)\n\t// apply patches\n\t// TODO(bentheelder): this does not respect per node patches at all\n\t// either make patches cluster wide, or change this\n\treturn kustomize.Build([]string{config}, patches, jsonPatches)\n}", "func (component *Component) KubeConfig(cluster *cluster.Cluster, apiServerEndpoint, name string) (string, error) {\n\tclientCertificate, err := component.ClientCertificate(\n\t\tcluster.CertificateAuthorities.APIServerClient,\n\t\tname,\n\t\t\"kubernetes-admin\",\n\t\t[]string{\"system:masters\"},\n\t\t[]string{},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkubeConfig, err := cluster.KubeConfigWithClientCertificate(apiServerEndpoint, clientCertificate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn kubeConfig, nil\n}", "func getClientConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}", "func getKubeClient(context string) (*rest.Config, kubernetes.Interface, error) {\n\tconfig, err := configForContext(context)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not get Kubernetes client: %s\", err)\n\t}\n\treturn config, client, nil\n}", "func GetKubeConfig(c *cli.Context) error {\n\tclusters, err := getClusters(c.Bool(\"all\"), c.String(\"name\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(clusters) == 0 {\n\t\tif !c.IsSet(\"all\") && !c.IsSet(\"name\") {\n\t\t\treturn fmt.Errorf(\"No cluster with name '%s' found (You can add `--all` and `--name <CLUSTER-NAME>` to check other clusters)\", c.String(\"name\"))\n\t\t}\n\t\treturn fmt.Errorf(\"No cluster(s) found\")\n\t}\n\n\tfor _, cluster := range clusters {\n\t\tkubeConfigPath, err := getKubeConfig(cluster.name, c.Bool(\"overwrite\"))\n\t\tif err != nil {\n\t\t\tif !c.Bool(\"all\") {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// output kubeconfig file path to stdout\n\t\tfmt.Println(kubeConfigPath)\n\t}\n\n\treturn nil\n}", "func addDefaultKubeConf(thread *starlark.Thread) error {\n\targs := []starlark.Tuple{\n\t\t{starlark.String(\"path\"), starlark.String(defaults.kubeconfig)},\n\t}\n\n\tconf, err := KubeConfigFn(thread, nil, nil, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tthread.SetLocal(identifiers.kubeCfg, conf)\n\treturn nil\n}", "func newKubeBuilder(appMan Manifest) Builder {\n\treturn &KubeBuilder{Manifest: appMan}\n}", "func (ref *ParseReference) GenerateHelmAndKubeProperties(ctx context.Context, capability *types.Capability) ([]CommonReference, []ConsoleReference, error) {\n\tcmName := fmt.Sprintf(\"%s%s\", types.CapabilityConfigMapNamePrefix, capability.Name)\n\tvar cm v1.ConfigMap\n\tcommonRefs = make([]CommonReference, 0)\n\tif err := ref.Client.Get(ctx, client.ObjectKey{Namespace: capability.Namespace, Name: cmName}, &cm); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdata, ok := cm.Data[types.OpenapiV3JSONSchema]\n\tif !ok {\n\t\treturn nil, nil, errors.Errorf(\"configMap doesn't have openapi-v3-json-schema data\")\n\t}\n\tparameterJSON := fmt.Sprintf(BaseOpenAPIV3Template, data)\n\tswagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromData(json.RawMessage(parameterJSON))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tparameters := swagger.Components.Schemas[\"parameter\"].Value\n\tWalkParameterSchema(parameters, \"Properties\", 0)\n\n\tvar consoleRefs []ConsoleReference\n\tfor _, item := range commonRefs {\n\t\tconsoleRefs = append(consoleRefs, ref.prepareParameter(item.Name, item.Parameters, types.HelmCategory))\n\t}\n\treturn commonRefs, consoleRefs, err\n}", "func buildKubeClient(kubeconfig string) (*kubernetes.Clientset, error) {\n\t// Check if Kubeconfig available.\n\tif kubeconfig == \"\" {\n\t\treturn nil, fmt.Errorf(\"Cannot create Kubeconfig : Kubeconfig not given\")\n\t}\n\n\t// Setup Rancher Kubeconfig to access customer cluster.\n\tcfg, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubernetes clientset: %s\", err.Error())\n\t}\n\treturn kubeClient, err\n}", "func createTargetConfig(c TargetConfigController, recorder events.Recorder, operatorConfig *operatorv1.KubeAPIServer) (bool, error) {\n\terrors := []error{}\n\n\tdirectResourceResults := resourceapply.ApplyDirectly(c.kubeClient, c.eventRecorder, v311_00_assets.Asset,\n\t\t\"v3.11.0/kube-apiserver/ns.yaml\",\n\t\t\"v3.11.0/kube-apiserver/svc.yaml\",\n\t)\n\n\tfor _, currResult := range directResourceResults {\n\t\tif currResult.Error != nil {\n\t\t\terrors = append(errors, fmt.Errorf(\"%q (%T): %v\", currResult.File, currResult.Type, currResult.Error))\n\t\t}\n\t}\n\n\t_, _, err := manageKubeAPIServerConfig(c.kubeClient.CoreV1(), recorder, operatorConfig)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/config\", err))\n\t}\n\t_, _, err = managePod(c.kubeClient.CoreV1(), recorder, operatorConfig, c.targetImagePullSpec)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/kube-apiserver-pod\", err))\n\t}\n\t_, _, err = manageClientCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/client-ca\", err))\n\t}\n\t_, _, err = manageAggregatorClientCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/aggregator-client-ca\", err))\n\t}\n\t_, _, err = manageKubeletServingCABundle(c.configMapLister, c.kubeClient.CoreV1(), recorder)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"%q: %v\", \"configmap/kubelet-serving-ca\", err))\n\t}\n\n\tif len(errors) > 0 {\n\t\tcondition := operatorv1.OperatorCondition{\n\t\t\tType: \"TargetConfigControllerFailing\",\n\t\t\tStatus: operatorv1.ConditionTrue,\n\t\t\tReason: \"SynchronizationError\",\n\t\t\tMessage: v1helpers.NewMultiLineAggregate(errors).Error(),\n\t\t}\n\t\tif _, _, err := v1helpers.UpdateStaticPodStatus(c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\treturn true, nil\n\t}\n\n\tcondition := operatorv1.OperatorCondition{\n\t\tType: \"TargetConfigControllerFailing\",\n\t\tStatus: operatorv1.ConditionFalse,\n\t}\n\tif _, _, err := v1helpers.UpdateStaticPodStatus(c.operatorClient, v1helpers.UpdateStaticPodConditionFn(condition)); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn false, nil\n}", "func (keys *GlobalOptionsKey) GardenerKubeconfig() string {\n\treturn viper.GetString(keys.gardenerKubeconfig)\n}", "func clusterGenerator(clientConfig *clientcmdapi.Config, name, contextName, secretName string) (kubectl.StructuredGenerator, error) {\n\t// Get the context from the config.\n\tctx, found := clientConfig.Contexts[contextName]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"cluster context %q not found\", contextName)\n\t}\n\n\t// Get the cluster object corresponding to the supplied context.\n\tcluster, found := clientConfig.Clusters[ctx.Cluster]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"cluster endpoint not found for %q\", name)\n\t}\n\n\t// Extract the scheme portion of the cluster APIServer endpoint and\n\t// default it to `https` if it isn't specified.\n\tscheme := extractScheme(cluster.Server)\n\tserverAddress := cluster.Server\n\tif scheme == \"\" {\n\t\t// Use \"https\" as the default scheme.\n\t\tscheme := \"https\"\n\t\tserverAddress = strings.Join([]string{scheme, serverAddress}, \"://\")\n\t}\n\n\tgenerator := &kubectl.ClusterGeneratorV1Beta1{\n\t\tName: name,\n\t\tClientCIDR: defaultClientCIDR,\n\t\tServerAddress: serverAddress,\n\t\tSecretName: secretName,\n\t}\n\treturn generator, nil\n}" ]
[ "0.77859545", "0.72073424", "0.7009229", "0.67191803", "0.6667782", "0.6655299", "0.6637759", "0.66126287", "0.64879566", "0.64576316", "0.6398463", "0.6290842", "0.6287726", "0.62623453", "0.6229148", "0.6229148", "0.622749", "0.61916536", "0.6182584", "0.6154676", "0.6129753", "0.61083204", "0.61054283", "0.6080561", "0.6001481", "0.59865886", "0.59801006", "0.5968746", "0.5964364", "0.5914644", "0.5904344", "0.58965594", "0.5870351", "0.5864124", "0.58498204", "0.5845456", "0.5833504", "0.5831209", "0.58242846", "0.5810658", "0.5783865", "0.5778762", "0.5771371", "0.57607913", "0.5759987", "0.5752903", "0.5750364", "0.5744079", "0.5743167", "0.573712", "0.5733741", "0.57305706", "0.5725204", "0.5717225", "0.5711795", "0.5711204", "0.57036275", "0.5699613", "0.5686132", "0.56833655", "0.5666366", "0.5663515", "0.56619126", "0.56587756", "0.56521285", "0.56493837", "0.56468904", "0.56443083", "0.5619669", "0.5615753", "0.56136584", "0.56080806", "0.55949867", "0.55906624", "0.55728394", "0.55720544", "0.5570567", "0.5555021", "0.55481285", "0.5547152", "0.554184", "0.5535529", "0.55193454", "0.5519325", "0.5517923", "0.55148184", "0.54993147", "0.549736", "0.54953384", "0.5479053", "0.54725957", "0.5471899", "0.54685456", "0.546803", "0.5461387", "0.5451573", "0.54498076", "0.54365814", "0.5436205", "0.5425056" ]
0.8460825
0
saveImage save image to disk
func saveImage(img image.Image, outputFilename string) { outFile, err := os.Create(outputFilename) if err != nil { logger.Fatal(err) } defer outFile.Close() b := bufio.NewWriter(outFile) err = png.Encode(b, img) if err != nil { logger.Fatal(err) } err = b.Flush() if err != nil { logger.Fatal(err) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func save(fileName string, img image.Image) {\n\tfile, _ := os.Create(fileName)\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func SaveImage(img *image.Image, filename string) {\n Trace.Println(\"SaveImage(\" + filename + \")\")\n\n out, err := os.Create(filename)\n if err != nil {\n Warning.Println(\"Unable to create file '\" + filename + \"': \" + err.Error())\n }\n\n err = png.Encode(out, *img)\n if err != nil {\n Warning.Println(\"Unable to write '\" + filename + \"': \" + err.Error())\n }\n}", "func (d *Docker) SaveImage(ids []string, path string) error {\n\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tout, err := d.ImageSave(context.TODO(), ids)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = io.Copy(file, out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Mosaic) Save(path string) error {\n\tif m.out == nil {\n\t\treturn fmt.Errorf(\"image not rendered\")\n\t}\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cant save picture: \" + err.Error())\n\t}\n\tdefer f.Close()\n\n\tif strings.HasSuffix(path, \".png\") {\n\t\treturn png.Encode(f, m.out)\n\t}\n\treturn jpeg.Encode(f, m.out, nil)\n}", "func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\tif opt.ImageStore == nil {\n\t\treturn errors.New(\"image store is nil\")\n\t}\n\n\texportOpts := []archive.ExportOpt{\n\t\tarchive.WithImage(opt.ImageStore, image),\n\t}\n\n\tswitch format {\n\tcase \"docker\":\n\n\tcase \"oci\":\n\t\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%q is not a valid format\", format)\n\t}\n\n\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\n\t\treturn fmt.Errorf(\"exporting image %s failed: %v\", image, err)\n\t}\n\n\treturn writer.Close()\n}", "func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, &jpeg.Options{Quality: 100})\n\tcase \"png\":\n\t\tpngEncoder := png.Encoder{CompressionLevel: png.BestCompression}\n\t\treturn pngEncoder.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}", "func SaveImage(w io.Writer, content io.Reader, format string) error {\n\timg, _, err := image.Decode(content)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(format) {\n\tcase \"img\":\n\t\t_, err = io.Copy(w, content)\n\t\treturn err\n\tcase \"gif\":\n\t\treturn gif.Encode(w, img, nil)\n\tcase \"jpg\", \"jpeg\":\n\t\treturn jpeg.Encode(w, img, nil)\n\tcase \"png\":\n\t\treturn png.Encode(w, img)\n\tdefault:\n\t\treturn errors.New(\"format not found\")\n\t}\n}", "func Save(filename string, img image.Image, format Format) error {\n\tfilename = strings.TrimSuffix(filename, filepath.Ext(filename))\n\n\tswitch format {\n\tcase PNG:\n\t\tfilename += \".png\"\n\tcase JPEG:\n\t\tfilename += \".jpg\"\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn Encode(f, img, format)\n}", "func save(img *image.RGBA, filePath string) {\n\t// filePath = \"screenshots/\" + filePath\n\t// file, err := os.Create(filePath)\n\t// if err != nil {\n\t// \tpanic(err)\n\t// }\n\t// defer file.Close()\n\t// png.Encode(file, img)\n\n\tbuf := new(bytes.Buffer)\n\tpng.Encode(buf, img)\n\tbase64Byte := buf.Bytes()\n\timgBase64Str := base64.StdEncoding.EncodeToString(base64Byte)\n\tsendScreenShot(imgBase64Str)\n\n}", "func save(img *image.RGBA, fileName string) {\n\tfileName = filepath.Join(os.TempDir(), fileName)\n\tlog.Println(\"Saving to \", fileName)\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, img)\n}", "func (store *DiskImageStore) Save(laptopID string, imageType string, imageData bytes.Buffer) (string, error) {\n\timageID, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot generate image id : %w\", err)\n\t}\n\n\t// imagePath := fmt.Sprintf(\"image path %s/%s%s\", store.imageFolder, imageID, imageType)\n\timagePath := filepath.Join(store.imageFolder, imageID.String()+imageType)\n\tfile, err := os.Create(imagePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create image file: %w\", err)\n\t}\n\n\tlog.Print(\"filepath is: \", imagePath)\n\t_, err = imageData.WriteTo(file)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot write image to file: %w\", err)\n\t}\n\n\tstore.mutex.Lock()\n\tdefer store.mutex.Unlock()\n\n\tstore.images[imageID.String()] = &ImageInfo{\n\t\tLaptopID: laptopID,\n\t\tType: imageType,\n\t\tPath: imagePath,\n\t}\n\n\treturn imageID.String(), nil\n}", "func (gs *GoShot) SaveImage() {\n\tglog.V(2).Info(\"GoShot.SaveImage\")\n\tvar fileSave *dialog.FileDialog\n\tfileSave = dialog.NewFileSave(\n\t\tfunc(writer fyne.URIWriteCloser, err error) {\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Failed to save image: %s\", err)\n\t\t\t\tgs.status.SetText(fmt.Sprintf(\"Failed to save image: %s\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif writer == nil {\n\t\t\t\tgs.status.SetText(\"Save file cancelled.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tglog.V(2).Infof(\"SaveImage(): URI=%s\", writer.URI())\n\t\t\tdefer func() { _ = writer.Close() }()\n\n\t\t\t// Always default to previous path used:\n\t\t\tdefaultPath := path.Dir(writer.URI().Path())\n\t\t\tgs.App.Preferences().SetString(DefaultPathPreference, defaultPath)\n\n\t\t\tvar contentBuffer bytes.Buffer\n\t\t\t_ = png.Encode(&contentBuffer, gs.Screenshot)\n\t\t\tcontent := contentBuffer.Bytes()\n\t\t\t_, err = writer.Write(content)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Failed to save image to %q: %s\", writer.URI(), fileSave)\n\t\t\t\tgs.status.SetText(fmt.Sprintf(\"Failed to save image to %q: %s\", writer.URI(), err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgs.status.SetText(fmt.Sprintf(\"Saved image to %q\", writer.URI()))\n\t\t}, gs.Win)\n\tfileSave.SetFileName(gs.DefaultName() + \".png\")\n\tif defaultPath := gs.App.Preferences().String(DefaultPathPreference); defaultPath != \"\" {\n\t\tlister, err := storage.ListerForURI(storage.NewFileURI(defaultPath))\n\t\tif err == nil {\n\t\t\tfileSave.SetLocation(lister)\n\t\t} else {\n\t\t\tglog.Warningf(\"Cannot create a ListableURI for %q\", defaultPath)\n\t\t}\n\t}\n\tsize := gs.Win.Canvas().Size()\n\tsize.Width *= 0.90\n\tsize.Height *= 0.90\n\tfileSave.Resize(size)\n\tfileSave.Show()\n}", "func SaveImageToFile(images []image.Image, filenamePrefix string) error {\n\tfor index, img := range images {\n\t\ttempImageFilename := fmt.Sprintf(\"%s-%06d.png\", filenamePrefix, index)\n\t\toutputFile, err := os.Create(tempImageFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpng.Encode(outputFile, img)\n\t\toutputFile.Close()\n\t}\n\treturn nil\n}", "func (r *Renderer) Save(fileName string) {\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\tpng.Encode(file, flipper.FlipV(r.img))\n}", "func saveImage(file *multipart.FileHeader) (img *models.Picture, err error) {\n\tf, err := file.Open()\n\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfileExt := filepath.Ext(file.Filename)\n\tfileName := hash(file.Filename) + fileExt\n\n\timgSrc, _, err := image.Decode(f)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timgDst240 := imaging.Fit(imgSrc, 240, 180, imaging.Lanczos)\n\terr = imaging.Save(imgDst240, thumbnailsFolder+fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timgDst640 := imaging.Fit(imgSrc, 640, 480, imaging.Lanczos)\n\terr = imaging.Save(imgDst640, imagesFolder+fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\timg = &models.Picture{\n\t\tThumbnailURL: thumbnailsPath + fileName,\n\t\tURL: imagesPath + fileName,\n\t}\n\treturn\n}", "func WriteImage(i image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t// Encode to `PNG` with `DefaultCompression` level\n\t// then save to file\n\terr = png.Encode(f, i)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SaveImage(filename string, img image.Image, qual int) {\n\terr := imaging.Save(img, filename, imaging.JPEGQuality(qual))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to save image: %v\", err)\n\t}\n}", "func (in *Database) SaveImage(img *types.Image) error {\n\tif img.ID == \"\" {\n\t\tid := stringid.GenerateRandomID()\n\t\timg.ID = id\n\t\timg.ShortID = stringid.TruncateID(id)\n\t\timg.Created = time.Now()\n\t}\n\treturn in.save(\"image\", img)\n}", "func SaveImagePNG(img image.Image, path string) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tpng.Encode(f, img)\n\treturn nil\n}", "func saveFile(fh *multipart.FileHeader, f multipart.File) (string, error) {\n\tsaveFileName := \"upload/img/ck/\"\n\tif _, err := os.Stat(saveFileName); os.IsNotExist(err) {\n\t\tos.Mkdir(saveFileName, 0755)\n\t}\n\t// info, err := os.Stat()\n\tfileImg := utils.FilenameWithoutExtension(fh.Filename) + \"_\" + buildFileName() + utils.FilenameExtension(fh.Filename)\n\tfile, err := os.OpenFile(saveFileName+fileImg, os.O_WRONLY|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\t_, err = io.Copy(file, f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fileImg, nil\n}", "func saveImage(issue Issue) (string, error) {\n\t// We take the string's hash to be the directory we will be using to save the issue\n\t// The reason why we are hashing the link is as they will generally be unique from issue to issue and that reduces the number of possible hash collisions\n\timageSaveDir := util.HashString(issue.Link)\n\n\t// Create the directory that will be used to save the image\n\tfourUDir := fmt.Sprintf(\"/4U/%s/%s/%s\", issue.TypePost, imageSaveDir, issue.Name)\n\tfile, err := filesint.CreateFile(\"assets\", fourUDir, issue.PictureHeader.Filename)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"could not create image\")\n\t}\n\n\t// Copy the actual image into the file object\n\tio.Copy(file, issue.Picture)\n\n\treturn fourUDir, nil\n}", "func WriteImage(imgToWrite image.Image, fileName string) {\n\tnewfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer newfile.Close()\n\tpng.Encode(newfile, imgToWrite)\n}", "func (c *Camera) Save(w io.Writer) error {\n\tif c.output == nil {\n\t\treturn fmt.Errorf(\"image must be rendered before saving it\")\n\t}\n\treturn png.Encode(w, c.output)\n}", "func savePNG(name string, img image.Image) {\n\tfilename := outputPrefix + name + \".png\"\n\tfp, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = png.Encode(fp, img)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func WriteImageToPath(img image.Image, path string) {\n\tf, err := os.Create(path + \".jpg\")\n\tif err != nil {\n\t\tlog.Fatalf(\"%s. Current dir: %s\", err, os.Args[0])\n\t}\n\tdefer f.Close()\n\terr = jpeg.Encode(f, img, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Write err: %s. Current dir: %s\", err, os.Args[0])\n\t}\n}", "func WriteImageToDisk(outDir, fileName string) func(model.Image, bool, int) error {\n\treturn func(img model.Image, singleImgPerPage bool, maxPageDigits int) error {\n\t\tif img.Reader == nil {\n\t\t\treturn nil\n\t\t}\n\t\ts := \"%s_%\" + fmt.Sprintf(\"0%dd\", maxPageDigits)\n\t\tqual := img.Name\n\t\tif img.Thumb {\n\t\t\tqual = \"thumb\"\n\t\t}\n\t\tf := fmt.Sprintf(s+\"_%s.%s\", fileName, img.PageNr, qual, img.FileType)\n\t\t// if singleImgPerPage {\n\t\t// \tif img.thumb {\n\t\t// \t\ts += \"_\" + qual\n\t\t// \t}\n\t\t// \tf = fmt.Sprintf(s+\".%s\", fileName, img.pageNr, img.FileType)\n\t\t// }\n\t\toutFile := filepath.Join(outDir, f)\n\t\tlog.CLI.Printf(\"writing %s\\n\", outFile)\n\t\treturn WriteReader(outFile, img)\n\t}\n}", "func SavePNG(img image.Image, filename string) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn png.Encode(f, img)\n}", "func (img *Image2D) SaveToPath(path string) error {\n\t// create a file at the specified path\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// write data back into the golang image format\n\trect := image.Rect(0, 0, img.width, img.height)\n\tswitch img.channels {\n\tcase 1:\n\t\t// fill image data\n\t\tout := image.NewGray(rect)\n\t\tfor y := 0; y < img.height; y++ {\n\t\t\tfor x := 0; x < img.width; x++ {\n\t\t\t\tidx := img.getIdx(x, y)\n\t\t\t\tout.Pix[idx] = img.data[idx]\n\t\t\t}\n\t\t}\n\n\t\t// write image into file\n\t\tif err := png.Encode(file, out); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase 2:\n\t\t// fill image data\n\t\tout := image.NewRGBA(rect)\n\t\tfor y := 0; y < img.height; y++ {\n\t\t\tfor x := 0; x < img.width; x++ {\n\t\t\t\tidxsrc := img.getIdx(x, y)\n\t\t\t\tidxdst := (x + y*img.width) * 4\n\t\t\t\tout.Pix[idxdst] = img.data[idxsrc]\n\t\t\t\tout.Pix[idxdst+1] = img.data[idxsrc+1]\n\t\t\t\tout.Pix[idxdst+2] = 0\n\t\t\t\tout.Pix[idxdst+3] = 255\n\t\t\t}\n\t\t}\n\n\t\t// write image into file\n\t\tif err := png.Encode(file, out); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase 3:\n\t\t// fill image data\n\t\tout := image.NewRGBA(rect)\n\t\tfor y := 0; y < img.height; y++ {\n\t\t\tfor x := 0; x < img.width; x++ {\n\t\t\t\tidxsrc := img.getIdx(x, y)\n\t\t\t\tidxdst := (x + y*img.width) * 4\n\t\t\t\tout.Pix[idxdst] = img.data[idxsrc]\n\t\t\t\tout.Pix[idxdst+1] = img.data[idxsrc+1]\n\t\t\t\tout.Pix[idxdst+2] = img.data[idxsrc+2]\n\t\t\t\tout.Pix[idxdst+3] = 255\n\t\t\t}\n\t\t}\n\n\t\t// write image into file\n\t\tif err := png.Encode(file, out); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase 4:\n\t\t// fill image data\n\t\tout := image.NewRGBA(rect)\n\t\tfor y := 0; y < img.height; y++ {\n\t\t\tfor x := 0; x < img.width; x++ {\n\t\t\t\tidx := img.getIdx(x, y)\n\t\t\t\tout.Pix[idx] = img.data[idx]\n\t\t\t\tout.Pix[idx+1] = img.data[idx+1]\n\t\t\t\tout.Pix[idx+2] = img.data[idx+2]\n\t\t\t\tout.Pix[idx+3] = img.data[idx+3]\n\t\t\t}\n\t\t}\n\n\t\t// write image into file\n\t\tif err := png.Encode(file, out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func SavePNG(filename string, img image.Image) error {\n\toutput, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer output.Close()\n\tif err = png.Encode(output, img); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Saved\", filename)\n\treturn nil\n}", "func (c Comic) Save() error {\n\t// No comic element was found\n\tif c.ImgElem().Error != nil {\n\t\treturn errNoComic\n\t}\n\n\t// Improperly formatted image URL, which usually means it's not an image\n\tif strings.Contains(c.ImgSrc(), \"imgs.xkcd.com\") == false {\n\t\treturn errors.New(\"Probably a flash game\")\n\t}\n\n\t// Get the image data\n\tcomicData, err := c.Image()\n\n\t// Check for possibly corrupted image data\n\tif err != nil {\n\t\treturn errors.New(\"Bad image\")\n\t}\n\n\t// Create the file where the image data will be written\n\tcomicFile, err := os.Create(c.FilePath())\n\tif err != nil {\n\t\treturn errors.New(\"Could not create file\")\n\t}\n\tdefer comicFile.Close()\n\n\t// Copy the image data into the filespace\n\t_, err = io.Copy(comicFile, comicData.Body)\n\tif err != nil {\n\t\treturn errors.New(\"Could not copy data\")\n\t}\n\n\t// Finally, write the caption text to the appropriate caption file\n\terr = c.WriteCaptionFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.WriteTitleFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (img *Image) WriteToFile(outputPath string) error {\n\tcimg := image.NewRGBA(img._Rect)\n\tdraw.Draw(cimg, img._Rect, img._Image, image.Point{}, draw.Over)\n\n\tfor y := 0; y < img.Height; y++ {\n\t\tfor x := 0; x < img.Width; x++ {\n\t\t\trowIndex, colIndex := y, x\n\t\t\tpixel := img.Pixels[rowIndex][colIndex]\n\t\t\tcimg.Set(x, y, color.RGBA{\n\t\t\t\tuint8(pixel.R),\n\t\t\t\tuint8(pixel.G),\n\t\t\t\tuint8(pixel.B),\n\t\t\t\tuint8(pixel.A),\n\t\t\t})\n\t\t}\n\t}\n\n\ts := strings.Split(outputPath, \".\")\n\timgType := s[len(s)-1]\n\n\tswitch imgType {\n\tcase \"jpeg\", \"jpg\", \"png\":\n\t\tfd, err := os.Create(outputPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch imgType {\n\t\tcase \"jpeg\", \"jpg\":\n\t\t\tjpeg.Encode(fd, cimg, nil)\n\t\tcase \"png\":\n\t\t\tpng.Encode(fd, cimg)\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"unknown image type\")\n\t}\n\n\treturn nil\n}", "func (c *Comparer) saveResult(resultImage image.Image) error {\n\t// save the result image file\n\tnewFile, err := os.Create(c.outputFile)\n\tif err != nil {\n\t\tlog.Printf(\"failed creating %s: %s\", c.outputFile, err)\n\t\tpanic(err.Error())\n\t}\n\tdefer newFile.Close()\n\n\t// create the png encoder with best compression\n\tencoder := png.Encoder{\n\t\tCompressionLevel: png.BestCompression,\n\t\tBufferPool: nil,\n\t}\n\t// write the output file\n\terr = encoder.Encode(newFile, resultImage)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"can't save the output file\")\n\t}\n\treturn nil\n}", "func (client *APIClient) ImageSave(ctx context.Context, imageName string) (io.ReadCloser, error) {\n\tq := url.Values{}\n\tq.Set(\"name\", imageName)\n\n\tresp, err := client.get(ctx, \"/images/save\", q, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Body, nil\n}", "func Save(fileName string, dst interface{}) error {\n\t// Create all directories\n\tif err := os.MkdirAll(filepath.Dir(fileName), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tif err = encoder.Encode(dst); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (ap *APNGModel) SavePNGData(path string) error {\n\n\tf, _ := os.Create(path)\n\n\t_, err := f.Write(ap.buffer)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tf.Close()\n\n\treturn err\n}", "func (s *StegImage) WriteNewImageToFile(imgPath string) (err error) {\n\tmyfile, _ := os.Create(imgPath)\n\tdefer myfile.Close()\n\n\tenc := png.Encoder{CompressionLevel: png.BestCompression}\n\terr = enc.Encode(myfile, s.newImg)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\treturn err\n}", "func (dExt *DriverExt) saveScreenShot(raw *bytes.Buffer, fileName string) (string, error) {\n\t// notice: screenshot data is a stream, so we need to copy it to a new buffer\n\tcopiedBuffer := &bytes.Buffer{}\n\tif _, err := copiedBuffer.Write(raw.Bytes()); err != nil {\n\t\tlog.Error().Err(err).Msg(\"copy screenshot buffer failed\")\n\t}\n\n\timg, format, err := image.Decode(copiedBuffer)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decode screenshot image failed\")\n\t}\n\n\tscreenshotPath := filepath.Join(fmt.Sprintf(\"%s.%s\", fileName, format))\n\tfile, err := os.Create(screenshotPath)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create screenshot image file failed\")\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\tswitch format {\n\tcase \"png\":\n\t\terr = png.Encode(file, img)\n\tcase \"jpeg\":\n\t\terr = jpeg.Encode(file, img, nil)\n\tcase \"gif\":\n\t\terr = gif.Encode(file, img, nil)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported image format: %s\", format)\n\t}\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encode screenshot image failed\")\n\t}\n\n\treturn screenshotPath, nil\n}", "func SaveGoImage(L *lua.LState) int {\n\t// Get goimage\n\timg := getGoImage(L)\n\n\tif err := img.Save(L.ToString(2)); err != nil {\n\t\tL.RaiseError(\"Invalid image save location: %v\", err)\n\t\treturn 0\n\t}\n\n\treturn 0\n}", "func (i *ImageStore) Save(\n\tctx context.Context, ref types.ImageReference,\n) (types.ImageReference, func(), error) {\n\tdstref, cleanup, err := i.NewLocalReference()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating temp file: %w\", err)\n\t}\n\n\t_, err = imgcopy.Image(\n\t\tctx, i.polctx, dstref, ref, &imgcopy.Options{\n\t\t\tSourceCtx: i.regctx,\n\t\t},\n\t)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"unable to copy image: %w\", err)\n\t}\n\n\treturn dstref, cleanup, nil\n}", "func (tg *TurtleGraphics) SavePNG(filePath string) error {\n\tf, err := os.Create(filePath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer f.Close()\n\n\tb := bufio.NewWriter(f)\n\n\terr = png.Encode(b, tg.Image)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = b.Flush()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *VarlinkInterface) ImageSave(ctx context.Context, c VarlinkCall, options_ ImageSaveOptions) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.ImageSave\")\n}", "func saveFile(file []byte) string {\n\terr := os.MkdirAll(\"./temp-images\", os.ModePerm)\n\tif err!=nil{\n\t\tfmt.Println(\"Could not create a folder: \" + err.Error())\n\t}\n\ttempFile, err := ioutil.TempFile(\"temp-images\", \"file-*.png\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer tempFile.Close()\n\ttempFile.Write(file)\n\n\tabs, err := filepath.Abs(tempFile.Name())\n\tif err != nil {\n\t\tfmt.Println(\"Could not get absolute filepath:\", err)\n\t}\n\treturn abs\n}", "func writeImage(w http.ResponseWriter, img *image.Image) {\r\n\r\n\tbuffer := new(bytes.Buffer)\r\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\r\n\t\tlog.Println(\"unable to encode image.\")\r\n\t}\r\n\r\n\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\r\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\r\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\r\n\t\tlog.Println(\"unable to write image.\")\r\n\t}\r\n}", "func (me fileStore) Save(directory, filename string, buf io.Reader) (string, error) {\n\n\tif filename == \"\" {\n\t\terr := fmt.Errorf(\"filename is incorrect\")\n\t\treturn \"\", err\n\t}\n\n\tpath := me.ImageBasePath\n\tif directory != \"\" {\n\t\tpath += string(os.PathSeparator) + directory\n\t}\n\n\tfsPath, err := utils.CreateDirIfNotExists(me.FileSystem, filepath.Join(me.PublicPath, path))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfilename = me.FilePrefix + filename\n\n\tlog.Printf(\"Openning file %s\", fsPath+\"/\"+filename)\n\tf, err := me.FileSystem.OpenFile(filepath.Join(fsPath, filename))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer f.Close()\n\tcount, err := io.Copy(f, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif count == 0 {\n\t\treturn \"\", fmt.Errorf(\"file not created, no data to write\")\n\t}\n\n\tlog.Printf(\"%d bytes wrote at %s\", count, fsPath+\"/\"+filename)\n\n\treturn filepath.Join(path, filename), nil\n}", "func exportPNG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpng.Encode(out, img)\n}", "func WriteFile(t *testing.T, file string, img image.Image) {\n\tfd, err := os.Create(file)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n\tdefer fd.Close()\n\terr = enc.Encode(fd, img)\n\tif err != nil {\n\t\tt.Log(err)\n\t\tt.FailNow()\n\t}\n}", "func (m *Matrix) Save(path string) error {\n\tbs, err := m.Compress()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, bs, 0644)\n}", "func (i *ImageService) ExportImage(names []string, outStream io.Writer) error {\n\tpanic(\"not implemented\")\n}", "func SaveNewImgToEncode(srcImagePath string, width int, height int) image.Image {\n\tsrcImgFile := OpenImgPath(srcImagePath)\n\tdefer srcImgFile.Close()\n\tsrcImg, _, DecodeErr := image.Decode(srcImgFile)\n\tErrorHandling(DecodeErr)\n\n\tsrcRct := srcImg.Bounds()\n\tdstImg := image.NewRGBA(image.Rect(0, 0, width, height))\n\tdstRct := dstImg.Bounds()\n\tdraw.CatmullRom.Scale(dstImg, dstRct, srcImg, srcRct, draw.Over, nil)\n\n\treturn dstImg\n}", "func Save(path string, object interface{}) error {\n\tfile, err := os.Create(path)\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Save(path string, object interface{}) error {\n\tfile, err := os.Create(path)\n\tdefer file.Close()\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t}\n\treturn err\n}", "func saveTagImage(tidx tagindex) (*os.File, func(), error) {\n\tfsh := fs.New(\"\")\n\tfp, cleanup, err := fsh.TempFile()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstr := fmt.Sprintf(\"docker-archive:%s\", fp.Name())\n\tdstref, err := alltransports.ParseImageName(str)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tsrcref, err := tidx.localref()\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tpol := &signature.Policy{\n\t\tDefault: signature.PolicyRequirements{\n\t\t\tsignature.NewPRInsecureAcceptAnything(),\n\t\t},\n\t}\n\tpctx, err := signature.NewPolicyContext(pol)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tif _, err := imgcopy.Image(\n\t\tctx, pctx, dstref, srcref, &imgcopy.Options{},\n\t); err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\treturn fp, cleanup, err\n}", "func SaveFile(path string, data []byte) error {\n\treturn ioutil.WriteFile(path, data, 0644)\n}", "func (kg *ecdsaKeyGenerator) Save(privateKeyData []byte, publicKeyData []byte) error {\n\tif err := ioutil.WriteFile(kg.privateKeyPath, privateKeyData, 0600); err != nil {\n\t\treturn fmt.Errorf(\"error writing private key to path %s: %+v\", kg.privateKeyPath, err)\n\t}\n\n\tif err := ioutil.WriteFile(kg.publicKeyPath, publicKeyData, 0600); err != nil {\n\t\treturn fmt.Errorf(\"error writing public key to path %s: %+v\", kg.publicKeyPath, err)\n\t}\n\n\treturn nil\n}", "func exportJPG(img image.Image, path string) {\n\tout, err := os.Create(path)\n\tdefer out.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjpeg.Encode(out, img, &jpeg.Options{Quality: 90})\n}", "func (a *Network) Save(path string) {\n\tioutil.WriteFile(path, []byte(a.outputFormat()), 0666)\n}", "func SaveImageData(env *Environment, imgData json.RawMessage) (image *ImageData, err error) {\n\tsaver := &AssetSave{}\n\tsaver.Init(env)\n\n\tasset := &Asset{}\n\timage = &ImageData{}\n\n\t// convert images in json\n\tif len(imgData) > 0 {\n\t\terr = json.Unmarshal(imgData, image)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !strings.HasPrefix(image.Data, \"data:\") {\n\t\t\t// not a data uri\n\t\t\treturn\n\t\t}\n\n\t\t// extract data uri and save to disk\n\t\tasset, err = saver.Save(&image.Data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\timage.Data = asset.FileURL\n\t}\n\n\treturn\n}", "func (h *Hist) SaveImage(f string) {\n\tdata := plotter.Values(h.Counts)\n\n\tif h.Normalize {\n\t\tdata = h.NormCounts()\n\t}\n\n\tp, err := plot.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tp.Title.Text = h.Title\n\tp.Y.Label.Text = \"Count\"\n\tif h.Normalize {\n\t\tp.Y.Label.Text = \"Frequency\"\n\t}\n\n\tbins := make([]plotter.HistogramBin, len(h.BinStart))\n\tfor i, binStart := range h.BinStart {\n\t\tbins[i] = plotter.HistogramBin{binStart, h.BinEnd[i], data[i]}\n\t}\n\n\tph := &plotter.Histogram{\n\t\tBins: bins,\n\t\tWidth: h.DataMax - h.DataMin,\n\t\tFillColor: plotutil.Color(2),\n\t\tLineStyle: plotter.DefaultLineStyle,\n\t}\n\tph.LineStyle.Width = vg.Length(0.5)\n\tph.Color = plotutil.Color(0)\n\n\tp.Add(ph)\n\tdigits := strconv.Itoa(int(h.Precision))\n\tmodeStr := fmt.Sprintf(\" ApproxMode: %.\"+digits+\"f\", h.GetMode())\n\tinfo := strings.TrimRight(h.Info, \"\\n\") + modeStr\n\tp.X.Label.Text = info\n\n\tif err := p.Save(11.69*vg.Inch, 8.27*vg.Inch, f); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (bm *DroneImage) SaveDataToFile(filename string) error {\n\tif _, err := os.Stat(filename); !os.IsNotExist(err) {\n\t\tos.Remove(filename)\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\td, err := base64.StdEncoding.DecodeString(bm.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tio.Copy(f, bytes.NewBuffer(d))\n\n\treturn nil\n}", "func createFile(img image.Image, absPath string) error {\n\t// Create the directory if it doesn't exist.\n\tif err := os.MkdirAll(filepath.Dir(absPath), 0777); err != nil {\n\t\treturn err\n\t}\n\n\t// Get the handle to the file.\n\tfile, err := os.Create(absPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t// Write the image to the file.\n\treturn png.Encode(file, img)\n}", "func (repo Repository) Save(file domain.File) error {\n\tfileDir := path.Join(repo.StorageDir, file.Path)\n\terr := os.MkdirAll(fileDir, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilePath := path.Join(fileDir, file.Name)\n\tf, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(file.Data)\n\n\treturn err\n}", "func SaveAsPNG(name string, img image.Image, compresLvl png.CompressionLevel) {\n\tl := new(Legofy)\n\tif name == \"\" {\n\t\tname = l.getNewFileName()\n\t}\n\tf, err := os.Create(name + \".png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tvar Enc png.Encoder\n\tEnc.CompressionLevel = compresLvl\n\terr = Enc.Encode(f, img)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (ossDriver *OSSArtifactDriver) Save(path string, outputArtifact *wfv1.Artifact) error {\n\terr := wait.ExponentialBackoff(wait.Backoff{Duration: time.Second * 2, Factor: 2.0, Steps: 5, Jitter: 0.1},\n\t\tfunc() (bool, error) {\n\t\t\tlog.Infof(\"OSS Save path: %s, key: %s\", path, outputArtifact.OSS.Key)\n\t\t\tosscli, err := ossDriver.newOSSClient()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Failed to create new OSS client: %v\", err)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tbucketName := outputArtifact.OSS.Bucket\n\t\t\tbucket, err := osscli.Bucket(bucketName)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tobjectName := outputArtifact.OSS.Key\n\t\t\terr = bucket.PutObjectFromFile(objectName, path)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\treturn err\n}", "func saveFile(savedPath string, res *http.Response) {\n\t// create a file of the given name and in the given path\n\tf, err := os.Create(savedPath)\n\terrCheck(err)\n\tio.Copy(f, res.Body)\n}", "func SavePNGRepresentations(r io.Reader, options []Options) error {\n\n\tif r == nil {\n\t\treturn errors.New(\"Nil reader received in SaveJpegRepresentation\")\n\t}\n\n\t// Read the image data, if we have a jpeg, convert to png?\n\toriginal, _, err := image.Decode(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For each option, save a file\n\tfor _, o := range options {\n\n\t\tfmt.Printf(\"Saving image file - %v\\n\", o)\n\n\t\t// Resize this image given the params - this is always in proportion, NEVER stretched\n\t\t// If Square is true we crop to a square\n\t\tresized, err := ResizeImage(original, o.MaxWidth, o.MaxHeight, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Write out to the desired file path\n\t\tw, err := os.Create(o.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer w.Close()\n\t\terr = png.Encode(w, resized)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}", "func (i *resizedImage) saveToJpegBuffer() ([]byte, error) {\n\timageBuffer, err := vips.SaveToJpegBuffer(i.vipsImage)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn imageBuffer, nil\n}", "func SaveFormFile(req *http.Request, resp http.ResponseWriter, path string) (*os.File, error) {\n\t// grab the file from the request\n\tf, h, err := req.FormFile(\"image\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\t// create the project path\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// save the file\n\tt, err := os.OpenFile(filepath.Join(path, h.Filename), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer t.Close()\n\t// copy the image to the file\n\tif _, err := io.Copy(t, f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}", "func (d *DiskStorage) Save() error {\n\n\tvar file, err = os.OpenFile(d.path, os.O_RDWR, 0644)\n\tif d.isError(err) {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, errWrite := file.WriteString(d.String())\n\treturn errWrite\n}", "func WritePngImage(byteImage ByteImage, pngFile *os.File) (string, error) {\n\t// compute images values\n\timgWidth := byteImage.width\n\timgHeight := byteImage.height\n\t// create image\n\timgRect := image.Rect(0, 0, imgWidth, imgHeight)\n\timg := image.NewGray(imgRect)\n\timg.Pix = byteImage.bytes\n\timg.Stride = imgWidth\n\t// write image\n\terr := png.Encode(pngFile, img)\n\t// if err != nil {\n\t// \tlog.Println(err)\n\t// \tos.Exit(1)\n\t// }\n\treturn pngFile.Name(), err\n}", "func (a *Atlas) SavePNG(filename string) error {\n\n\t// Save that RGBA image to disk.\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tb := bufio.NewWriter(outFile)\n\terr = png.Encode(b, a.Image)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = b.Flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func exportTrackImageCB() {\n\tvar expPath string\n\tfs := gtk.NewFileChooserDialog(\n\t\t\"File for Track Image\",\n\t\twin,\n\t\tgtk.FILE_CHOOSER_ACTION_SAVE, \"_Cancel\", gtk.RESPONSE_CANCEL, \"_Export\", gtk.RESPONSE_ACCEPT)\n\tfs.SetCurrentFolder(settings.DataDir)\n\tff := gtk.NewFileFilter()\n\tff.AddPattern(\"*.png\")\n\tfs.SetFilter(ff)\n\tres := fs.Run()\n\tif res == gtk.RESPONSE_ACCEPT {\n\t\texpPath = fs.GetFilename()\n\t\tif expPath != \"\" {\n\t\t\texp, err := os.Create(expPath)\n\t\t\tif err != nil {\n\t\t\t\tmessageDialog(win, gtk.MESSAGE_INFO, \"Could not create image file.\")\n\t\t\t} else {\n\t\t\t\tdefer exp.Close()\n\t\t\t\tif err := png.Encode(exp, trackChart.backingImage); err != nil {\n\t\t\t\t\tmessageDialog(win, gtk.MESSAGE_INFO, \"Could not write image file.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfs.Destroy()\n}", "func (d deck) saveToFile(fileName string) error{\n\n\t// WriteFile (filename, [] byte, permission)\n\treturn ioutil.WriteFile(fileName, []byte (d.toString()), 0666)\n}", "func (a *ImageApiService) ImageSaveAsPNGFile(ctx _context.Context, imageSaveAsPngParameters ImageSaveAsPngParameters) (*os.File, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageSaveAsPNGFile\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageSaveAsPngParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v *os.File\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Save(filePath string, content []byte) error {\n\tkh, err := KymaHome()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\n\tfilePath = fp.Join(kh, filePath)\n\n\terr = os.MkdirAll(fp.Dir(filePath), 0700)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\n\tif err = ioutil.WriteFile(filePath, content, 0644); err != nil {\n\t\treturn errors.Wrap(err, \"Could not save file\")\n\t}\n\treturn nil\n}", "func Save(obj any, file string) error {\n\tfp, err := os.Create(file)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tbw := bufio.NewWriter(fp)\n\terr = Write(obj, bw)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\terr = bw.Flush()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func SaveFile(name string, v interface{}) error {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := filepath.Join(path, name)\n\terr = ioutil.WriteFile(p, data, 0740)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveAsJPEG(name string, img image.Image, quality int) {\n\tl := new(Legofy)\n\tif name == \"\" {\n\t\tname = l.getNewFileName()\n\t}\n\tf, err := os.Create(name + \".jpg\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tvar opt jpeg.Options\n\tif opt.Quality = 80; quality <= 80 {\n\t\topt.Quality = quality\n\t}\n\t// ok, write out the data into the new JPEG file\n\t// TODO file write should be able to selec\n\n\terr = jpeg.Encode(f, img, &opt)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n}", "func (f *File) Save(path string) (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"File.Save(%s): %w\", path, err)\n\t\t}\n\t}()\n\ttarget, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif ie := target.Close(); ie != nil {\n\t\t\terr = fmt.Errorf(\"write:%+v close:%w\", err, ie)\n\t\t}\n\t}()\n\terr = f.Write(target)\n\treturn\n}", "func SaveScreenshot(filename string) {\n\tC.TCOD_sys_save_screenshot(C.CString(filename))\n}", "func (m *MockImageSaver) SaveImage(arg0 context.Context, arg1 images.SaveOpts) chan interface{} {\n\tret := m.ctrl.Call(m, \"SaveImage\", arg0, arg1)\n\tret0, _ := ret[0].(chan interface{})\n\treturn ret0\n}", "func SaveUploadedFile(file io.Reader, pathAndName string) error {\n\n\t// Check For file Exsistence ;\n\tif _, err := os.Stat(pathAndName); err == nil {\n\t\treturn errors.New(\"File already exsists\")\n\t}\n\n\t// Read BytesArray from io.Reader ;\n\tfileBytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write The File with BytesArray ;\n\tif err := ioutil.WriteFile(pathAndName, fileBytes, 0644); err != nil {\n\t\treturn err\n\t}\n\n\t// Craete Thumbnail ;\n\tgo genThumbnail(pathAndName)\n\n\treturn nil\n\n}", "func Save(path string, v interface{}, opts Options) (err error) {\n\tvar (\n\t\tfile *os.File\n\t\ttmp = path + \".tmp.\" + cmn.GenTie()\n\t)\n\tif file, err = cmn.CreateFile(tmp); err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(tmp)\n\t\t}\n\t}()\n\tif err = Encode(file, v, opts); err != nil {\n\t\treturn\n\t}\n\tif err = file.Close(); err != nil {\n\t\treturn\n\t}\n\terr = os.Rename(tmp, path)\n\treturn\n}", "func (d deck) saveToFile (filename string) error {\n\t\treturn ioutil.WriteFile(filename, []byte (d.toString()), 0666)\n}", "func (s store) Save() {\n\ts.writeToDisk()\n}", "func ExportImage(client *httputil.ClientConn, fingerprintURL string) ([]byte, error) {\n\tbody, err := utils.Do(client, \"GET\", fingerprintURL+\"/export\", nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to export image: %v\", err)\n\t}\n\treturn body, nil\n}", "func SaveFile(fileName string, dir string, data string) (*os.File, error) {\n\tvar file *os.File\n\n\tcwd, err := filepath.Abs(filepath.Dir(\"\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfilePath := cwd + dir\n\t// Check if output directory does not exits. In this case create it.\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\tos.Mkdir(filePath, os.ModePerm)\n\t}\n\t// Create the output file.\n\tfile, err = os.Create(filepath.Join(filePath, fileName))\n\tif isError(err) {\n\t\treturn nil, err\n\t}\n\n\tfile, err = os.OpenFile(filepath.Join(filePath, fileName), os.O_RDWR, 0644)\n\tif isError(err) {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\t_, err = file.WriteString(data)\n\tif isError(err) {\n\t\treturn nil, err\n\t}\n\treturn file, nil\n}", "func (d deck) saveToFile(fileName string) error {\n\treturn ioutil.WriteFile(fileName, []byte(d.toString()), 0776)\n}", "func (i *resizedImage) saveToWebPBuffer() ([]byte, error) {\n\timageBuffer, err := vips.SaveToWebPBuffer(i.vipsImage)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn imageBuffer, nil\n}", "func (t TestRepo) SaveFile(filename, subdir, content string) {\n\td := filepath.Join(t.Workdir(), subdir)\n\terr := os.MkdirAll(d, 0700)\n\tCheckFatal(t.test, err)\n\terr = ioutil.WriteFile(filepath.Join(d, filename), []byte(content), 0644)\n\tCheckFatal(t.test, err)\n}", "func (a *ImageApiService) ImageSaveAsPNG(ctx _context.Context, imageSaveAsPngParameters ImageSaveAsPngParameters) (ImageSaveAsPngResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImageSaveAsPngResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageSaveAsPNG\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageSaveAsPngParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ImageSaveAsPngResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (d *DXF) Save() error {\n\terr := d.drawing.SaveAs(d.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func writeImageWithTemplate(w http.ResponseWriter, img *image.Image) {\n\n\tbuffer := new(bytes.Buffer)\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\n\t\tlog.Fatalln(\"unable to encode image.\")\n\t}\n\n\tstr := base64.StdEncoding.EncodeToString(buffer.Bytes())\n\tif tmpl, err := template.New(\"image\").Parse(ImageTemplate); err != nil {\n\t\tlog.Println(\"unable to parse image template.\")\n\t} else {\n\t\tdata := map[string]interface{}{\"Image\": str}\n\t\tif err = tmpl.Execute(w, data); err != nil {\n\t\t\tlog.Println(\"unable to execute template.\")\n\t\t}\n\t}\n}", "func SavePhoto(name string, username string, path string, date string) *Photo {\n\tdir := packageTools.GetWD()\n\thash := packageTools.HashSHAFile(dir + \"/static\" + path)\n\n\tfmt.Println(\"Hashing \" + name + \" Path: \" + path + \" Hash: \" + hash)\n\n\tcurrentPhotos := *GetAllPhotosByUser(username)\n\n\tif GetPhotoByUserAndHash(&currentPhotos, hash) != nil {\n\t\treturn nil\n\t}\n\n\tphoto := Photo{\n\t\tName: name,\n\t\tPath: path,\n\t\tHash: hash,\n\t\tDate: date,\n\t}\n\n\tcurrentPhotos = append(currentPhotos, photo)\n\n\tsavePhotos(username, &currentPhotos)\n\n\treturn &photo\n}", "func (d deck) saveToFile(filename string) error {\n\t//convert the d deck to single string (toString) and then convert to []byte slice and finally WritesFile create the file\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0666)\n}", "func save(bytes []byte, fh *os.File) error {\n\t_, err := fh.Write(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fh.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d deck) saveTofile(filename string) error {\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0666)\n}", "func (d deck) saveToFile(filename string) error {\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0666) //0666 is a default permission\n}", "func (d deck) saveToFile(filename string) error {\n\treturn ioutil.WriteFile(filename, []byte(d.toString()), 0755)\n}", "func (f *File) Save(name string) error {\n\treturn ioutil.WriteFile(name, []byte(f.String()), 0666)\n}", "func (c *Passward) Save() error {\n\n\tif !util.DirectoryExists(c.Path) {\n\t\tif err := os.MkdirAll(c.Path, 0700); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfile, err := os.Create(c.configPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err := toml.NewEncoder(file).Encode(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}" ]
[ "0.7630419", "0.76008147", "0.73763996", "0.7319533", "0.72648215", "0.7232412", "0.7197126", "0.7176601", "0.7140585", "0.7048283", "0.69071436", "0.6843526", "0.67325836", "0.67032164", "0.66581595", "0.6631153", "0.6620724", "0.66068083", "0.65837497", "0.65563893", "0.65424746", "0.651715", "0.6514465", "0.649107", "0.6474507", "0.6449749", "0.6397979", "0.6397663", "0.6332571", "0.63280565", "0.6318932", "0.629777", "0.62867665", "0.62811655", "0.62396526", "0.6202663", "0.61138064", "0.61107904", "0.6085546", "0.6072351", "0.60520613", "0.6020913", "0.5993267", "0.59808916", "0.59736925", "0.5927796", "0.58908695", "0.5833208", "0.58071977", "0.5806884", "0.5784127", "0.5782691", "0.57728225", "0.5729256", "0.5707925", "0.56704897", "0.56568706", "0.5650115", "0.5629066", "0.56265897", "0.5593746", "0.55932635", "0.5584527", "0.5584147", "0.55796736", "0.5565668", "0.55587023", "0.5557621", "0.553362", "0.55162996", "0.55107456", "0.5479672", "0.5461437", "0.54492843", "0.54461014", "0.54420066", "0.5429837", "0.5426487", "0.5425105", "0.5424165", "0.5423911", "0.5422535", "0.5415806", "0.540989", "0.539483", "0.5384122", "0.53814507", "0.5371089", "0.53703666", "0.5359249", "0.53450835", "0.5343293", "0.53411555", "0.533841", "0.5334793", "0.53296745", "0.53251207", "0.53149617", "0.53100914", "0.52994907" ]
0.8080319
0
Main method that invokes the service and starts it at default port
func main() { service := service.Service{} service.Start("") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tservice.StartWebServer(\"8081\")\n}", "func main() {\n\t//\n\t// Load startup flags\n\t//\n\tflags := cmd.LoadFlags()\n\n\t//\n\t// Load env.\n\t//\n\tif flags.EnvFile != \"\" {\n\t\terr := env.LoadEnvFile(flags.EnvFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\t//\n\t// Select service\n\t//\n\treg := registry.NewRegistryContainer()\n\n\treg.Add(portGateway.ServiceName, portGateway.FactoryMethod)\n\treg.Add(portService.ServiceName, portService.FactoryMethod)\n\n\tserviceFactory, err := reg.Get(flags.Kind)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//\n\t// Create service\n\t//\n\tservice, err := serviceFactory()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//\n\t// Run till the death comes\n\t//\n\tlog.Printf(\"[%s] started serving on '%s'\", flags.Kind, flags.Address)\n\tlog.Fatal(service.Serve(flags.Address))\n}", "func main() {\n\tlog.Info(\"Initialize service...\")\n\n\trouter := httprouter.New()\n\trouter.GET(\"/\", home)\n\n\tlog.Info(\"Service is ready to listen and serve.\")\n\thttp.ListenAndServe(\":8000\", router)\n}", "func main() {\n if len(os.Args) != 2 {\n log.Panic(\"args:\", \"<port>\")\n }\n port := os.Args[1]\n startServer(port)\n}", "func (s *Service) Run(port string) {\n\ts.log.Println(\"Starting...\")\n\tr := s.prepareRouter()\n\n\tif err := http.ListenAndServe(port, r); err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\n\tfmt.Println(\"Starting Restful services...\")\n\tfmt.Println(\"Using port:8080\")\n\thandleRequests()\n}", "func main() {\n\tgodotenv.Load()\n\n\tport := os.Getenv(\"REST_PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\tserver, err := start(port)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\terr = stopServer(server)\n\tif err != nil {\n\t\tlog.Println(\"err:\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", \":9091\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tdao := database.CreateDAO(database.CreateConn())\n\tsvc := service.CreateService(dao)\n\n\tgrpcServer := grpc.NewServer()\n\n\t// attach the Ping service to the server\n\tpb.RegisterDBServer(grpcServer, &svc)\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %s\", err)\n\t}\n}", "func main() {\n\tportNo := os.Args[1]\n\tstartServerMode(portNo)\n}", "func main() {\n\te := godotenv.Load()\n\tif e != nil {\n\t\tfmt.Print(e)\n\t}\n\n\tr := routers.SetupRouter()\n\trouters.MirrorRouter(r)\n\trouters.ProxyRouter(r)\n\n\tport := os.Getenv(\"port\")\n\n\t// For run on requested port\n\tif len(os.Args) > 1 {\n\t\treqPort := os.Args[1]\n\t\tif reqPort != \"\" {\n\t\t\tport = reqPort\n\t\t}\n\t}\n\n\tif port == \"\" {\n\t\tport = \"8080\" //localhost\n\t}\n\ttype Job interface {\n\t\tRun()\n\t}\n\n\tr.Run(\":\" + port)\n}", "func main() {\n\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Println(\"ERROR : \", err)\n\t}\n\tr := Routers.SetupRouter()\n\n\tport := os.Getenv(\"port\")\n\n\t// For run on requested port\n\tif len(os.Args) > 1 {\n\t\treqPort := os.Args[1]\n\t\tif reqPort != \"\" {\n\t\t\tport = reqPort\n\t\t}\n\t}\n\n\tif port == \"\" {\n\t\tport = \"8080\" //localhost\n\t}\n\ttype Job interface {\n\t\tRun()\n\t}\n\n\terr = r.Run(\":\" + port)\n\tif err != nil {\n\t\tlog.Println(\"ERROR\")\n\t}\n\n\n\n}", "func main() {\n\ta := App{}\n\ta.Initialize()\n\ta.Run(\":8000\")\n}", "func main() {\r\n\tbind := fmt.Sprintf(\"%s:%s\", getIP(), getPort())\r\n\tlog.Println(\"Listening on\", bind)\r\n\r\n\terr := http.ListenAndServe(bind, http.HandlerFunc(mainHandle))\r\n\tif err != nil {\r\n\t\tpanic(\"ListenAndServe: \" + err.Error())\r\n\t}\r\n}", "func main() {\n\t// Get api routes\n\trouter := Router.Router()\n\t// Get Port to listen and serve\n\tPORT := os.Getenv(\"PORT\")\n\t// Check port variable\n\tif PORT == \"\" {\n\t\t// Set port variable\n\t\tPORT = \"5000\"\n\t}\n\t// Serve the api\n\tlog.Fatal(http.ListenAndServe(\":\" + PORT, router))\n}", "func main() {\n\tbindTo := flag.String(\n\t\t\"l\", \"0.0.0.0:999\", \"interface and port to listen at\")\n\tflag.Parse()\n\trunServer(*bindTo)\n}", "func main() {\n\tcalculix := serverCalculix.NewCalculix()\n\terr := rpc.Register(calculix)\n\tif err != nil {\n\t\tfmt.Println(\"Cannot register the calculix\")\n\t\treturn\n\t}\n\trpc.HandleHTTP()\n\tl, e := net.Listen(\"tcp\", \":1234\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\terr = http.Serve(l, nil)\n\tif err != nil {\n\t\tfmt.Println(\"Cannot serve the calculix\")\n\t\treturn\n\t}\n}", "func (s *Service) Run(host, port string) error {\n\t// let's gooooo\n\ts.l.Infow(\"spinning up core service\",\n\t\t\"core.host\", host,\n\t\t\"core.port\", port)\n\tlistener, err := net.Listen(\"tcp\", host+\":\"+port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = s.grpc.Serve(listener); err != nil {\n\t\ts.l.Errorf(\"error encountered - service stopped\",\n\t\t\t\"error\", err)\n\t\treturn err\n\t}\n\n\t// report shutdown\n\ts.l.Info(\"service shut down\")\n\treturn nil\n}", "func main() {\n\tport, exists := os.LookupEnv(\"PORT\")\n\tif !exists {\n\t\tport = \"2001\"\n\t}\n\tfmt.Println(\"Running on port \" + port)\n\thttp.HandleFunc(\"/\", RelayServer)\n\thttp.ListenAndServe(\":\"+port, nil)\n}", "func Run(port int) {\n\n\trunStartupHooks()\n\n}", "func main() {\n\tvar (\n\t\trepository = storage.NewInMemory()\n\t\tportServer = service.NewPortServer(repository)\n\t)\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot start the server: %s\", err)\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\n\tproto.RegisterStorageServer(grpcServer, portServer)\n\n\tlog.Printf(\"starting GRPC server on %s\", listener.Addr().String())\n\tif err := grpcServer.Serve(listener); err != nil {\n\t\tlog.Fatalf(\"failed to start the server: %s\", err)\n\t}\n}", "func main() {\n\tctx := context.Background()\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\t// New server multiplexer\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\n\t// Our gRPC host address\n\tconn := os.Getenv(\"SERVICE_ADDRESS\")\n\tapiAddress := os.Getenv(\"API_ADDRESS\")\n\n\tlog.Printf(\"Connecting to gRPC server on: %s\\n\", conn)\n\tlog.Printf(\"Starting API on: %s\\n\", apiAddress)\n\n\t// Register the handler to an endpoint\n\terr := gw.RegisterUserServiceHandlerFromEndpoint(ctx, mux, conn, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Return a server instance\n\thttp.ListenAndServe(apiAddress, mux)\n}", "func Start(port string) {\n\tif port == \"\" {\n\t\tport = portDefault\n\t}\n\tlog.Printf(\"Starting new server on port %v.\\n\", port)\n\n\tport = fmt.Sprintf(\":%v\", port)\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\ts := grpc.NewServer()\n\tproto.RegisterSumServiceServer(s, &server{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func main() {\n\t//init()\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"MISSING\"\n\t}\n\n\tinnerPort := os.Getenv(\"BACKEND_PORT\")\n\tif innerPort == \"\" {\n\t\tlog.Printf(\"Running on %s:5001\", hostname)\n\t\tlog.Fatal(http.ListenAndServe(\":5001\", nil))\n\t} else {\n\t\tlog.Printf(\"Running on %s:%s\", hostname, innerPort)\n\t\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%s\", innerPort), nil))\n\t}\n}", "func main() {\n\tif err := http.ListenAndServe(port, handler()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tif len(os.Args) != 2 {\n\t\tlog.Fatal(\"Usage: ./server-go [server port]\")\n\t}\n\tserver_port := os.Args[1]\n\tserver(server_port)\n}", "func main(){\n\tr := ctrl.HttpRouter()\n\tr.Run(\":1234\")\n}", "func main() {\n\thttpPort := 8080\n\tserver := api.NewServer()\n\tlog.Printf(\"Server running on Port: %v\\n\", httpPort)\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", httpPort), logRequest(server))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\tForceColors: true,\n\t\tFullTimestamp: true,\n\t})\n\tmlog := logrus.WithFields(logrus.Fields{\n\t\t\"component\": componentName,\n\t\t\"version\": env.Version(),\n\t})\n\n\tgrpc_logrus.ReplaceGrpcLogger(mlog.WithField(\"component\", componentName+\"_grpc\"))\n\tmlog.Infof(\"Starting %s\", componentName)\n\n\tgrpcServer, err := createGRPCServer(mlog)\n\tif err != nil {\n\t\tmlog.WithError(err).Fatal(\"failed to create grpc server\")\n\t}\n\t// Start go routines\n\tgo handleExitSignals(grpcServer, mlog)\n\tserveGRPC(env.ServiceAddr(), grpcServer, mlog)\n}", "func main() {\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"9280\"\n\t}\n\tlis, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tinitOTel(context.Background(), \"echo\")\n\n\terr = Run(lis)\n\tif err != nil {\n\t\tfmt.Println(\"Error \", err)\n\t}\n\tgo http.ListenAndServe(\"127.0.0.1:9281\", http.DefaultServeMux)\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\t<-sigs\n\n}", "func main() {\n\tws := new(restful.WebService)\n\tws.Route(ws.GET(\"/hello\").To(hello))\n\trestful.Add(ws)\n\tlog.Println(\"server start in 8082\")\n\tlog.Fatal(http.ListenAndServe(\":8082\", nil))\n}", "func main() {\n\tif runtime.GOOS != \"linux\" {\n\t\tfmt.Println(aurora.Red(\"Sorry mate, this is a Linux app\"))\n\t\treturn\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\te.Debug = true\n\te.Server.ReadTimeout = 1 * time.Minute\n\te.Server.WriteTimeout = 1 * time.Minute\n\n\tport := \"10591\"\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tport = os.Getenv(\"PORT\")\n\t}\n\n\t// Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\te.Use(middleware.CORS())\n\n\te.GET(\"info\", getInfo)\n\te.POST(\"upgrade\", doUpgrade)\n\n\t// Start the service\n\te.Logger.Fatal(e.Start(\":\" + port))\n}", "func main() {\n\troute := initiateRoutes()\n\n\troute.Run(\":3004\")\n\n}", "func (p *Service) Run(port string, certChain *dapr_credentials.CertChain) {\n\tvar err error\n\tp.serverListener, err = net.Listen(\"tcp\", fmt.Sprintf(\":%s\", port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\topts, err := dapr_credentials.GetServerOptions(certChain)\n\tif err != nil {\n\t\tlog.Fatalf(\"error creating gRPC options: %s\", err)\n\t}\n\tp.grpcServer = grpc.NewServer(opts...)\n\tplacementv1pb.RegisterPlacementServer(p.grpcServer, p)\n\n\tif err := p.grpcServer.Serve(p.serverListener); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func main() {\n\n\tlis ,err := net.Listen(\"tcp\",fmt.Sprintf(\":%d\", 1368))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tserver := grpc.NewServer()\n\trpc.RegisterUserServiceServer(server, &service.UserService{})\n\n\terr = server.Serve(lis)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tvar addr string\n\tflag.StringVar(&addr, \"e\", \":4040\", \"service address endpoint\")\n\tflag.Parse()\n\n\t// create local addr for socket\n\tladdr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\t// announce service using ListenTCP\n\t// which a TCPListener.\n\tl, err := net.ListenTCP(\"tcp\", laddr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer l.Close()\n\tfmt.Println(\"listening at (tcp)\", laddr.String())\n\n\t// req/response loop\n\tfor {\n\t\t// use TCPListener to block and wait for TCP\n\t\t// connection request using AcceptTCP which creates a TCPConn\n\t\tconn, err := l.AcceptTCP()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"failed to accept conn:\", err)\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(\"connected to: \", conn.RemoteAddr())\n\n\t\tgo handleConnection(conn)\n\t}\n}", "func main() {\n\ts := master.New()\n\tif err := s.Run(port); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tserver.New().Start()\n}", "func main() {\n\n\tvar listenPort = flag.Int(\"lp\", 8081, \"Thrift Listening port\")\n\tvar listenIp = flag.String(\"li\", \"0.0.0.0\", \"Listening interface\")\n\tvar backendPort = flag.Int(\"bp\", 4001, \"Etcd Service port\")\n\tvar backendIp = flag.String(\"bi\", \"127.0.0.1\", \"Etcd Service addr\")\n\tvar logDest = flag.String(\"log\", \"-\", \"Logging destination file, '-' for STDOUT\")\n\tvar debug = flag.Bool(\"debug\", false, \"enable debug\")\n\tflag.Parse()\n\n\tlogger = common.GetLogger(*logDest, *debug)\n\tlogger.Print(\"Starting Backend Processor\")\n\tlogger.Printf(\"Thrift Listening: %s:%d\\t\\tEtcd Service: %s:%d\\n\", *listenIp, *listenPort, *backendIp, *backendPort)\n\n\terr := runServer(listenIp, listenPort, backendIp, backendPort, debug)\n\tif err != nil {\n\t\tlogger.Printf(\"Failed to start Thrift service: %s\\n\", err)\n\t}\n}", "func (s *Server) Run(addr string) {\n\tfmt.Println(\"Listening to port 8080\")\n\tlog.Fatal(http.ListenAndServe(addr, s.Router))\n}", "func main() {\n\tfmt.Println(\"APPLICATION BEGIN\")\n\twebserver := new(service.Webserver)\n\tregisterConfig()\n\tregisterErrors()\n\tregisterAllApis()\n\tregisterInitFunc()\n\toverrideConfByEnvVariables()\n\twebserver.Start()\n}", "func main() {\n\tflag.BoolVar(&debug, \"debug\", false, \"Enable debug output\")\n\tflag.StringVar(&host, \"host\", \"127.0.0.1\", \"Host to listen on\")\n\tflag.StringVar(&port, \"port\", \"5000\", \"Port to listen on\")\n\tflag.Parse()\n\n\t// create the host:port string for use\n\tlistenAddress := fmt.Sprintf(\"%s:%s\", host, port)\n\tif debug {\n\t\tlog.Printf(\"Listening on %s\", listenAddress)\n\t}\n\n\t// Map /config to our configHandler and wrap it in the log middleware\n\thttp.Handle(\"/config/\", logMiddleware(http.HandlerFunc(configHandler)))\n\n\t// Run forever on all interfaces on port 5000\n\tlog.Fatal(http.ListenAndServe(listenAddress, nil))\n}", "func (ms *MicroService) Start() {\n \tms.StartOnPort(8080)\n}", "func main() {\n\tserver.StartUp(false)\n}", "func main() {\n\t// create a listener on TCP port 7777\n\tlis, err := net.Listen(\"tcp\", \":7777\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\t// create a server instance\n\ts := api.Server{}\n\n\t// create the TLS creds\n\tcreds, err := credentials.NewServerTLSFromFile(\"cert/server.crt\", \"cert/server.key\")\n\tif err != nil {\n\t\tlog.Fatalf(\"could not load TLS keys: %s\", err)\n\t}\n\n\t// add credentials to the gRPC options\n\topts := []grpc.ServerOption{grpc.Creds(creds)}\n\n\t// create a gRPC server object\n\tgrpcServer := grpc.NewServer(opts...)\n\n\t// attach the Ping service to the server\n\tapi.RegisterPingServer(grpcServer, &s)\n\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func main() {\n\tport := os.Getenv(\"PORT\")\n\tlog.Printf(\"Starting a device model grpc service in port \" + port)\n\tlis, err := net.Listen(\"tcp\", \":\"+port)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"faild to listen: %v\", err)\n\t}\n\tctn, err := registry.NewContainer()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to build container: %v\", err)\n\t}\n\n\tserver := grpc.NewServer()\n\t// Start the device model service rpc\n\trpc.Apply(server, ctn)\n\n\tgo func() {\n\t\tlog.Printf(\"start grpc server port: %s\", port)\n\t\tserver.Serve(lis)\n\t}()\n\n\tquit := make(chan os.Signal)\n\tsignal.Notify(quit, os.Interrupt)\n\t<-quit\n\tlog.Println(\"stopping grpc server...\")\n\tserver.GracefulStop()\n\tctn.Clean()\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on port [%s]: %v\", port, err)\n\t}\n\ts := grpc.NewServer()\n\tpb.RegisterColorGeneratorServer(s, &server{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"Failed to start the server: %v\", err)\n\t}\n}", "func main() {\n\tws := new(restful.WebService)\n\tws.Route(ws.GET(\"/run\").To(hello))\n\trestful.Add(ws)\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func main() {\n\tlog.Print(\"Starting PortDomainService...\\n\")\n\tparams, er := models.NewEnvParams(true)\n\tif er != nil {\n\t\tlog.Fatalf(\"Error: Environment parameters not set: %v\\n\", er)\n\t\treturn\n\t}\n\tgrpcAddr := params.GrpcAddr\n\tlis, err := net.Listen(\"tcp\", grpcAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error listening to port %s: %v\", grpcAddr, err)\n\t}\n\tdefer lis.Close()\n\t_, cancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer()\n\tportDomainService := service.NewPortDomainService()\n\n\tgo func() {\n\t\tgorpc.RegisterPortDomainServer(grpcServer, portDomainService)\n\t\tgrpcServer.Serve(lis)\n\t}()\n\n\tsignalChan := make(chan os.Signal, 1)\n\n\tsignal.Notify(\n\t\tsignalChan,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGQUIT,\n\t)\n\n\t<-signalChan\n\tlog.Print(\"Gracefully shutting down...\\n\")\n\n\tgo func() {\n\t\t<-signalChan\n\t\tlog.Fatal(\"Terminating...\\n\")\n\t}()\n\n\tgrpcServer.GracefulStop()\n\tcancel()\n\n\tdefer os.Exit(0)\n\treturn\n}", "func main() {\n\n\t// Calls startup logic\n\tcommon.StartUp()\n\t// Get the mux router object\n\trouter := routers.InitRoutes()\n\n\tserver := &http.Server{\n\t\tAddr: common.AppConfig.Server,\n\t\tHandler: router,\n\t}\n\tlog.Println(\"Listening [products]...\")\n\tserver.ListenAndServe()\n}", "func main() {\n\tlog.Println(\"main : Started\")\n\n\t// Check the environment for a configured port value.\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"3000\"\n\t}\n\n\t// Create this goroutine to run the web server.\n\tgo func() {\n\t\tlog.Println(\"listener : Started : Listening on: http://localhost:\" + port)\n\t\thttp.ListenAndServe(\":\"+port, routes.API())\n\t}()\n\n\t// Listen for an interrupt signal from the OS.\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, os.Interrupt)\n\t<-sigChan\n\n\tlog.Println(\"main : Completed\")\n}", "func main() {\n\thttp.ListenAndServe(\"127.0.0.1:8080\", NewServer())\n}", "func (s *SamFSServer) Run() error {\n\tlis, err := net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\tglog.Fatalf(\"falied to listen on port :: %s(err=%s)\", s.port, err.Error())\n\t\treturn err\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\ts.sessionID = rand.Int63()\n\tglog.Infof(\"starting new server with sessionID %d\", s.sessionID)\n\n\tgs := grpc.NewServer()\n\tpb.RegisterNFSServer(gs, s)\n\ts.grpcServer = gs\n\treturn gs.Serve(lis)\n}", "func (s *Service) Run() error {\n s.pipeline = s.pipeline.Add(HandlerFunc(s.routeRequest))\n \n server := &http.Server{\n Addr: s.port,\n Handler: s,\n ReadTimeout: s.readTimeout,\n WriteTimeout: s.writeTimeout,\n IdleTimeout: s.idleTimeout,\n }\n \n alt.Debugf(\"%s: Listening on %v\", s.name, s.port)\n return server.ListenAndServe()\n}", "func RunServer(port int) {}", "func main() {\n\tconst port = 8090\n\tfmt.Printf(\"Listening on port: %d\\n\", port)\n\thttp.HandleFunc(\"/\", requestHandler)\n\thttp.ListenAndServe(fmt.Sprintf(\":%d\", port), nil)\n}", "func main() {\n\thttp.HandleFunc(\"/\", handlers.Home)\n\thttp.HandleFunc(\"/about\", handlers.About)\n\n\tfmt.Printf(\"Staring application on port %s\", portNumber)\n\t_ = http.ListenAndServe(portNumber, nil)\n}", "func Run(ctx context.Context, port string) struct{} {\n\n\t//The server to get up\n\tli, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Server stopped: %v\", err)\n\t}\n\n\t//Passing the server to grpc\n\ts := &Server{}\n\tgrpcServer := grpc.NewServer()\n\tsubscribe.RegisterSubscribeServiceServer(grpcServer, s)\n\tgrpcServer.Serve(li)\n\n\tfmt.Printf(\"Server up on port: %v\\n\", err)\n\treturn <-ctx.Done()\n}", "func mainExample() {\n\tfmt.Printf(\"webserv main running.\\n\")\n\tw := NewWebServer(\"127.0.0.1:7708\", nil)\n\tw.Start()\n\tselect {}\n\t// ...\n\tw.Stop()\n}", "func (s * Service)Start(port string) {\n\tr := chi.NewRouter()\n\n\tr.Use(middleware.Logger)\n\tr.Use(middleware.Timeout(5 * time.Second))\n\n\trpc := rpc.RPC{\n\t\tApp: &app.App{},\n\t}\n\tif len(port) == 0 {\n\t\t// default port 3000\n\t\tport = \"3000\"\n\t}\n\tr.Post(\"/generate_pricing\", rpc.GeneratePricing)\n\tr.Get(\"/generate_pricing\", rpc.GeneratePricingConfig)\n\ts.ListenAndServe(\":\"+port, r)\n}", "func (s *Rest) Run(port int) {\n\tlog.Printf(\"[INFO] activate rest server on port %d\", port)\n\n\tif len(s.Authenticator.Admins) > 0 {\n\t\tlog.Printf(\"[DEBUG] admins %+v\", s.Authenticator.Admins)\n\t}\n\n\trouter := s.routes()\n\n\ts.lock.Lock()\n\ts.httpServer = &http.Server{\n\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\tHandler: router,\n\t\tReadHeaderTimeout: 5 * time.Second,\n\t\tWriteTimeout: 5 * time.Second,\n\t\tIdleTimeout: 30 * time.Second,\n\t}\n\ts.lock.Unlock()\n\n\terr := s.httpServer.ListenAndServe()\n\tlog.Printf(\"[WARN] http server terminated, %s\", err)\n}", "func main() {\n\n\t// Initialize Logger instance\n\tlog, err := logger.New(serviceName, logger.Options{\n\t\tFormat: logger.SyslogLogFormat,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\terr = os.Setenv(\"KUBECONFIG\", path.Join(\n\t\tconfig.KubeConfig[configprovider.FilePath],\n\t\tfmt.Sprintf(\"%s.%s\", config.KubeConfig[configprovider.FileName], config.KubeConfig[configprovider.FileType])),\n\t)\n\tif err != nil {\n\t\t// Fail silently\n\t\tlog.Warn(err)\n\t}\n\n\t// Initialize application specific configs and dependencies\n\t// App and request config\n\tcfg, err := config.New(configprovider.ViperKey)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tservice := &grpc.Service{}\n\terr = cfg.GetObject(adapter.ServerKey, service)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tkubeconfigHandler, err := config.NewKubeconfigBuilder(configprovider.ViperKey)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\t// // Initialize Tracing instance\n\t// tracer, err := tracing.New(service.Name, service.TraceURL)\n\t// if err != nil {\n\t// \tlog.Err(\"Tracing Init Failed\", err.Error())\n\t// \tos.Exit(1)\n\t// }\n\n\t// Initialize Handler intance\n\thandler := nginx.New(cfg, log, kubeconfigHandler)\n\thandler = adapter.AddLogger(log, handler)\n\n\tservice.Handler = handler\n\tservice.Channel = make(chan interface{}, 10)\n\tservice.StartedAt = time.Now()\n\n\tgo registerCapabilities(service.Port, log) //Registering static capabilities\n\tgo registerDynamicCapabilities(service.Port, log) //Registering latest capabilities periodically\n\n\t// Server Initialization\n\tlog.Info(\"Adapter Listening at port: \", service.Port)\n\terr = grpc.Start(service, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tfmt.Println(\"################################\")\n\tfmt.Println(\"#### Hello from MyAppStatus ####\")\n\tfmt.Println(\"################################\")\n\n\tapp.StartServer()\n}", "func main() {\n\tflag.Parse()\n\tlog := logrus.New()\n\n\tif *Debug {\n\t\tlog.Level = logrus.DebugLevel\n\t\tlog.Debug(\"Debug mode is on.\")\n\t} else {\n\t\tlog.Level = logrus.InfoLevel\n\t}\n\n\thost := os.Getenv(\"HOST\")\n\tport := os.Getenv(\"PORT\")\n\taddr := host + \":\" + port\n\n\tlog.Info(\"Start service on \" + addr + \"...\")\n\n\tdb, err := utils.StartupDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trouter := httprouter.New()\n\tmw := middleware.New(db, log)\n\n\trouter.GET(\"/api/v1/books\", mw.SearchBooks)\n\trouter.GET(\"/api/v1/books/:id\", mw.SingleBook)\n\n\trouter.GET(\"/api/v1/categories\", mw.SearchCategories)\n\n\trouter.GET(\"/api/v1/library\", mw.Authorize(mw.Library))\n\trouter.POST(\"/api/v1/library\", mw.Authorize(mw.AddToLibrary))\n\trouter.DELETE(\"/api/v1/library\", mw.Authorize(mw.DeleteFromLibrary))\n\n\tlog.Info(\"Service is waiting for requests...\")\n\n\terr = http.ListenAndServe(addr, router)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\r\n\tconfig.InitViper()\r\n\tlogger.Logger().Printf(\"notebook server, startPort: %s\", os.Getenv(\"START_PORT\"))\r\n\tlogger.Logger().Printf(\"notebook server, endPort: %s\", os.Getenv(\"END_PORT\"))\r\n\r\n\tswaggerSpec, err := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON)\r\n\tif err != nil {\r\n\t\tlogger.Logger().Fatalln(err)\r\n\t}\r\n\r\n\tapi := operations.NewJupyterServerAPI(swaggerSpec)\r\n\tserver := restapi.NewServer(api)\r\n\tdefer server.Shutdown()\r\n\r\n\tserver.Port = viper.GetInt(config.PortKey)\r\n\tserver.ConfigureAPI()\r\n\r\n\tmux := http.NewServeMux()\r\n\tmux.Handle(\"/\", server.GetHandler())\r\n\tmux.HandleFunc(\"/health\", restapi.GetHealth)\r\n\r\n\taddress := fmt.Sprintf(\":%d\", server.Port)\r\n\r\n\tlogger.Logger().Printf(\"Jupyter Notebook Service REST API v1 serving on %s\", address)\r\n\r\n\terr = graceful.RunWithErr(address, 10*time.Second, mux)\r\n\tif err != nil {\r\n\t\tlogger.Logger().Fatalln(err)\r\n\t}\r\n}", "func main() {\n\tfmt.Println(\"Hello server\")\n\n\tlis, err := net.Listen(\"tcp\", \"0.0.0.0:50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Faild to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\thellopb.RegisterHelloServiceServer(s, &server{})\n\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"Failed to serve: %v\", err)\n\t}\n\n}", "func main() {\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tflag.Parse()\n\n\trestConfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tc := service.New(restConfig)\n\tc.Run(genericapiserver.SetupSignalContext(), 1)\n}", "func main() {\n\t// get environment variables\n\tport := os.Getenv(portEnv)\n\t// default for port\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\tlog.Print(\"[Info][Main] Creating server...\")\n\ts, err := sessions.NewServer(\":\"+port, os.Getenv(redisAddressEnv),\n\t\tos.Getenv(gameServerImageEnv), deserialiseEnvMap(os.Getenv(gameNodeSelectorEnv)),\n\t\tos.Getenv(cpuLimitEnv))\n\n\tif err != nil {\n\t\tlog.Fatalf(\"[Error][Main] %+v\", err)\n\t}\n\n\tif err := s.Start(); err != nil {\n\t\tlog.Fatalf(\"[Error][Main] %+v\", err)\n\t}\n}", "func Start(e *echo.Echo) {\n Connect()\n e.Logger.Fatal(e.Start(\":\" + os.Getenv(\"PORT\")))\n}", "func (a *App) Run() {\n\tlog := a.log\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", a.host, a.port))\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tlog.Infof(\"events gateway listening on %s:%d\", a.host, a.port)\n\n\tvar opts []grpc.ServerOption\n\n\totelPropagator := otelgrpc.WithPropagators(otel.GetTextMapPropagator())\n\totelTracerProvider := otelgrpc.WithTracerProvider(otel.GetTracerProvider())\n\n\topts = append(opts, grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(\n\t\ta.metricsReporterInterceptor,\n\t\totelgrpc.UnaryServerInterceptor(otelTracerProvider, otelPropagator),\n\t)))\n\topts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{\n\t\tMaxConnectionIdle: a.config.GetDuration(\"server.maxConnectionIdle\"),\n\t\tMaxConnectionAge: a.config.GetDuration(\"server.maxConnectionAge\"),\n\t\tMaxConnectionAgeGrace: a.config.GetDuration(\"server.maxConnectionAgeGrace\"),\n\t\tTime: a.config.GetDuration(\"server.Time\"),\n\t\tTimeout: a.config.GetDuration(\"server.Timeout\"),\n\t}))\n\ta.grpcServer = grpc.NewServer(opts...)\n\n\tpb.RegisterGRPCForwarderServer(a.grpcServer, a.Server)\n\tif err := a.grpcServer.Serve(listener); err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n}", "func StartApplicatin() {\n\tmapUrls()\n\trouter.Run(\":8080\")\n}", "func (s *Service) Run() {\n\tlog.Printf(\"[Info] todolist service listen on %s...\\n\", s.httpServer.Addr)\n\tlog.Fatal(\"[Fatal]\", s.httpServer.ListenAndServe())\n}", "func main() {\n\n\t// db, err := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n\t// if err != nil {\n\t// log.Fatal(err)\n\t// }\n\n\thttp.HandleFunc(\"/\", hello)\n\tfmt.Println(\"listening... on port: \" + os.Getenv(\"PORT\"))\n\t// fmt.Println(\"listening...\")\n\terr := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n\t// err := http.ListenAndServe(\":\"+PORT, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func main() {\n\n\tconfigFile := flag.String(\"config\", \"config/config.yaml\", \"configuration file\")\n\t// debug := flag.Bool(\"debug\", false, \"enable debug mode\")\n\tflag.Parse()\n\n\t// Load global configuration from file\n\terr := cfg.loadConfig(*configFile)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"ConfigFile\": *configFile,\n\t\t\t\"Error\": err,\n\t\t}).Fatal(\"Unable to read configuration file\")\n\t}\n\n\tr := setupRouter()\n\n\t// Check for PORT environment variable config override.\n\tp := cfg.Server.Port\n\tif s := os.Getenv(\"PORT\"); len(s) > 0 {\n\t\tp, _ = strconv.Atoi(s)\n\t}\n\n\t// TODO fix path for logrus. Using fmt temporarily\n\t// log.WithFields(log.Fields{\n\t// \t\"Address\": cfg.Server.Address,\n\t// \t\"Port\": p,\n\t// }).Debug(\"Starting HTTP server\")\n\n\tfmt.Println(\"Starting HTTP Server\")\n\n\t// Listen and Serve at server address and port specified in config file\n\tr.Run(fmt.Sprintf(\"%s:%d\", cfg.Server.Address, p))\n}", "func main() {\n\tname := flag.String(\"name\", \"echo\", \"server name\")\n\tport := flag.String(\"port\", \"3000\", \"server port\")\n\tflag.Parse()\n\n\t// Echo instance\n\te := echo.New()\n\n\t// Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\t// Route => handler\n\te.GET(\"/\", func(c echo.Context) error {\n\t\treturn c.HTML(http.StatusOK, fmt.Sprintf(\"<div style='font-size: 8em;'>Hello from upstream server %s!</div>\", *name))\n\t})\n\te.GET(\"/alive\", func(c echo.Context) error {\n\t\tdata := map[string]interface{}{\n\t\t\t\"alive\": true,\n\t\t\t\"hostname\": \"localhost:\" + *port,\n\t\t\t\"serviceName\": *name,\n\t\t\t\"num_cpu\": runtime.NumCPU(),\n\t\t\t\"num_goroutine\": runtime.NumGoroutine(),\n\t\t\t\"go_version\": runtime.Version(),\n\t\t\t\"build_date\": Buildstamp,\n\t\t\t\"commit\": Commit,\n\t\t\t\"startup_time\": startupTime,\n\t\t}\n\t\treturn c.JSON(http.StatusOK, data)\n\t})\n\n\t// Start server\n\te.Logger.Fatal(e.Start(fmt.Sprintf(\":%s\", *port)))\n}", "func main() {\n\ta := App{}\n\t//\ta.Initialize(\"user\", \"password\", \"db\", \"db_mysql\", 3306)\n\ta.Initialize(\n\t\tos.Getenv(\"DB_USER\"),\n\t\tos.Getenv(\"DB_PASSWORD\"),\n\t\tos.Getenv(\"DB_NAME\"),\n\t\tos.Getenv(\"DB_HOST\"),\n\t\t3306)\n\n\ta.Run(\":8081\")\n}", "func main() {\n\n\tlog.Printf(\"Server started\")\n\n\trouter := sw.NewRouter()\n\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"5000\"\n\t}\n\n\theadersOk := handlers.AllowedHeaders([]string{\"X-Requested-With\", \"Content-Type\"})\n\toriginsOk := handlers.AllowedOrigins([]string{\"*\"})\n\tmethodsOk := handlers.AllowedMethods([]string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"OPTIONS\"})\n\n\tlog.Fatal(http.ListenAndServe(\":\"+port, handlers.CORS(originsOk, headersOk, methodsOk)(router)))\n}", "func run() error {\n\tport := os.Getenv(\"PORT\")\n\tdbURI := os.Getenv(\"DATABASE_URI\")\n\n\t// conn -> repo\n\tr, err := NewRepo(dbURI)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer r.Close()\n\n\t// repo -> service\n\tservice := NewService(r)\n\n\treadTimeoutSecondsCount, _ := strconv.Atoi(os.Getenv(\"SERVER_READ_TIMEOUT\"))\n\t// fiber initialize\n\tapp := fiber.New(fiber.Config{\n\t\tReadTimeout: time.Second * time.Duration(readTimeoutSecondsCount),\n\t})\n\n\tif !IsProduction() {\n\t\tapp.Use(logger.New())\n\t\tapp.Use(cors.New())\n\t}\n\n\t// service -> routes\n\tRoutes(app, service)\n\treturn app.Listen(fmt.Sprintf(\":%s\", port))\n}", "func main() {\n\tflag.Parse()\n\n\tproxy := launcher.NewProxy()\n\tif !*quiet {\n\t\tproxy.Logger = os.Stdout\n\t}\n\n\tl, err := net.Listen(\"tcp\", *addr)\n\tif err != nil {\n\t\tutils.E(err)\n\t}\n\n\tfmt.Println(\"Remote control url is\", \"ws://\"+l.Addr().String())\n\n\tsrv := &http.Server{Handler: proxy}\n\tutils.E(srv.Serve(l))\n}", "func main() {\n\t// Uncomment the following lines to customize the chatbot\n\t// chatbot.WelcomeMessage = \"What's your name?\"\n\t// chatbot.ProcessFunc(chatbotProcess)\n\n\t// Use the PORT environment variable\n\tfmt.Println(\"Hello World \")\n}", "func (a *App) Run() {\n\taddr := fmt.Sprintf(\":%d\", a.getPort())\n\n\ta.Logger.Info(\"starting application\", logging.DataFields{\"port\": addr})\n\terr := http.ListenAndServe(addr,a.router)\n\tif err != nil {\n\t\ta.Logger.Error(\"An error occurred starting the server. Going to call exit\", logging.DataFields{\"Error\": err.Error()})\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tc := dig.New()\n\n\t_ = c.Provide(config.New)\n\n\t_ = c.Provide(logger.New)\n\n\t_ = c.Provide(func(cfg *config.Config) (statuspb.GrpcStarterClient, error) {\n\t\tconn, err := grpc.Dial(cfg.GRPCStarterAddress, grpc.WithInsecure())\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t// defer conn.Close()\n\t\treturn statuspb.NewGrpcStarterClient(conn), nil\n\t})\n\n\t_ = c.Provide(handlers.New)\n\t_ = c.Provide(router.New)\n\n\terr := c.Invoke(func(cfg *config.Config, r router.Router, l *zap.SugaredLogger) error {\n\t\tdefer l.Sync()\n\t\treturn r.Serve(cfg.Port)\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn\n}", "func main() {\n\n\tvar logger *simple.Logger\n\n\tif os.Getenv(\"LOG_LEVEL\") == \"\" {\n\t\tlogger = &simple.Logger{Level: \"info\"}\n\t} else {\n\t\tlogger = &simple.Logger{Level: os.Getenv(\"LOG_LEVEL\")}\n\t}\n\terr := validator.ValidateEnvars(logger)\n\tif err != nil {\n\t\tos.Exit(-1)\n\t}\n\n\t// setup our client connectors (message producer)\n\tconn := connectors.NewClientConnectors(logger)\n\n\t// call the start server function\n\tlogger.Info(\"Starting server on port \" + os.Getenv(\"SERVER_PORT\"))\n\tstartHttpServer(conn)\n}", "func main() {\n\tfmt.Println(\"server is up and running!!\")\n\truntime.GOMAXPROCS(4)\n\n\tapp := gin.Default()\n\n\tsearch.RouterMain(app)\n\n\terr := app.Run(\"0.0.0.0:5000\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"server got fired!!!!\")\n}", "func main() {\n\tconfig := types.SetupConfig()\n\tlog.Printf(\"main.SetupConfig: %#v\\n\", config)\n\n\t/***** Start three GreeterServers(with one of them to be the slowServer). *****/\n\tgrpcAddress := strings.Split(config.GrpcAddress, \",\")\n\tfor i := 0; i < 3; i++ {\n\t\tlis, err := net.Listen(\"tcp\", grpcAddress[i])\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"main.Listen: %v\", err)\n\t\t}\n\t\tdefer lis.Close()\n\t\ts := grpc.NewServer()\n\t\tpb.RegisterPortsDbServer(s, &server{})\n\t\tgo s.Serve(lis)\n\t}\n\n\t/***** Wait for user exiting the program *****/\n\tselect {}\n}", "func (s *Service) Run() *http.Server {\n\t// Init address.\n\taddr := net.JoinHostPort(\"\", GetExplorerPort(s.Port))\n\n\ts.router = mux.NewRouter()\n\n\t// Set up router for addresses.\n\t// Fetch addresses request, accepts parameter size: how much addresses to read,\n\t// parameter prefix: from which address prefix start\n\ts.router.Path(\"/addresses\").Queries(\"size\", \"{[0-9]*?}\", \"prefix\", \"{[a-zA-Z0-9]*?}\").HandlerFunc(s.GetAddresses).Methods(\"GET\")\n\ts.router.Path(\"/addresses\").HandlerFunc(s.GetAddresses)\n\n\t// Set up router for node count.\n\ts.router.Path(\"/circulating-supply\").Queries().HandlerFunc(s.GetCirculatingSupply).Methods(\"GET\")\n\ts.router.Path(\"/circulating-supply\").HandlerFunc(s.GetCirculatingSupply)\n\n\t// Set up router for node count.\n\ts.router.Path(\"/total-supply\").Queries().HandlerFunc(s.GetTotalSupply).Methods(\"GET\")\n\ts.router.Path(\"/total-supply\").HandlerFunc(s.GetTotalSupply)\n\n\t// Do serving now.\n\tutils.Logger().Info().Str(\"port\", GetExplorerPort(s.Port)).Msg(\"Listening\")\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: s.router,\n\t\tReadTimeout: 5 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tIdleTimeout: 120 * time.Second,\n\t}\n\tgo func() {\n\t\tif err := server.ListenAndServe(); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"server.ListenAndServe()\")\n\t\t}\n\t}()\n\treturn server\n}", "func (r *openvpnAuthd) Run() error {\n\tgo func() {\n\t\tlistener := fmt.Sprintf(\"%s:%d\", r.config.ServiceBind, r.config.ServicePort)\n\t\terr := r.router.Run(listener)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"failed to start the service, error: %s\", err)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (s *Server) Run() {\n\tlog.Printf(\"[INFO] activate rest server on port %v\", s.Port)\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\"%v:%v\", s.address, s.Port), s.routes()))\n}", "func (g *RESTFrontend) Run(port int) {\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tg.Listener = listener\n\tg.RunWithListener(listener)\n}", "func main() {\n\tlog.Println(\"Starting Server.....\")\n\tDB_URL := os.Getenv(\"DB_URL\")\n\t// DB_URL := \"root:admin@tcp(127.0.0.1:3306)/dockertest\"\n\n\tstorage, err := sqlStorage.NewSQLStorage(DB_URL)\n\n\tservice := sv.NewService(storage)\n\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\thandler := httpHandler.NewHandler(service)\n\n\tport := \":8080\"\n\n\thttp.Handle(\"/geodata/\", handler)\n\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, \"Welcome to Geolocation Service!\")\n\t})\n\n\tfmt.Println(\"Listening on Port\", port)\n\terr = http.ListenAndServe(port, nil)\n\tlog.Fatal(err)\n}", "func main() {\n\tlog.Printf(\"grpc-ping: starting server...\")\n\n\t//Get env vars\n\t//Can be passed in at command line PORT=9090 or in code\n\tport := os.Getenv(\"PORT\")\n\t//if no port set to 8080\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t\tlog.Printf(\"Defaulting to port %s\", port)\n\t}\n\n\t//Creates a TCP listener on port you want\n\t//gRPC uses HTTP/2, which multiplexes multiple calls on a single TCP connection. All gRPC calls over that connection go to one endpoint\n\tlistener, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\tlog.Fatalf(\"net.Listen: %v\", err)\n\t}\n\n\n\t//creates a new gRPC server with a server service which can be called via an API\n\t//attach the Ping service to the server\n\t//Remember server implements service interface to create API that can be called - PingServiceServer interface\n\t//RegisterService registers a service and its implementation to the gRPC server. - Server API ready for calls\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterPingServiceServer(grpcServer, &pingService{})\n\tif err = grpcServer.Serve(listener); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Run(http_handler http.Handler, https_handler http.Handler) {\n\n\tvar server Server\n\tvar port int\n\tvar error error\n\n\tserver.Hostname = os.Getenv(\"HOSTNAME\")\n\tserver.UseHTTP = true\n\tserver.UseHTTPS = false\n\t\n\tport, error = strconv.Atoi(os.Getenv(\"HTTP_PORT\"))\n\tif error != nil {\n\t\tlog.Println(\"Config file does not specify a listener to start\")\n\t}\n\n\tserver.HTTPPort = port\n\tif server.HTTPPort == 0 {\n\t\tserver.HTTPPort = 8000\n\t}\n\n\tport, error = strconv.Atoi(os.Getenv(\"HTTPS_PORT\"))\n\tif error != nil {\n\t\tlog.Println(\"Config file does not specify a listener to start\")\n\t}\n\n\tserver.HTTPSPort = port\n\tif server.HTTPSPort == 0 {\n\t\tserver.HTTPSPort = 8443\n\t}\n\tserver.CertFile = os.Getenv(\"SSL_CERTIFICATE_FILE\")\n\tserver.KeyFile = os.Getenv(\"SSL_KEY_FILE\")\n\n\tif server.UseHTTP && server.UseHTTPS {\n\t\tgo func() {\n\t\t\tstart_HTTPS(https_handler, server)\n\t\t}()\n\n\t\tstart_HTTP(http_handler, server)\n\t} else if server.UseHTTP {\n\t\tstart_HTTP(http_handler, server)\n\t} else if server.UseHTTPS {\n\t\tstart_HTTPS(https_handler, server)\n\t} else {\n\t\tlog.Println(\"Config file does not specify a listener to start\")\n\t}\n}", "func main() {\n\ttypha := daemon.New()\n\terr := typha.InitializeAndServeForever(context.Background())\n\tlogrus.WithError(err).Panic(\"InitializeAndServeForever returned\")\n}", "func main() {\n\tws := new(restful.WebService)\n\tws.Route(ws.GET(\"/\").To(home))\n\trestful.Add(ws)\n\tprint(\"open browser on http://localhost:8080/\\n\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func main() {\n\t// load config and construct the server shared environment\n\tcfg := common.LoadConfig()\n\tlog := services.NewLogger(cfg)\n\n\t// create repository\n\trepo, err := repository.NewRepository(cfg, log)\n\tif err != nil {\n\t\tlog.Fatalf(\"Can not create application data repository. Terminating!\")\n\t}\n\n\t// setup GraphQL API handler\n\thttp.Handle(\"/api\", handlers.ApiHandler(cfg, repo, log))\n\n\t// show the server opening info and start the server with DefaultServeMux\n\tlog.Infof(\"Welcome to Fantom Rocks API server on [%s]\", cfg.BindAddr)\n\tlog.Fatal(http.ListenAndServe(cfg.BindAddr, nil))\n}", "func main() {\n\n\trouter := NewRouter()\n\tlog.Fatal(http.ListenAndServe(\":8080\", router))\n}", "func Start() error {\n\treturn e.Start(fmt.Sprintf(\"%s:%d\", defaultListenAddr, cfg.Port()))\n}", "func (ms *MicroService) StartOnPort(port int) {\n\n\t// add health\n\tms.Handle(\"GET\", \"/health\", ms.Health)\n\n\t// start the web server\n\tfmt.Printf(\"Listening on %d....\\n\", port)\n\t\n\tif err := http.ListenAndServe(\":\" + strconv.Itoa(port), ms.muxx); err != nil {\n\t\tfmt.Println(\"error\")\n\t\tlog.Fatal(\"ListenAndServe:\", err)\n\t} else {\n\t\tfmt.Println(\"running\")\n\t}\n}", "func (app *App) Run() {\n\tMust(app.Engine.Start(\":\" + app.Conf.UString(\"port\")))\n}", "func main() {\n\ta := bouncerule.App{}\n\n\tuser := os.Getenv(\"MYSQL_USER\")\n\tpassword := os.Getenv(\"MYSQL_PASSWORD\")\n\tdbname := os.Getenv(\"MYSQL_DATABASE\")\n\tport := os.Getenv(\"SERVER_PORT\")\n\taddress := fmt.Sprintf(\":%s\", port)\n\n\tfmt.Printf(\"Running server on port %s...\", port)\n\n\ta.Initialize(user, password, dbname)\n\ta.Run(address)\n}", "func main() {\n\t//\n\t//fileName := \"index\"\n\t//\n\t//port, _ := PickUnusedPort()\n\t//ui.ShowUI(port, fileName)\n\t// 4780\n\t//startProxy := ui.StartProxy()\n\t//log.Printf(\"%+v\\n\", startProxy)\n\n\tproxy := ui.ReqForProxy(\"127.0.0.1:4780\")\n\tlog.Printf(\"%+v\\n\", proxy)\n\n}" ]
[ "0.76951945", "0.7435243", "0.7348933", "0.7216398", "0.72111994", "0.71475387", "0.7131827", "0.7094178", "0.70566064", "0.7005312", "0.69892347", "0.69597363", "0.6941611", "0.6922821", "0.69024724", "0.6870611", "0.68511647", "0.68307954", "0.6821628", "0.68199885", "0.681419", "0.6810463", "0.68090093", "0.68075645", "0.68007934", "0.6797594", "0.67575765", "0.67526937", "0.6738359", "0.673835", "0.67364657", "0.6726005", "0.6724087", "0.67179245", "0.67130494", "0.67076904", "0.67060393", "0.6695063", "0.6662851", "0.6662085", "0.66580915", "0.66468734", "0.6645453", "0.66441154", "0.6637357", "0.6629619", "0.66267604", "0.66181713", "0.6609979", "0.6608797", "0.66041803", "0.65887165", "0.6586378", "0.65837574", "0.6579656", "0.6576219", "0.6562585", "0.65584326", "0.655837", "0.65571266", "0.655177", "0.6548185", "0.6517218", "0.6507488", "0.65002877", "0.6499167", "0.6492231", "0.64774203", "0.6475969", "0.64740556", "0.64691746", "0.646802", "0.64556575", "0.6455033", "0.64532775", "0.64456946", "0.6444976", "0.64446956", "0.64350104", "0.64335704", "0.64335406", "0.64326364", "0.64262044", "0.6426043", "0.6422642", "0.6422166", "0.6415511", "0.6405355", "0.6403677", "0.6401577", "0.6399182", "0.63968176", "0.63907206", "0.6390282", "0.6390237", "0.6389708", "0.6385165", "0.63844675", "0.63840127", "0.63833696" ]
0.768993
1
Dependencies is used to override any resource/dependency settings with a v2alpha1.DatadogAgentComponentOverride.
func Dependencies(logger logr.Logger, manager feature.ResourceManagers, dda *v2alpha1.DatadogAgent) (errs []error) { overrides := dda.Spec.Override namespace := dda.Namespace for component, override := range overrides { err := overrideRBAC(logger, manager, override, component, namespace) if err != nil { errs = append(errs, err) } // Handle custom agent configurations (datadog.yaml, cluster-agent.yaml, etc.) errs = append(errs, overrideCustomConfigs(logger, manager, override.CustomConfigurations, dda.Name, namespace)...) // Handle custom check configurations confdCMName := fmt.Sprintf(v2alpha1.ExtraConfdConfigMapName, strings.ToLower((string(component)))) errs = append(errs, overrideExtraConfigs(logger, manager, override.ExtraConfd, namespace, confdCMName, true)...) // Handle custom check files checksdCMName := fmt.Sprintf(v2alpha1.ExtraChecksdConfigMapName, strings.ToLower((string(component)))) errs = append(errs, overrideExtraConfigs(logger, manager, override.ExtraChecksd, namespace, checksdCMName, false)...) // Handle scc errs = append(errs, overrideSCC(manager, dda)...) } return errs }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t DotNetAgentVersion) Dependencies() []string {\n\treturn []string{\n\t\t\"DotNet/Agent/Installed\",\n\t}\n}", "func (p PHPEnvPHPinfoCLI) Dependencies() []string {\n\treturn []string{\"PHP/Config/Agent\"}\n}", "func (p BaseConfigProxyDetect) Dependencies() []string {\n\t// no dependencies!\n\treturn []string{\n\t\t\"Base/Config/Validate\",\n\t\t\"Base/Env/CollectEnvVars\",\n\t\t\"Base/Env/CollectSysProps\",\n\t}\n}", "func (p BaseLogCopy) Dependencies() []string {\n\treturn []string{\n\t\t\"Base/Env/CollectEnvVars\",\n\t\t\"Base/Env/CollectSysProps\",\n\t\t\"Base/Config/Validate\",\n\t}\n}", "func (p DotnetRequirementsDatastores) Dependencies() []string {\n\treturn []string{\n\t\t\"DotNet/Agent/Installed\",\n\t}\n}", "func (a *AdminKubeConfigCABundle) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&AdminKubeConfigSignerCertKey{},\n\t}\n}", "func (p InfraConfigValidateJMX) Dependencies() []string {\n\treturn []string{\n\t\t\"Infra/Config/IntegrationsMatch\",\n\t\t\"Java/Env/Version\",\n\t}\n}", "func (*gaeModule) Dependencies() []module.Dependency {\n\treturn []module.Dependency{\n\t\tmodule.OptionalDependency(redisconn.ModuleName), // for dscache, if enabled\n\t\tmodule.OptionalDependency(secrets.ModuleName), // to install DS random secrets backend\n\t}\n}", "func (f *dogstatsdFeature) ManageDependencies(managers feature.ResourceManagers, components feature.RequiredComponents) error {\n\t// agent local service\n\tif component.ShouldCreateAgentLocalService(managers.Store().GetVersionInfo(), f.forceEnableLocalService) {\n\t\tdsdPort := &corev1.ServicePort{\n\t\t\tProtocol: corev1.ProtocolUDP,\n\t\t\tTargetPort: intstr.FromInt(int(apicommon.DefaultDogstatsdPort)),\n\t\t\tPort: apicommon.DefaultDogstatsdPort,\n\t\t\tName: apicommon.DefaultDogstatsdPortName,\n\t\t}\n\t\tif f.hostPortEnabled {\n\t\t\tdsdPort.Port = f.hostPortHostPort\n\t\t\tdsdPort.Name = apicommon.DogstatsdHostPortName\n\t\t\tif f.useHostNetwork {\n\t\t\t\tdsdPort.TargetPort = intstr.FromInt(int(f.hostPortHostPort))\n\t\t\t}\n\t\t}\n\t\tserviceInternalTrafficPolicy := corev1.ServiceInternalTrafficPolicyLocal\n\t\tif err := managers.ServiceManager().AddService(f.localServiceName, f.owner.GetNamespace(), nil, []corev1.ServicePort{*dsdPort}, &serviceInternalTrafficPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif f.createSCC {\n\t\tsccName := component.GetAgentSCCName(f.owner)\n\t\tscc := securityv1.SecurityContextConstraints{}\n\n\t\tif f.hostPortEnabled {\n\t\t\tscc.AllowHostPorts = true\n\t\t}\n\t\tif f.originDetectionEnabled && f.udsEnabled {\n\t\t\tscc.AllowHostPID = true\n\t\t}\n\n\t\treturn managers.PodSecurityManager().AddSecurityContextConstraints(sccName, f.owner.GetNamespace(), &scc)\n\t}\n\treturn nil\n}", "func (t DotNetCoreRequirementsNetCoreVersion) Dependencies() []string {\n\treturn []string{\n\t\t\"DotNetCore/Agent/Installed\",\n\t\t\"DotNetCore/Env/Versions\",\n\t}\n}", "func (t BrowserAgentDetect) Dependencies() []string {\n\treturn []string{\n\t\t\"Browser/Agent/GetSource\",\n\t}\n}", "func (l *LoadInventory) Dependencies(\n\tc base.Container,\n) (err error) {\n\tl.client, err = c.S3API()\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.db, err = c.DB()\n\tl.inventory = c.InventoryManager()\n\n\treturn err\n}", "func (c *ClusterK8sIO) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&installconfig.InstallConfig{},\n\t\t&Networking{},\n\t}\n}", "func (a *baseDomain) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&platform{},\n\t}\n}", "func (p BaseConfigLogLevel) Dependencies() []string {\n\treturn []string{\n\t\t\"Base/Config/Validate\", //This identifies this task as dependent on \"Base/Config/Validate\" and so the results from that task will be passed to this task. See the execute method to see how to interact with the results.\n\t}\n}", "func (k *LoopbackClient) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&tls.AdminKubeConfigClientCertKey{},\n\t\t&tls.KubeAPIServerLocalhostCABundle{},\n\t\t&installconfig.InstallConfig{},\n\t}\n}", "func (c *AdminKubeConfigSignerCertKey) Dependencies() []asset.Asset {\n\treturn []asset.Asset{}\n}", "func (a *AdminKubeConfigClientCertKey) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&AdminKubeConfigSignerCertKey{},\n\t}\n}", "func (t *tectonic) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\tt.installConfig,\n\t\tt.ingressCertKey,\n\t\tt.kubeCA,\n\t}\n}", "func (p BaseEnvCheckWindowsAdmin) Dependencies() []string {\n\treturn []string{}\n}", "func (t *RoleCloudCredsSecretReader) Dependencies() []asset.Asset {\n\treturn []asset.Asset{}\n}", "func (*serverModule) Dependencies() []module.Dependency {\n\treturn nil\n}", "func (cs *Supervisor) InjectDependencies(l echo.Logger, s *stores.Stores, ws *socket.Server) {\n\tcs.logger = l\n\tcs.stores = s\n\tcs.ws = ws\n}", "func (m *Master) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&installconfig.InstallConfig{},\n\t\t&machine.Master{},\n\t}\n}", "func Dependencies(jaeger *v1alpha1.Jaeger) []batchv1.Job {\n\tif strings.ToLower(jaeger.Spec.Storage.Type) == \"cassandra\" {\n\t\treturn cassandraDeps(jaeger)\n\t}\n\n\treturn []batchv1.Job{}\n}", "func (t *TerraformVariables) Dependencies() []asset.Asset {\n\treturn []asset.Asset{\n\t\t&installconfig.InstallConfig{},\n\t\t&bootstrap.Bootstrap{},\n\t\t&machine.Master{},\n\t}\n}", "func (t BaseContainersDetectDocker) Dependencies() []string {\n\treturn []string{}\n}", "func (s DhcpServer) Dependencies() (deps []depgraph.Dependency) {\n\treturn []depgraph.Dependency{\n\t\t{\n\t\t\tRequiredItem: depgraph.ItemRef{\n\t\t\t\tItemType: NetNamespaceTypename,\n\t\t\t\tItemName: normNetNsName(s.NetNamespace),\n\t\t\t},\n\t\t\tDescription: \"Network namespace must exist\",\n\t\t},\n\t\t{\n\t\t\tRequiredItem: depgraph.ItemRef{\n\t\t\t\tItemType: VethTypename,\n\t\t\t\tItemName: s.VethName,\n\t\t\t},\n\t\t\tDescription: \"veth interface must exist\",\n\t\t},\n\t}\n}", "func (o VirtualDatabaseSpecBuildSourceOutput) Dependencies() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuildSource) []string { return v.Dependencies }).(pulumi.StringArrayOutput)\n}", "func (p *Wheel) Dependencies() []Dependency {\n\tvar dependencies []Dependency\n\n\tfor _, row := range p.RequiresDist {\n\t\tdep, err := version.ParseDependency(row)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"❗️ %s: %s(%v)\\n\", p.name, row, err)\n\t\t\tcontinue\n\t\t}\n\t\tinstall, err := dep.Evaluate(env)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"❗️ %s: %s(%v)\\n\", p.name, row, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !install {\n\t\t\tcontinue\n\t\t}\n\n\t\t// fmt.Fprintf(os.Stderr, \"🍀 %s: %s(minimal = %s)\\n\", name, row, version.Minimal(dep.Versions))\n\t\tdependencies = append(dependencies, Dependency{\n\t\t\tName: NormalizePackageName(dep.Name),\n\t\t\tVersion: version.Minimal(dep.Versions),\n\t\t})\n\t}\n\n\treturn dependencies\n}", "func (f *apmFeature) ManageDependencies(managers feature.ResourceManagers, components feature.RequiredComponents) error {\n\t// agent local service\n\tif component.ShouldCreateAgentLocalService(managers.Store().GetVersionInfo(), f.forceEnableLocalService) {\n\t\tapmPort := &corev1.ServicePort{\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\tTargetPort: intstr.FromInt(int(apicommon.DefaultApmPort)),\n\t\t\tPort: apicommon.DefaultApmPort,\n\t\t\tName: apicommon.DefaultApmPortName,\n\t\t}\n\t\tif f.hostPortEnabled {\n\t\t\tapmPort.Port = f.hostPortHostPort\n\t\t\tapmPort.Name = apicommon.APMHostPortName\n\t\t\tif f.useHostNetwork {\n\t\t\t\tapmPort.TargetPort = intstr.FromInt(int(f.hostPortHostPort))\n\t\t\t}\n\t\t}\n\n\t\tserviceInternalTrafficPolicy := corev1.ServiceInternalTrafficPolicyLocal\n\t\tif err := managers.ServiceManager().AddService(f.localServiceName, f.owner.GetNamespace(), nil, []corev1.ServicePort{*apmPort}, &serviceInternalTrafficPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// network policies\n\tif f.hostPortEnabled {\n\t\tpolicyName, podSelector := component.GetNetworkPolicyMetadata(f.owner, v2alpha1.NodeAgentComponentName)\n\t\tif f.createKubernetesNetworkPolicy {\n\t\t\tprotocolTCP := corev1.ProtocolTCP\n\t\t\tingressRules := []netv1.NetworkPolicyIngressRule{\n\t\t\t\t{\n\t\t\t\t\tPorts: []netv1.NetworkPolicyPort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPort: &intstr.IntOrString{\n\t\t\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\t\t\tIntVal: f.hostPortHostPort,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tProtocol: &protocolTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\treturn managers.NetworkPolicyManager().AddKubernetesNetworkPolicy(\n\t\t\t\tpolicyName,\n\t\t\t\tf.owner.GetNamespace(),\n\t\t\t\tpodSelector,\n\t\t\t\tnil,\n\t\t\t\tingressRules,\n\t\t\t\tnil,\n\t\t\t)\n\t\t} else if f.createCiliumNetworkPolicy {\n\t\t\tpolicySpecs := []cilium.NetworkPolicySpec{\n\t\t\t\t{\n\t\t\t\t\tDescription: \"Ingress for APM trace\",\n\t\t\t\t\tEndpointSelector: podSelector,\n\t\t\t\t\tIngress: []cilium.IngressRule{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFromEndpoints: []metav1.LabelSelector{\n\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tToPorts: []cilium.PortRule{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tPorts: []cilium.PortProtocol{\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tPort: strconv.Itoa(int(f.hostPortHostPort)),\n\t\t\t\t\t\t\t\t\t\t\tProtocol: cilium.ProtocolTCP,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\treturn managers.CiliumPolicyManager().AddCiliumPolicy(policyName, f.owner.GetNamespace(), policySpecs)\n\t\t}\n\t}\n\n\t// scc\n\tif f.createSCC {\n\t\tsccName := component.GetAgentSCCName(f.owner)\n\t\tscc := securityv1.SecurityContextConstraints{}\n\n\t\tif f.hostPortEnabled {\n\t\t\tscc.AllowHostPorts = true\n\t\t}\n\n\t\treturn managers.PodSecurityManager().AddSecurityContextConstraints(sccName, f.owner.GetNamespace(), &scc)\n\t}\n\n\treturn nil\n}", "func (shl *SharedLibrary) Dependencies() []string {\n\treturn shl.dependencies\n}", "func (h Client) UpdateDependencies(path string) error {\n\tklog.V(5).Infof(\"updating chart dependencies for %s\", path)\n\t_, stdErr, _ := h.Exec(\"dependency\", \"update\", path)\n\tif stdErr != \"\" {\n\t\treturn fmt.Errorf(\"error running helm dependency update: %s\", stdErr)\n\t}\n\n\treturn nil\n}", "func ExpectDependency(logger *logrusx.Logger, dependencies ...interface{}) {\n\tif logger == nil {\n\t\tpanic(\"missing logger for dependency check\")\n\t}\n\tfor _, d := range dependencies {\n\t\tif d == nil {\n\t\t\tlogger.WithError(errors.WithStack(ErrNilDependency)).Fatalf(\"A fatal issue occurred.\")\n\t\t}\n\t}\n}", "func (mgr *Manager) UpdateDependencies(cluster *common.Cluster) error {\n\toperators, err := mgr.resolveDependencies(cluster.MonitoredOperators)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcluster.MonitoredOperators = operators\n\treturn nil\n}", "func (b *BaseIntent) GetDependencies() map[string]UUIDSet {\n\treturn b.Dependencies\n}", "func (d *ABFToInterfaceDescriptor) Dependencies(key string, emptyVal proto.Message) []api.Dependency {\n\t_, ifName, _ := vpp_abf.ParseToInterfaceKey(key)\n\treturn []api.Dependency{\n\t\t{\n\t\t\tLabel: interfaceDep,\n\t\t\tKey: vpp_interfaces.InterfaceKey(ifName),\n\t\t},\n\t}\n}", "func CacheDependency(a app.App, d pkg.Descriptor, customName string) error {\n\tlogger := log.WithFields(log.Fields{\n\t\t\"descriptor\": d,\n\t\t\"custom-name\": customName,\n\t})\n\n\tlogger.Debug(\"caching dependency\")\n\n\tlibs, err := a.Libraries()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := libs[customName]; ok {\n\t\treturn errors.Errorf(\"package '%s' already exists. Use the --name flag to install this package with a unique identifier\",\n\t\t\tcustomName)\n\t}\n\n\tregistries, err := a.Registries()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tregRefSpec, exists := registries[d.Registry]\n\tif !exists {\n\t\treturn fmt.Errorf(\"registry '%s' does not exist\", d.Registry)\n\t}\n\n\tr, err := Locate(a, regRefSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvendorPath := filepath.Join(a.Root(), \"vendor\")\n\n\t// Get all directories and files first, then write to disk. This\n\t// protects us from failing with a half-cached dependency because of\n\t// a network failure.\n\tdirectories := []string{}\n\tfiles := map[string][]byte{}\n\t_, libRef, err := r.ResolveLibrary(\n\t\td.Part,\n\t\tcustomName,\n\t\td.Version,\n\t\tfunc(relPath string, contents []byte) error {\n\t\t\tfiles[filepath.Join(vendorPath, relPath)] = contents\n\t\t\treturn nil\n\t\t},\n\t\tfunc(relPath string) error {\n\t\t\tdirectories = append(directories, filepath.Join(vendorPath, relPath))\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add library to app specification, but wait to write it out until\n\t// the end, in case one of the network calls fails.\n\tlog.Infof(\"Retrieved %d files\", len(files))\n\n\tfor _, dir := range directories {\n\t\tif err = a.Fs().MkdirAll(dir, app.DefaultFolderPermissions); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor path, content := range files {\n\t\tif err = afero.WriteFile(a.Fs(), path, content, app.DefaultFilePermissions); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlibRef.Registry = d.Registry\n\n\treturn a.UpdateLib(libRef.Name, libRef)\n}", "func GuessDeps(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {\n\tbuildContext, err := util.GetBuildContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := p.Get(\"dirname\", \".\").(string)\n\tskipImport := p.Get(\"skipImport\", false).(bool)\n\tname := guessPackageName(buildContext, base)\n\n\tInfo(\"Generating a YAML configuration file and guessing the dependencies\")\n\n\tconfig := new(cfg.Config)\n\n\t// Get the name of the top level package\n\tconfig.Name = name\n\n\t// Import by looking at other package managers and looking over the\n\t// entire directory structure.\n\n\t// Attempt to import from other package managers.\n\tif !skipImport {\n\t\tInfo(\"Attempting to import from other package managers (use --skip-import to skip)\")\n\t\tdeps := []*cfg.Dependency{}\n\t\tabsBase, err := filepath.Abs(base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif d, ok := guessImportGodep(absBase); ok {\n\t\t\tInfo(\"Importing Godep configuration\")\n\t\t\tWarn(\"Godep uses commit id versions. Consider using Semantic Versions with Glide\")\n\t\t\tdeps = d\n\t\t} else if d, ok := guessImportGPM(absBase); ok {\n\t\t\tInfo(\"Importing GPM configuration\")\n\t\t\tdeps = d\n\t\t} else if d, ok := guessImportGB(absBase); ok {\n\t\t\tInfo(\"Importing GB configuration\")\n\t\t\tdeps = d\n\t\t}\n\n\t\tfor _, i := range deps {\n\t\t\tInfo(\"Found imported reference to %s\\n\", i.Name)\n\t\t\tconfig.Imports = append(config.Imports, i)\n\t\t}\n\t}\n\n\t// Resolve dependencies by looking at the tree.\n\tr, err := dependency.NewResolver(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := &dependency.DefaultMissingPackageHandler{Missing: []string{}, Gopath: []string{}}\n\tr.Handler = h\n\n\tsortable, err := r.ResolveLocal(false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Strings(sortable)\n\n\tvpath := r.VendorDir\n\tif !strings.HasSuffix(vpath, \"/\") {\n\t\tvpath = vpath + string(os.PathSeparator)\n\t}\n\n\tfor _, pa := range sortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot := util.GetRootFromPackage(n)\n\n\t\tif !config.HasDependency(root) {\n\t\t\tInfo(\"Found reference to %s\\n\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tsubpkg := strings.TrimPrefix(n, root)\n\t\t\tif len(subpkg) > 0 && subpkg != \"/\" {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.Imports = append(config.Imports, d)\n\t\t} else {\n\t\t\tsubpkg := strings.TrimPrefix(n, root)\n\t\t\tif len(subpkg) > 0 && subpkg != \"/\" {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.Imports.Get(root)\n\t\t\t\tf := false\n\t\t\t\tfor _, v := range d.Subpackages {\n\t\t\t\t\tif v == subpkg {\n\t\t\t\t\t\tf = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !f {\n\t\t\t\t\tInfo(\"Adding sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn config, nil\n}", "func (o VirtualDatabaseSpecBuildSourcePtrOutput) Dependencies() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecBuildSource) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Dependencies\n\t}).(pulumi.StringArrayOutput)\n}", "func (b *Bundle) DependsOn() []string {\n\treturn []string{viper.BundleName}\n}", "func (d *InterfaceVrfDescriptor) Dependencies(key string, emptyVal proto.Message) (deps []kvs.Dependency) {\n\tif _, vrf, ipv4, ipv6, isIfaceVrfKey := interfaces.ParseInterfaceVrfKey(key); isIfaceVrfKey {\n\t\tif vrf > 0 && ipv4 {\n\t\t\tdeps = append(deps, kvs.Dependency{\n\t\t\t\tLabel: vrfV4Dep,\n\t\t\t\tKey: l3.VrfTableKey(uint32(vrf), l3.VrfTable_IPV4),\n\t\t\t})\n\t\t}\n\t\tif vrf > 0 && ipv6 {\n\t\t\tdeps = append(deps, kvs.Dependency{\n\t\t\t\tLabel: vrfV6Dep,\n\t\t\t\tKey: l3.VrfTableKey(uint32(vrf), l3.VrfTable_IPV6),\n\t\t\t})\n\t\t}\n\t\treturn deps\n\t}\n\n\t_, fromIface, _ := interfaces.ParseInterfaceInheritedVrfKey(key)\n\treturn []kvs.Dependency{\n\t\t{\n\t\t\tLabel: inheritedVrfDep,\n\t\t\tAnyOf: kvs.AnyOfDependency{\n\t\t\t\tKeyPrefixes: []string{interfaces.InterfaceVrfKeyPrefix(fromIface)},\n\t\t\t},\n\t\t},\n\t}\n}", "func installDependencies(workingDirectoryPath string) error {\n\n\t// Install Ansible\n\tansibleVersion := inputValues.Ansible.Version\n\tif err := installAnsible(ansibleVersion); err != nil {\n\t\treturn err\n\t}\n\n\t// Install paramiko\n\tif err := installParamiko(); err != nil {\n\t\treturn err\n\t}\n\n\t// Download Consul\n\toverwrite := (previousBootstrapVersion.Consul != consulVersion)\n\tif err := downloadUnzip(inputValues.Consul.DownloadURL, \"consul.zip\", workingDirectoryPath, overwrite); err != nil {\n\t\treturn err\n\t}\n\n\t// Download Terraform\n\toverwrite = (previousBootstrapVersion.Terraform != terraformVersion)\n\tif err := downloadUnzip(inputValues.Terraform.DownloadURL, \"terraform.zip\", workingDirectoryPath, overwrite); err != nil {\n\t\treturn err\n\t}\n\n\t// Donwload Terraform plugins\n\tfor i, url := range inputValues.Terraform.PluginURLs {\n\t\tif err := downloadUnzip(url, fmt.Sprintf(\"terraform-plugin-%d.zip\", i), workingDirectoryPath, overwrite); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func buildUnconfiguredIgnitionAssetDefaultDependencies(t *testing.T) []asset.Asset {\n\tt.Helper()\n\n\tinfraEnv := getTestInfraEnv()\n\tagentPullSecret := getTestAgentPullSecret(t)\n\tclusterImageSet := getTestClusterImageSet()\n\n\treturn []asset.Asset{\n\t\t&infraEnv,\n\t\t&agentPullSecret,\n\t\t&clusterImageSet,\n\t\t&manifests.NMStateConfig{},\n\t\t&mirror.RegistriesConf{},\n\t\t&mirror.CaBundle{},\n\t}\n}", "func importDependencies(project common.AppProject) error {\n\n\tai, err := util.GetAppImports(filepath.Join(project.Dir(), fileFlogoJson), project.DepManager(), true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timports := ai.GetAllImports()\n\n\tif len(imports) == 0 {\n\t\treturn nil\n\t}\n\n\terr = project.AddImports(true, false, imports...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlegacySupportRequired := false\n\n\tfor _, details := range ai.GetAllImportDetails() {\n\n\t\tpath, err := project.GetPath(details.Imp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdesc, err := util.GetContribDescriptor(path)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif desc != nil {\n\n\t\t\tcType := desc.GetContribType()\n\t\t\tif desc.IsLegacy {\n\t\t\t\tlegacySupportRequired = true\n\t\t\t\tcType = \"legacy \" + desc.GetContribType()\n\t\t\t\terr := CreateLegacyMetadata(path, desc.GetContribType(), details.Imp.GoImportPath())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Installed %s: %s\\n\", cType, details.Imp)\n\t\t\t//instStr := fmt.Sprintf(\"Installed %s:\", cType)\n\t\t\t//fmt.Printf(\"%-20s %s\\n\", instStr, imp)\n\t\t}\n\t}\n\t\n\tif Verbose() {\n\t\tfmt.Printf(\"Tidying go mod...\")\n\t}\n\t\n\terr = util.ExecCmd(exec.Command(\"go\", \"mod\", \"tidy\"), project.SrcDir())\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to clean deps: %s\\n\", err)\n\t}\n\n\tif legacySupportRequired {\n\t\terr := InstallLegacySupport(project)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *App) InstallDeps(w io.Writer) error {\n\treturn a.run(\"/var/lib/tsuru/hooks/dependencies\", w)\n}", "func buildDependencies(fdSet *dpb.FileDescriptorSet) {\n\t// Dependency to google/api/annotations.proto for gRPC-HTTP transcoding. Here a couple of problems arise:\n\t// 1. Problem: \tWe cannot call descriptor.ForMessage(&annotations.E_Http), which would be our\n\t//\t\t\t\trequired dependency. However, we can call descriptor.ForMessage(&http) and\n\t//\t\t\t\tthen construct the extension manually.\n\t// 2. Problem: \tThe name is set wrong.\n\t// 3. Problem: \tgoogle/api/annotations.proto has a dependency to google/protobuf/descriptor.proto.\n\thttp := annotations.Http{}\n\tfd, _ := descriptor.MessageDescriptorProto(&http)\n\n\textensionName := \"http\"\n\tn := \"google/api/annotations.proto\"\n\tl := dpb.FieldDescriptorProto_LABEL_OPTIONAL\n\tt := dpb.FieldDescriptorProto_TYPE_MESSAGE\n\ttName := \"google.api.HttpRule\"\n\textendee := \".google.protobuf.MethodOptions\"\n\n\thttpExtension := &dpb.FieldDescriptorProto{\n\t\tName: &extensionName,\n\t\tNumber: &annotations.E_Http.Field,\n\t\tLabel: &l,\n\t\tType: &t,\n\t\tTypeName: &tName,\n\t\tExtendee: &extendee,\n\t}\n\n\tfd.Extension = append(fd.Extension, httpExtension) // 1. Problem\n\tfd.Name = &n // 2. Problem\n\tfd.Dependency = append(fd.Dependency, \"google/protobuf/descriptor.proto\") //3.rd Problem\n\n\t// Build other required dependencies\n\te := empty.Empty{}\n\tfdp := dpb.DescriptorProto{}\n\tfd2, _ := descriptor.MessageDescriptorProto(&e)\n\tfd3, _ := descriptor.MessageDescriptorProto(&fdp)\n\tdependencies := []*dpb.FileDescriptorProto{fd, fd2, fd3}\n\n\t// According to the documentation of protoReflect.CreateFileDescriptorFromSet the file I want to print\n\t// needs to be at the end of the array. All other FileDescriptorProto are dependencies.\n\tfdSet.File = append(dependencies, fdSet.File...)\n}", "func (mgr *Manager) UpdateDependencies(cluster *common.Cluster) error {\n\toperators, err := unmarshallOperators(cluster.Operators)\n\tif err != nil {\n\t\treturn err\n\t}\n\toperators, err = mgr.resolveDependencies(operators)\n\tif err != nil {\n\t\treturn err\n\t}\n\tupdatedOperators, err := json.Marshal(operators)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcluster.Operators = string(updatedOperators)\n\n\treturn nil\n}", "func (h *Helm) installDependencies(ctx context.Context, chartDir string, mc *masterChart) error {\n\tfor _, dep := range mc.requirements.Dependencies {\n\t\tchartName := fmt.Sprintf(\"%s-%s.tgz\", dep.Name, dep.Version)\n\t\tif err := ioutil.WriteFile(filepath.Join(chartDir, \"charts\", chartName), mc.inlineCharts[dep.Alias], 0644); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create chart file %s: %v\", chartName, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *AWSMediaLiveChannel_InputAttachment) DependsOn() []string {\n\treturn r._dependsOn\n}", "func (s *Service) Depends() []string {\n\treturn s.depends\n}", "func (m manager) installDependencies() error {\n\tif err := m.installVSDependencies(); err != nil {\n\t\treturn fmt.Errorf(\"could not install Visual Studio dependencies: %v\", err)\n\t}\n\tif err := m.installUnrealPrereqs(); err != nil {\n\t\treturn fmt.Errorf(\"could not install unreal dependencies: %v\", err)\n\t}\n\tif err := m.installVCRedist(); err != nil {\n\t\treturn fmt.Errorf(\"could not install VC Redistributable: %v\", err)\n\t}\n\tif runningInCI() {\n\t\t// TODO(b/164400783): Stackdriver could be messing up with CI machines, evaluate over some\n\t\t// period of time if this is correct.\n\t\t// if err := m.installStackDriverMonitoring(); err != nil {\n\t\t// \treturn fmt.Errorf(\"could not install Stack Driver monitoring: %v\", err)\n\t\t// }\n\t}\n\treturn nil\n}", "func (s S) Dependencies() []batchv1.Job {\n\treturn s.dependencies\n}", "func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency {\n\tvar dependencies []kvs.Dependency\n\t// the outgoing interface must exist and be UP\n\tif route.OutgoingInterface != \"\" {\n\t\tdependencies = append(dependencies, kvs.Dependency{\n\t\t\tLabel: routeOutInterfaceDep,\n\t\t\tKey: interfaces.InterfaceKey(route.OutgoingInterface),\n\t\t})\n\t}\n\n\t// non-zero VRFs\n\tvar protocol l3.VrfTable_Protocol\n\t_, isIPv6, _ := addrs.ParseIPWithPrefix(route.DstNetwork)\n\tif isIPv6 {\n\t\tprotocol = l3.VrfTable_IPV6\n\t}\n\tif route.VrfId != 0 {\n\t\tdependencies = append(dependencies, kvs.Dependency{\n\t\t\tLabel: vrfTableDep,\n\t\t\tKey: l3.VrfTableKey(route.VrfId, protocol),\n\t\t})\n\t}\n\tif route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 {\n\t\tdependencies = append(dependencies, kvs.Dependency{\n\t\t\tLabel: viaVrfTableDep,\n\t\t\tKey: l3.VrfTableKey(route.ViaVrfId, protocol),\n\t\t})\n\t}\n\n\t// if destination network is netalloc reference, then the address must be allocated first\n\tallocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork,\n\t\t\"\", \"dst_network-\")\n\tif hasAllocDep {\n\t\tdependencies = append(dependencies, allocDep)\n\t}\n\t// if GW is netalloc reference, then the address must be allocated first\n\tallocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.NextHopAddr,\n\t\troute.OutgoingInterface, \"gw_addr-\")\n\tif hasAllocDep {\n\t\tdependencies = append(dependencies, allocDep)\n\t}\n\n\t// TODO: perhaps check GW routability\n\treturn dependencies\n}", "func (mdr *Modder) MvsMergeDependency(m *Module) error {\n\t// Don't add the root module to the dependencies\n\tif mdr.module.Module == m.Module {\n\t\treturn nil\n\t}\n\n\t// check for existing module\n\te, ok := mdr.depsMap[m.Module]\n\tif !ok {\n\t\t// just add\n\t\tmdr.depsMap[m.Module] = m\n\n\t} else {\n\t\t// check local replace\n\t\tif strings.HasPrefix(e.ReplaceModule, \".\") {\n\t\t\t// do nothing\n\t\t\treturn nil\n\t\t}\n\n\t\t// check remote replace\n\t\tif m.ReplaceModule != \"\" {\n\t\t\tif e.ReplaceModule == m.ReplaceModule {\n\t\t\t\t// check version, is what we have a newer version?\n\t\t\t\tif semver.Compare(e.ReplaceVersion, m.ReplaceVersion) >= 0 {\n\t\t\t\t\t// do nothing, only 1/4 cases\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t// all other cases, want to update module\n\t\t} else {\n\t\t\t// check version, is what we have a newer version?\n\t\t\tif semver.Compare(e.Version, m.Version) >= 0 {\n\t\t\t\t// do nothing\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tmdr.depsMap[m.Module] = m\n\n\t}\n\n\tfmt.Printf(\"Merge %-48s => %s\\n\", m.Module + \"@\" + m.Version, m.ReplaceModule + \"@\" + m.ReplaceVersion)\n\n\t// XXX This is what basically makes us BFS\n\tfor _, R := range m.SelfDeps {\n\t\terr := mdr.VendorDep(R)\n\t\tif err != nil {\n\t\t\tmdr.errors = append(mdr.errors, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (component *Component) ListDependencies() ([]string, error) {\n\t// collect names\n\tdependencies := []string{}\n\n\tcomponent.DependenciesX.RLock()\n\tfor dependency := range component.Dependencies {\n\t\tdependencies = append(dependencies, dependency)\n\t}\n\tcomponent.DependenciesX.RUnlock()\n\n\t// success\n\treturn dependencies, nil\n}", "func getDependencies() error {\n\t// go get -u dependencies from the dependencies array\n\tfor _, dependency := range dependencies {\n\t\t// Exec go get command inside Name folder using exec.Command\n\t\tcmd := exec.Command(\"go\", \"get\", \"-u\", dependency)\n\t\tcmd.Dir = Name\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *AWSApiGatewayUsagePlan_ApiStage) DependsOn() []string {\n\treturn r._dependsOn\n}", "func addDependencies(fdSet *dpb.FileDescriptorSet) {\n\t// At last, we need to add the dependencies to the FileDescriptorProto in order to get them rendered.\n\tlastFdProto := getLast(fdSet.File)\n\tfor _, fd := range fdSet.File {\n\t\tif fd != lastFdProto {\n\t\t\tif *fd.Name == \"google/protobuf/empty.proto\" { // Reference: https://github.com/googleapis/gnostic-grpc/issues/8\n\t\t\t\tif shouldRenderEmptyImport {\n\t\t\t\t\tlastFdProto.Dependency = append(lastFdProto.Dependency, *fd.Name)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlastFdProto.Dependency = append(lastFdProto.Dependency, *fd.Name)\n\t\t}\n\t}\n\t// Sort imports so they will be rendered in a consistent order.\n\tsort.Strings(lastFdProto.Dependency)\n}", "func PrepareDependensies(cfg config.Config) *Dependencies {\n\tvar (\n\t\trepositories Repositories\n\t\tservices Services\n\t\thandlers Handlers\n\t)\n\n\trepositories.discountRepository = repository.NewDiscountRepository(cfg.Database)\n\trepositories.usedDiscountRepository = repository.NewUsedDiscountRepository(cfg.Database)\n\tservices.discountService = service.NewDiscountService(*cfg.Logger, repositories.discountRepository, repositories.usedDiscountRepository)\n\thandlers.discountHandler = handler.NewDiscountHandler(*cfg.Logger, *cfg.Validator, services.discountService)\n\n\treturn &Dependencies{\n\t\tRepositories: repositories,\n\t\tServices: services,\n\t\tHandlers: handlers,\n\t}\n}", "func EnsureHelmDependencies(t *testing.T, options *helm.Options, chartDir string, skipIfChartsFolderExists bool) {\n\tIsHelm3(t, false, true)\n\n\tif !files.FileExists(chartDir) {\n\t\trequire.FailNow(t, \"Chart not found: \"+chartDir)\n\t}\n\n\tif !files.FileExists(chartDir + \"/Chart.yaml\") {\n\t\tlogger.Log(t, \"Skip chart dependencies - no Chart.yaml\")\n\t\treturn\n\t}\n\n\tif files.FileExists(chartDir+\"/charts\") && skipIfChartsFolderExists {\n\t\tlogger.Log(t, \"Skip chart dependencies - charts folder already present\")\n\t\treturn\n\t}\n\n\tviper.SetConfigName(\"Chart\")\n\tviper.AddConfigPath(chartDir)\n\tvar requirements ChartRequirements\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tt.Fatalf(\"Error reading requirements file, %s\", err)\n\t}\n\n\terr := viper.Unmarshal(&requirements)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to decode into struct, %v\", err)\n\t}\n\n\t// Find any file dependencies in the subcharts so we can ensure\n\t// they are up to date\n\tfor index := range requirements.Dependencies {\n\t\tif value, ok := requirements.Dependencies[index][\"repository\"]; ok {\n\t\t\tif strings.HasPrefix(value, \"file:\") {\n\t\t\t\tsubChartDir := strings.Trim(value, \"file://\")\n\t\t\t\tHelmDep(t, options, chartDir+\"/\"+subChartDir)\n\t\t\t}\n\t\t}\n\t}\n\n\tHelmDep(t, options, chartDir)\n}", "func DefaultDatadogAgentSpecDatadogAgentStrategy(agent *DatadogAgentSpecAgentSpec) *DaemonSetDeploymentStrategy {\n\tstrategyOverride := &DaemonSetDeploymentStrategy{}\n\tif agent.DeploymentStrategy == nil {\n\t\tagent.DeploymentStrategy = &DaemonSetDeploymentStrategy{}\n\t}\n\n\tif agent.DeploymentStrategy.UpdateStrategyType == nil {\n\t\tupdateStrategy := apicommon.DefaultUpdateStrategy\n\t\tagent.DeploymentStrategy.UpdateStrategyType = &updateStrategy\n\t\tstrategyOverride.UpdateStrategyType = agent.DeploymentStrategy.UpdateStrategyType\n\t}\n\n\tif agent.DeploymentStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\tagent.DeploymentStrategy.RollingUpdate.MaxUnavailable = &intstr.IntOrString{\n\t\t\tType: intstr.String,\n\t\t\tStrVal: apicommon.DefaultRollingUpdateMaxUnavailable,\n\t\t}\n\t\tstrategyOverride.RollingUpdate.MaxUnavailable = agent.DeploymentStrategy.RollingUpdate.MaxUnavailable\n\t}\n\n\tif agent.DeploymentStrategy.RollingUpdate.MaxPodSchedulerFailure == nil {\n\t\tagent.DeploymentStrategy.RollingUpdate.MaxPodSchedulerFailure = &intstr.IntOrString{\n\t\t\tType: intstr.String,\n\t\t\tStrVal: apicommon.DefaultRollingUpdateMaxPodSchedulerFailure,\n\t\t}\n\t\tstrategyOverride.RollingUpdate.MaxPodSchedulerFailure = agent.DeploymentStrategy.RollingUpdate.MaxPodSchedulerFailure\n\t}\n\n\tif agent.DeploymentStrategy.RollingUpdate.MaxParallelPodCreation == nil {\n\t\tagent.DeploymentStrategy.RollingUpdate.MaxParallelPodCreation = apiutils.NewInt32Pointer(apicommon.DefaultRollingUpdateMaxParallelPodCreation)\n\t\tstrategyOverride.RollingUpdate.MaxParallelPodCreation = agent.DeploymentStrategy.RollingUpdate.MaxParallelPodCreation\n\t}\n\n\tif agent.DeploymentStrategy.RollingUpdate.SlowStartIntervalDuration == nil {\n\t\tagent.DeploymentStrategy.RollingUpdate.SlowStartIntervalDuration = &metav1.Duration{\n\t\t\tDuration: apicommon.DefaultRollingUpdateSlowStartIntervalDuration,\n\t\t}\n\t\tstrategyOverride.RollingUpdate.SlowStartIntervalDuration = agent.DeploymentStrategy.RollingUpdate.SlowStartIntervalDuration\n\t}\n\n\tif agent.DeploymentStrategy.RollingUpdate.SlowStartAdditiveIncrease == nil {\n\t\tagent.DeploymentStrategy.RollingUpdate.SlowStartAdditiveIncrease = &intstr.IntOrString{\n\t\t\tType: intstr.String,\n\t\t\tStrVal: apicommon.DefaultRollingUpdateSlowStartAdditiveIncrease,\n\t\t}\n\t\tstrategyOverride.RollingUpdate.SlowStartAdditiveIncrease = agent.DeploymentStrategy.RollingUpdate.SlowStartAdditiveIncrease\n\t}\n\n\tif agent.DeploymentStrategy.Canary == nil {\n\t\tagent.DeploymentStrategy.Canary = edsdatadoghqv1alpha1.DefaultExtendedDaemonSetSpecStrategyCanary(\n\t\t\t&edsdatadoghqv1alpha1.ExtendedDaemonSetSpecStrategyCanary{},\n\t\t\tedsdatadoghqv1alpha1.ExtendedDaemonSetSpecStrategyCanaryValidationModeAuto,\n\t\t)\n\t\tstrategyOverride.Canary = agent.DeploymentStrategy.Canary\n\t}\n\n\tif agent.DeploymentStrategy.ReconcileFrequency == nil {\n\t\tagent.DeploymentStrategy.ReconcileFrequency = &metav1.Duration{\n\t\t\tDuration: apicommon.DefaultReconcileFrequency,\n\t\t}\n\t\tstrategyOverride.ReconcileFrequency = agent.DeploymentStrategy.ReconcileFrequency\n\t}\n\n\treturn strategyOverride\n}", "func (d *galleryDocument) Dependencies() map[string]struct{} {\n\treturn map[string]struct{}{tmplPathToName(galTmplPath): {}}\n}", "func (dm *DotnetModule) CalcDependencies() error {\n\terr := dm.runCmd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !dm.containingBuild.buildNameAndNumberProvided() {\n\t\treturn nil\n\t}\n\tslnFile, err := dm.updateSolutionPathAndGetFileName()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsol, err := solution.Load(dm.solutionPath, slnFile, dm.containingBuild.logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuildInfo, err := sol.BuildInfo(dm.name, dm.containingBuild.logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn dm.containingBuild.SaveBuildInfo(buildInfo)\n}", "func (r *AWSMediaLiveChannel_InputAttachment) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}", "func (m *multiNode) SetDependency(dep []int32) {\n\tm.dependency = dep\n}", "func Depends(dock *docker.Docker, n *naming.Naming, extraPackages []string) error {\n\tlog.Info(\"Installing dependencies\")\n\tlog.Drop()\n\n\targs := []docker.ContainerExecArgs{\n\t\t{\n\t\t\tName: n.Container,\n\t\t\tCmd: \"rm -f a.list\",\n\t\t\tAsRoot: true,\n\t\t\tWorkDir: \"/etc/apt/sources.list.d\",\n\t\t}, {\n\t\t\tName: n.Container,\n\t\t\tCmd: \"echo deb [trusted=yes] file://\" + naming.ContainerArchiveDir + \" ./ > a.list\",\n\t\t\tAsRoot: true,\n\t\t\tWorkDir: \"/etc/apt/sources.list.d\",\n\t\t\tSkip: extraPackages == nil,\n\t\t}, {\n\t\t\tName: n.Container,\n\t\t\tCmd: \"dpkg-scanpackages -m . > Packages\",\n\t\t\tAsRoot: true,\n\t\t\tWorkDir: naming.ContainerArchiveDir,\n\t\t\tSkip: extraPackages == nil,\n\t\t}, {\n\t\t\tName: n.Container,\n\t\t\tCmd: \"apt-get update\",\n\t\t\tAsRoot: true,\n\t\t\tNetwork: true,\n\t\t}, {\n\t\t\tName: n.Container,\n\t\t\tCmd: \"apt-get build-dep ./ -t \" + n.Target,\n\t\t\tNetwork: true,\n\t\t\tAsRoot: true,\n\t\t},\n\t}\n\n\tfor _, arg := range args {\n\t\terr := dock.ContainerExec(arg)\n\t\tif err != nil {\n\t\t\treturn log.Failed(err)\n\t\t}\n\t}\n\n\treturn log.Done()\n}", "func CheckDependencies(ctx context.Context, clt client.Client, addon *types.Addon) bool {\n\tvar app v1beta1.Application\n\tfor _, dep := range addon.Dependencies {\n\t\terr := clt.Get(ctx, client.ObjectKey{\n\t\t\tNamespace: types.DefaultKubeVelaNS,\n\t\t\tName: Convert2AppName(dep.Name),\n\t\t}, &app)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Dependencies(g *Graph) (pacman.Packages, aur.Packages, []string) {\n\trps := make(pacman.Packages, 0)\n\taps := make(aur.Packages, 0)\n\tups := make([]string, 0)\n\n\tnames := make(map[string]bool)\n\tnodes := AllNodesBottomUp(g)\n\tfor _, vn := range nodes {\n\t\tn := vn.(*Node)\n\t\tif names[n.PkgName()] {\n\t\t\tcontinue\n\t\t}\n\n\t\tnames[n.PkgName()] = true\n\t\tswitch p := n.AnyPackage.(type) {\n\t\tcase *aur.Package:\n\t\t\taps = append(aps, p)\n\t\tcase *pacman.Package:\n\t\t\tif p.Origin == pacman.UnknownOrigin {\n\t\t\t\tups = append(ups, p.Name)\n\t\t\t} else {\n\t\t\t\trps = append(rps, p)\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unexpected type of package in graph\")\n\t\t}\n\t}\n\treturn rps, aps, ups\n}", "func Deps() error {\n\tenv := map[string]string{\n\t\t\"GO111MODULE\": \"on\",\n\t\t\"CGO_ENABLED\": \"0\",\n\t\t\"CGO_LDFLAGS\": \"-s -w -extldflags '-static'\",\n\t}\n\targs := []string{\n\t\t\"mod\",\n\t\t\"tidy\",\n\t}\n\terr := sh.RunWithV(env, \"go\", args...)\n\tif err != nil {\n\t\terr = stacktrace.Propagate(err, \"could not tidy go modules\")\n\t\treturn err\n\t}\n\targs = []string{\n\t\t\"get\",\n\t}\n\tif mg.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args, \".\"+string(os.PathSeparator)+\"...\")\n\terr = sh.RunWithV(env, \"go\", args...)\n\tif err != nil {\n\t\terr = stacktrace.Propagate(err, \"could not download dependant packages\")\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (m *Module) Depends() []dingo.Module {\n\treturn []dingo.Module{\n\t\tnew(commerceProduct.Module),\n\t}\n}", "func guessDeps(base string, skipImport bool) *cfg.Config {\n\tbuildContext, err := util.GetBuildContext()\n\tif err != nil {\n\t\tmsg.Die(\"Failed to build an import context: %s\", err)\n\t}\n\tname := buildContext.PackageName(base)\n\n\n\tmsg.Info(\"Generating a YAML configuration file and guessing the dependencies\")\n\n\tconfig := new(cfg.Config)\n\n\t// Get the name of the top level package\n\tconfig.Name = name\n\n\t// Import by looking at other package managers and looking over the\n\t// entire directory structure.\n\n\t// Attempt to import from other package managers.\n\tif !skipImport {\n\t\tguessImportDeps(base, config)\n\t}\n\n\timportLen := len(config.Imports)\n\tif importLen == 0 {\n\t\tmsg.Info(\"Scanning code to look for dependencies\")\n\t} else {\n\t\tmsg.Info(\"Scanning code to look for dependencies not found in import\")\n\t}\n\n\t// 返回依赖解析器\n\tr, err := dependency.NewResolver(base)\n\n\n\tif err != nil {\n\t\tmsg.Die(\"Error creating a dependency resolver: %s\", err)\n\t}\n\n\t// 初始化以测试模式\n\tr.ResolveTest = true\n\n\th := &dependency.DefaultMissingPackageHandler{Missing: []string{}, Gopath: []string{}}\n\tr.Handler = h\n\n\tsortable, testSortable, err := r.ResolveLocal(false)\n\tif err != nil {\n\t\tmsg.Die(\"分析本地依赖失败: %s\", err)\n\t}\n\n\tsort.Strings(sortable)\n\tsort.Strings(testSortable)\n\n\tvpath := r.VendorDir\n\tif !strings.HasSuffix(vpath, \"/\") {\n\t\tvpath = vpath + string(os.PathSeparator)\n\t}\n\n\tfor _, pa := range sortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot, subpkg := util.NormalizeName(n)\n\n\t\tif !config.Imports.Has(root) && root != config.Name {\n\t\t\tmsg.Info(\"--> Found reference to %s\\n\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.Imports = append(config.Imports, d)\n\t\t} else if config.Imports.Has(root) {\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.Imports.Get(root)\n\t\t\t\tif !d.HasSubpackage(subpkg) {\n\t\t\t\t\tmsg.Info(\"--> Adding sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, pa := range testSortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot, subpkg := util.NormalizeName(n)\n\n\t\tif config.Imports.Has(root) && root != config.Name {\n\t\t\tmsg.Debug(\"--> Found test reference to %s already listed as an import\", n)\n\t\t} else if !config.DevImports.Has(root) && root != config.Name {\n\t\t\tmsg.Info(\"--> Found test reference to %s\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.DevImports = append(config.DevImports, d)\n\t\t} else if config.DevImports.Has(root) {\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.DevImports.Get(root)\n\t\t\t\tif !d.HasSubpackage(subpkg) {\n\t\t\t\t\tmsg.Info(\"--> Adding test sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(config.Imports) == importLen && importLen != 0 {\n\t\tmsg.Info(\"--> Code scanning found no additional imports\")\n\t}\n\n\treturn config\n}", "func (module *SdkLibraryImport) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {\n\tfor apiScope, scopeProperties := range module.scopeProperties {\n\t\tif len(scopeProperties.Jars) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Add dependencies to the prebuilt stubs library\n\t\tctx.AddVariationDependencies(nil, apiScope.stubsTag, android.PrebuiltNameFromSource(module.stubsLibraryModuleName(apiScope)))\n\n\t\tif len(scopeProperties.Stub_srcs) > 0 {\n\t\t\t// Add dependencies to the prebuilt stubs source library\n\t\t\tctx.AddVariationDependencies(nil, apiScope.stubsSourceTag, android.PrebuiltNameFromSource(module.stubsSourceModuleName(apiScope)))\n\t\t}\n\t}\n}", "func updateDeps(repo string, deps *[]u.Dependency, depChangeList *[]u.Dependency) error {\n\tfor _, dep := range *deps {\n\t\tif dep.File == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := u.UpdateKeyValueInFile(dep.File, dep.Name, dep.LastStableSHA); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif repo != proxyRepo {\n\t\t\tcontinue\n\t\t}\n\t\tif err := extraUpdateForProxy(dep.File, dep.Name, dep.LastStableSHA); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif repo != istioRepo || len(*hub) == 0 {\n\t\treturn nil\n\t}\n\n\targs := \"\"\n\tfor _, updatedDep := range *depChangeList {\n\t\tswitch updatedDep.RepoName {\n\t\tcase mixerRepo:\n\t\t\targs += fmt.Sprintf(\"-x %s,%s \", *hub, updatedDep.LastStableSHA)\n\t\tcase pilotRepo:\n\t\t\tistioctlURL := generateArtifactURL(pilotRepo, updatedDep.LastStableSHA, istioctlSuffix)\n\t\t\tdebianURL := generateArtifactURL(pilotRepo, updatedDep.LastStableSHA, debianSuffix)\n\t\t\targs += fmt.Sprintf(\"-p %s,%s -i %s -P %s \", *hub, updatedDep.LastStableSHA, istioctlURL, debianURL)\n\t\tcase authRepo:\n\t\t\tdebianURL := generateArtifactURL(authRepo, updatedDep.LastStableSHA, debianSuffix)\n\t\t\targs += fmt.Sprintf(\"-c %s,%s -A %s \", *hub, updatedDep.LastStableSHA, debianURL)\n\t\tcase proxyRepo:\n\t\t\tdebianURL := generateArtifactURL(proxyRepo, updatedDep.LastStableSHA, debianSuffix)\n\t\t\targs += fmt.Sprintf(\"-r %s -E %s \", updatedDep.LastStableSHA, debianURL)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown dependency: %s\", updatedDep.Name)\n\t\t}\n\t}\n\tcmd := fmt.Sprintf(\"./install/updateVersion.sh %s\", args)\n\t_, err := u.Shell(cmd)\n\treturn err\n}", "func Setup() Dependencies {\n\tviper.SetConfigFile(\"./logfairy.yaml\")\n\tviper.SetConfigType(\"yaml\")\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.Fatal(\"no config file found\")\n\t}\n\n\tservice := srv.New(viper.GetString(\"client.base_url\"), viper.GetInt(\"client.timeout\"))\n\tgraylog := api.New(service, os.Getenv(\"GRAYLOG_USERNAME\"), os.Getenv(\"GRAYLOG_PASSWORD\"))\n\n\treturn Dependencies{\n\t\tDashboardClient: dapi.New(service, &graylog),\n\t\tStreamClient: sapi.New(service, &graylog),\n\t\tWidgetClient: wapi.New(service, &graylog),\n\t}\n}", "func (o *V0037JobProperties) SetDependency(v string) {\n\to.Dependency = &v\n}", "func (r *Alarm_MetricDataQuery) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}", "func dependencgInjections() (ReqProcessor, PropProcessor) {\n\t// get a single DB connection/pool\n\tdb, err := NewDBClient()\n\tif err != nil {\n\t\tpanic(\"Unable to get a DB connection\")\n\t}\n\n\trAlgo := NewReqMatchingAlgo()\n\tpAlgo := NewPropMatchingAlgo()\n\n\treqProcessor := NewReqProcessor(db, rAlgo)\n\tpropProcessor := NewPropProcessor(db, pAlgo)\n\n\t// Here we use r and p to perform the usecasaes\n\t// API handler/cotrollers will have access to r and p to perform the usecases\n\treturn reqProcessor, propProcessor\n}", "func (r *AWSEC2SecurityGroup_Egress) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}", "func SetupUsecaseDependencies(spec *testcase.Spec) {\n\tpostgres_repos.SetupPostgresStorageVar(spec)\n}", "func (r *AWSCloudWatchAlarm_MetricDataQuery) SetDependsOn(dependencies []string) {\n\tr._dependsOn = dependencies\n}", "func updateDependenciesOf(repo string) error {\n\tlog.Printf(\"Updating dependencies of %s\\n\", repo)\n\tsaveDir, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\trepoDir, err := u.CloneRepoCheckoutBranch(githubClnt, repo, *baseBranch, \"\", \"go/src/istio.io\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err = os.Chdir(saveDir); err != nil {\n\t\t\tlog.Fatalf(\"Error during chdir: %v\\n\", err)\n\t\t}\n\t\tif err = u.RemoveLocalRepo(\"go\"); err != nil {\n\t\t\tlog.Fatalf(\"Error during clean up: %v\\n\", err)\n\t\t}\n\t}()\n\tdeps, err := u.DeserializeDeps(istioDepsFile)\n\t// Don't fail if istio.deps file does not exist in the repo.\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tlog.Printf(\"%s repo does not have istio.deps file to update.\", repo)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tfingerPrint, depChangeList, err := updateDepSHAGetFingerPrint(repo, &deps)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbranch := \"autoUpdateDeps_\" + fingerPrint\n\n\t// First try to cleanup old PRs\n\tif err = githubClnt.CloseIdlePullRequests(\n\t\tprTitlePrefix, repo, *baseBranch); err != nil {\n\t\tlog.Printf(\"error while closing idle PRs: %v\\n\", err)\n\t}\n\t// If the same branch still exists (which means it's not old enough), leave it there and don't do anything in this cycle\n\texists, err := githubClnt.ExistBranch(repo, branch)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\tlog.Printf(\"Branch %s exists\", branch)\n\t\treturn nil\n\t}\n\n\tif _, err = u.Shell(\"git checkout -b \" + branch); err != nil {\n\t\treturn err\n\t}\n\tif err = updateDeps(repo, &deps, &depChangeList); err != nil {\n\t\treturn err\n\t}\n\tif err = u.SerializeDeps(istioDepsFile, &deps); err != nil {\n\t\treturn err\n\t}\n\tif repo == istioRepo {\n\t\tgoPath := path.Join(repoDir, \"../../..\")\n\t\tenv := \"GOPATH=\" + goPath\n\t\tupdateCommand := \"; go get -u github.com/golang/dep/cmd/dep; dep ensure -update istio.io/api\"\n\t\tif _, err = u.Shell(env + updateCommand); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif *updateExtDep {\n\t\t\t// while depend update can introduce new changes,\n\t\t\t// introduce them only when requested\n\t\t\tif _, err = u.Shell(\"make depend.update\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif _, err = u.Shell(\"git diff -w --quiet HEAD\"); err == nil {\n\t\t// diff exited without error, nothing to commit or only whitespace changes\n\t\tlog.Printf(\"%s is up to date. No commits are made.\", repo)\n\t\treturn nil\n\t}\n\t// git is dirty so commit\n\tif err = u.CreateCommitPushToRemote(branch, \"Update_Dependencies\"); err != nil {\n\t\treturn err\n\t}\n\tprTitle := prTitlePrefix + repo\n\tpr, err := githubClnt.CreatePullRequest(prTitle, prBody, \"\", branch, *baseBranch, repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := githubClnt.AddAutoMergeLabelsToPR(repo, pr); err != nil {\n\t\treturn err\n\t}\n\treturn githubClnt.AddlabelsToPR(repo, pr, dependencyUpdateLabel)\n}", "func ResolveDependencies(m meta.RESTMapper, objects []unstructuredv1.Unstructured, uids []types.UID) (NodeMap, error) {\n\treturn resolveDeps(m, objects, uids, true)\n}", "func (fastenJSON *JSON) AddDependency(target *JSON) {\n\tif target.Product == \"\" {\n\t\treturn\n\t}\n\n\tfor _, inner := range fastenJSON.Depset {\n\t\tfor _, dependency := range inner {\n\t\t\tif dependency.Product == target.Product {\n\t\t\t\tfound := false\n\t\t\t\tif target.Version == \"\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor _, constraint := range dependency.Constraints {\n\t\t\t\t\tif constraint == target.Version {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif found {\n\t\t\t\t\treturn\n\t\t\t\t} else if target.Version != \"\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(fastenJSON.Depset) == 0 {\n\t\tfastenJSON.Depset = append(fastenJSON.Depset, []Dependency{})\n\t}\n\tfastenJSON.Depset[0] = append(fastenJSON.Depset[0], Dependency{\n\t\tProduct: target.Product,\n\t\tForge: \"cratesio\",\n\t\tConstraints: []string{\"[\" + target.Version + \"]\"},\n\t})\n}", "func (r *AWSCloudWatchAlarm_MetricDataQuery) DependsOn() []string {\n\treturn r._dependsOn\n}", "func (r *Alarm_MetricDataQuery) DependsOn() []string {\n\treturn r._dependsOn\n}", "func (r *AWSAmplifyDomain_SubDomainSetting) DependsOn() []string {\n\treturn r._dependsOn\n}", "func (r *runtime) buildServiceDependency() {\n\t// create replica channel mgr.\n\tcm := newChannelManager(r.ctx, rpc.NewClientStreamFactory(r.ctx, r.node, rpc.GetBrokerClientConnFactory()), r.stateMgr)\n\n\ttaskMgr := query.NewTaskManager(r.queryPool, linmetric.BrokerRegistry)\n\t// close connections in connection-manager\n\tr.factory.taskClient.SetTaskReceiver(taskMgr)\n\n\ts := srv{\n\t\tchannelManager: cm,\n\t\ttaskManager: taskMgr,\n\t\ttransportManager: query.NewTransportManager(r.factory.taskClient, r.factory.taskServer, linmetric.BrokerRegistry),\n\t}\n\tr.srv = s\n}", "func (r *AWSCloudFrontDistribution_Origin) DependsOn() []string {\n\treturn r._dependsOn\n}", "func getDependenciesEnvVarVarMap(deployConfig deploy.Config) (map[string]string, error) {\n\tdependencyVars := map[string]string{}\n\tfor dependencyName := range deployConfig.AppContext.GetRemoteDependencies() {\n\t\tserviceData, err := getDependencyServiceData(dependencyName, deployConfig)\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\t\tserviceDataEnvVar, err := createEnvVarString(map[string]string{\"SERVICE_DATA\": serviceData})\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\t\tdependencyVars[fmt.Sprintf(\"%s_env_vars\", dependencyName)] = serviceDataEnvVar\n\t}\n\treturn dependencyVars, nil\n}", "func (config *Config) FetchAllDependencies(force bool) error {\n\turls := []string{}\n\tfor url := range config.Dependencies {\n\t\turls = append(urls, url)\n\t}\n\tsort.Strings(urls)\n\n\ttitle := \"Checking dependencies\"\n\tif force {\n\t\ttitle = \"Updating dependencies\"\n\t}\n\n\treturn config.UI.InMeasuredFrame(title, func(ctx *gluey.Ctx, frame *gluey.Frame) error {\n\t\tgroup := ctx.NewSpinGroup()\n\t\tfor _, url := range urls {\n\t\t\tdepurl := url\n\t\t\tgroup.Go(depurl, func() error {\n\t\t\t\treturn config.addDep(depurl, force)\n\t\t\t})\n\t\t}\n\t\treturn config.UI.Debreif(group.Wait())\n\t})\n}", "func (s *status) GetDependencies() *lcm.CRStatusCollection {\n\treturn s.collection\n}", "func checkDeploymentDependencies(bc *buildv1.BuildConfig) (err error) {\n\tif bc == nil {\n\t\treturn fmt.Errorf(\"Impossible to create the DeploymentConfig without a reference to a the service BuildConfig\")\n\t}\n\n\treturn nil\n}", "func TestDependencySteps(t *testing.T) {\n\tintegration.ProgramTest(t, &integration.ProgramTestOptions{\n\t\tDir: \"step1\",\n\t\tDependencies: []string{\"@pulumi/pulumi\"},\n\t\tQuick: true,\n\t\tEditDirs: []integration.EditDir{\n\t\t\t{\n\t\t\t\tDir: \"step2\",\n\t\t\t\tAdditive: true,\n\t\t\t},\n\t\t},\n\t})\n}", "func (s *memoryStorage) GetDependencies(srvFilter ...string) ([]tracer.Dependencies, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif len(srvFilter) == 0 {\n\t\tsrvFilter = make([]string, 0)\n\t\tfor _, srvName := range s.services {\n\t\t\tsrvFilter = append(srvFilter, srvName)\n\t\t}\n\t}\n\n\t// Sort service names alphabetically\n\tsort.Strings(srvFilter)\n\n\treplyCount := len(srvFilter)\n\tserviceDeps := make([]tracer.Dependencies, replyCount)\n\tfor index, srvName := range srvFilter {\n\t\tdep, exists := s.serviceDeps[srvName]\n\t\tif !exists {\n\t\t\tdep = &tracer.Dependencies{\n\t\t\t\tService: srvName,\n\t\t\t\tDependencies: make([]string, 0),\n\t\t\t}\n\t\t}\n\t\tserviceDeps[index] = *dep\n\t}\n\n\treturn serviceDeps, nil\n\n}", "func (h *descriptorHandler) dependencies(key string, value proto.Message) (deps []kvs.Dependency) {\n\tif h.descriptor == nil || h.descriptor.Dependencies == nil {\n\t\treturn\n\t}\n\t// TODO: check that label is unique for each KV pair, throw panic if not (?)\n\tdefer trackDescMethod(h.descriptor.Name, \"Dependencies\")()\n\treturn h.descriptor.Dependencies(key, value)\n}", "func (d Dependency) DoRecover() (interface{}, error) {\n\tdLog.V(utils.Debug).Info(\"can not recover dependency now\", \"name\", d.Name, \"version\", d.Version)\n\treturn \"\", nil\n}", "func HelmDepE(t *testing.T, options *helm.Options, chartDir string) error {\n\tvar buildOrUpdate string\n\tif files.FileExists(chartDir + \"/requirements.lock\") {\n\t\tbuildOrUpdate = \"build\"\n\t} else {\n\t\tbuildOrUpdate = \"update\"\n\t}\n\n\t_, err := helm.RunHelmCommandAndGetOutputE(t, options, \"dependency\", buildOrUpdate, chartDir)\n\treturn err\n}", "func (s *SimplePublishNode) SetDependency(d *int64) {\n\ts.dependency = d\n}", "func Install(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {\n\tlock := p.Get(\"lock\", nil).(*cfg.Lockfile)\n\tconf := p.Get(\"conf\", nil).(*cfg.Config)\n\tforce := p.Get(\"force\", true).(bool)\n\thome := p.Get(\"home\", \"\").(string)\n\tcache := p.Get(\"cache\", false).(bool)\n\tcacheGopath := p.Get(\"cacheGopath\", false).(bool)\n\tuseGopath := p.Get(\"useGopath\", false).(bool)\n\n\tcwd, err := VendorPath(c)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Create a config setup based on the Lockfile data to process with\n\t// existing commands.\n\tnewConf := &cfg.Config{}\n\tnewConf.Name = conf.Name\n\n\tnewConf.Imports = make(cfg.Dependencies, len(lock.Imports))\n\tfor k, v := range lock.Imports {\n\t\tnewConf.Imports[k] = &cfg.Dependency{\n\t\t\tName: v.Name,\n\t\t\tReference: v.Version,\n\t\t\tRepository: v.Repository,\n\t\t\tVcsType: v.VcsType,\n\t\t\tSubpackages: v.Subpackages,\n\t\t\tArch: v.Arch,\n\t\t\tOs: v.Os,\n\t\t}\n\t}\n\n\tnewConf.DevImports = make(cfg.Dependencies, len(lock.DevImports))\n\tfor k, v := range lock.DevImports {\n\t\tnewConf.DevImports[k] = &cfg.Dependency{\n\t\t\tName: v.Name,\n\t\t\tReference: v.Version,\n\t\t\tRepository: v.Repository,\n\t\t\tVcsType: v.VcsType,\n\t\t\tSubpackages: v.Subpackages,\n\t\t\tArch: v.Arch,\n\t\t\tOs: v.Os,\n\t\t}\n\t}\n\n\tnewConf.DeDupe()\n\n\tif len(newConf.Imports) == 0 {\n\t\tInfo(\"No dependencies found. Nothing installed.\\n\")\n\t\treturn false, nil\n\t}\n\n\t// for _, dep := range newConf.Imports {\n\t// \tif err := VcsUpdate(dep, cwd, home, force, cache, cacheGopath, useGopath); err != nil {\n\t// \t\tWarn(\"Update failed for %s: %s\\n\", dep.Name, err)\n\t// \t}\n\t// }\n\n\tdone := make(chan struct{}, concurrentWorkers)\n\tin := make(chan *cfg.Dependency, concurrentWorkers)\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < concurrentWorkers; i++ {\n\t\tgo func(ch <-chan *cfg.Dependency) {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase dep := <-ch:\n\t\t\t\t\tif err := VcsUpdate(dep, cwd, home, force, cache, cacheGopath, useGopath); err != nil {\n\t\t\t\t\t\tWarn(\"Update failed for %s: %s\\n\", dep.Name, err)\n\t\t\t\t\t}\n\t\t\t\t\twg.Done()\n\t\t\t\tcase <-done:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}(in)\n\t}\n\n\tfor _, dep := range newConf.Imports {\n\t\twg.Add(1)\n\t\tin <- dep\n\t}\n\n\twg.Wait()\n\t// Close goroutines setting the version\n\tfor i := 0; i < concurrentWorkers; i++ {\n\t\tdone <- struct{}{}\n\t}\n\n\treturn newConf, nil\n}" ]
[ "0.6741954", "0.63648534", "0.6255764", "0.6234734", "0.61984146", "0.61395365", "0.6014456", "0.5983391", "0.5905607", "0.586772", "0.5856507", "0.5838749", "0.58284426", "0.57780486", "0.57302", "0.57122", "0.56217706", "0.558046", "0.5567231", "0.5549555", "0.5499117", "0.5440008", "0.5424036", "0.5390047", "0.53711414", "0.5352768", "0.5349576", "0.530761", "0.5213482", "0.519057", "0.5184695", "0.5155505", "0.51264036", "0.51084554", "0.50939", "0.5083174", "0.50032294", "0.49786144", "0.4974968", "0.49680853", "0.4962014", "0.49549377", "0.49433798", "0.49364865", "0.49088898", "0.48988235", "0.48967832", "0.4863567", "0.48597145", "0.48547223", "0.48265266", "0.48049745", "0.47978467", "0.47913972", "0.47888324", "0.47830406", "0.47752163", "0.4750812", "0.4739375", "0.47352287", "0.473507", "0.47292164", "0.47087997", "0.47058466", "0.46865958", "0.4682006", "0.4673816", "0.46694696", "0.46689218", "0.46386912", "0.46367207", "0.4631461", "0.46305963", "0.4629426", "0.46276933", "0.4624224", "0.46169958", "0.46161738", "0.46035904", "0.45934778", "0.45862103", "0.45855814", "0.45853472", "0.45816997", "0.45775652", "0.45631796", "0.4557317", "0.45553294", "0.45343134", "0.4524313", "0.45186135", "0.45159855", "0.45154053", "0.45062447", "0.4503379", "0.44954515", "0.4494627", "0.44866782", "0.44865322", "0.44834763" ]
0.78393555
0
/ BrowseAvailabilityZones Method for BrowseAvailabilityZones
func (a *AmazonConnectionsApiService) BrowseAvailabilityZones(ctx _context.Context, amazonConnectionId string) ApiBrowseAvailabilityZonesRequest { return ApiBrowseAvailabilityZonesRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseAvailabilityZonesExecute(r ApiBrowseAvailabilityZonesRequest) (RegionsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue RegionsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseAvailabilityZones\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/availabilityZones\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client DnsClient) listZones(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/zones\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListZonesResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func listURL(c *gophercloud.ServiceClient) string {\n\treturn c.ServiceURL(\"os-availability-zone\")\n}", "func (s stack) ListAvailabilityZones(ctx context.Context) (_ map[string]bool, ferr fail.Error) {\n\tif valid.IsNil(s) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\n\treturn nil, fail.NotImplementedError(\"implement me\")\n}", "func GetZones(sess *session.Session) (*ec2.DescribeAvailabilityZonesOutput, error) {\n svc := ec2.New(sess)\n\n // snippet-start:[ec2.go.regions_and_zones.zones]\n resultAvalZones, err := svc.DescribeAvailabilityZones(nil)\n // snippet-end:[ec2.go.regions_and_zones.zones]\n if err != nil {\n return nil, err\n }\n\n return resultAvalZones, nil\n}", "func (c *Client) DescribeZones(request *DescribeZonesRequest) (response *DescribeZonesResponse, err error) {\n return c.DescribeZonesWithContext(context.Background(), request)\n}", "func AvailabilityZones(project, region string) ([]string, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)\n\tdefer cancel()\n\n\tssn, err := gcpconfig.GetSession(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get session\")\n\t}\n\n\tsvc, err := compute.NewService(ctx, option.WithCredentials(ssn.Credentials))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create compute service\")\n\t}\n\n\tregionURL := fmt.Sprintf(\"https://www.googleapis.com/compute/v1/projects/%s/regions/%s\",\n\t\tproject, region)\n\treq := svc.Zones.List(project).Filter(fmt.Sprintf(\"(region eq %s) (status eq UP)\", regionURL))\n\n\tvar zones []string\n\tif err := req.Pages(ctx, func(page *compute.ZoneList) error {\n\t\tfor _, z := range page.Items {\n\t\t\tzones = append(zones, z.Name)\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to list zones\")\n\t}\n\tif len(zones) == 0 {\n\t\treturn nil, errors.New(\"no zone was found\")\n\t}\n\n\tsort.Strings(zones)\n\treturn zones, nil\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := baseURL(client)\n\tif opts != nil {\n\t\tquery, err := opts.ToZoneListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn ZonePage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func listInfo() ([]*RegionInfo, error) {\n // ex-1)\n // /cloud-info-spaces/regions/aws_region01/AWS/region [ap-northeast-2]\n // ex-2)\n // /cloud-info-spaces/regions/gcp_region02/GCP/region [us-east1]\n // /cloud-info-spaces/regions/gcp_region02/GCP/zone [us-east1-c]\n\n\n key := \"/cloud-info-spaces/regions\"\n keyValueList, err := store.GetList(key, true)\n if err != nil {\n return nil, err\n }\n\n var regionInfoList []*RegionInfo\n\tvar inKeyValueList []icbs.KeyValue\n\tprevRegionName := \"\"\n\tprevProviderName := \"\"\n for _, kv := range keyValueList {\n\n\t\tregionName := utils.GetNodeValue(kv.Key, 3)\n\t\tproviderName := utils.GetNodeValue(kv.Key, 4)\n\n\t\tif prevRegionName==\"\" || regionName == prevRegionName {\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t} else {\n\t\t\t// insert prev RegionInfo\n\t\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tinKeyValueList = nil\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t}\n\n }\n\n\tif len(keyValueList) > 0 {\n\t\t// insert last RegionInfo\n\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\t}\n\n return regionInfoList, nil\n}", "func (a *AzureInfoer) GetZones(region string) ([]string, error) {\n\tlogger := a.log.WithFields(map[string]interface{}{\"region\": region})\n\tlogger.Debug(\"getting zones\")\n\n\tskusResultPage, err := a.skusClient.List(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tzonesMap := make(map[string]string)\n\tzones := make([]string, 0)\n\n\tfor _, sku := range skusResultPage.Values() {\n\t\tfor _, locationInfo := range *sku.LocationInfo {\n\t\t\tif strings.ToLower(*locationInfo.Location) == region {\n\t\t\t\t// retrieve zones per instance type\n\t\t\t\tfor _, zone := range *locationInfo.Zones {\n\t\t\t\t\tzonesMap[zone] = \"\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor zone := range zonesMap {\n\t\tzones = append(zones, zone)\n\t}\n\n\tlogger.Debug(\"found zones\", map[string]interface{}{\"numberOfZones\": len(zones)})\n\n\treturn zones, nil\n}", "func (client DnsClient) ListZones(ctx context.Context, request ListZonesRequest) (response ListZonesResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listZones, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListZonesResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListZonesResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListZonesResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListZonesResponse\")\n\t}\n\treturn\n}", "func (a *Client) ListOpenstackAvailabilityZones(params *ListOpenstackAvailabilityZonesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackAvailabilityZonesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackAvailabilityZonesParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackAvailabilityZones\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/providers/openstack/availabilityzones\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackAvailabilityZonesReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackAvailabilityZonesOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackAvailabilityZonesDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (z *zones) List() ([]dnsprovider.Zone, error) {\n\tsnapshot := z.dnsView.Snapshot()\n\n\tvar zones []dnsprovider.Zone\n\tzoneInfos := snapshot.ListZones()\n\tfor i := range zoneInfos {\n\t\tzones = append(zones, &zone{dnsView: z.dnsView, zoneInfo: zoneInfos[i]})\n\t}\n\treturn zones, nil\n}", "func ListZones(r *route53.Route53) {\n\tresp, err := r.ListHostedZones(&route53.ListHostedZonesRequest{})\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(*resp)\n}", "func ListZones(ctx context.Context, tenantID int, offset, limit int) (*handlers.ZoneList, error) {\n\treq := handlers.ListZonesRequest{\n\t\tTenantID: tenantID,\n\t\tPaging: database.Paging{\n\t\t\tLimit: limit,\n\t\t\tOffset: offset,\n\t\t},\n\t\tZoneOptions: database.ZoneOptions{\n\t\t\tWithPlaces: true,\n\t\t},\n\t}\n\tresp := handlers.ZoneList{}\n\terr := jsonConn.RequestWithContext(ctx, \"zones.list\", &req, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (a *AzureInfoer) GetZones(region string) ([]string, error) {\n\treturn []string{region}, nil\n}", "func (api *powerdnsProvider) ListZones() ([]string, error) {\n\tvar result []string\n\tmyZones, err := api.client.Zones().ListZones(context.Background(), api.ServerName)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tfor _, zone := range myZones {\n\t\tresult = append(result, zone.Name)\n\t}\n\treturn result, nil\n}", "func (c *TestClient) ListZones(project string, opts ...ListCallOption) ([]*compute.Zone, error) {\n\tif c.ListZonesFn != nil {\n\t\treturn c.ListZonesFn(project, opts...)\n\t}\n\treturn c.client.ListZones(project, opts...)\n}", "func (s *FastDNSv2Service) ListZones(ctx context.Context, opt *ZoneListOptions) (*ZoneList, *Response, error) {\n\tu := fmt.Sprintf(\"config-dns/v2/zones\")\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar zones *ZoneList\n\tresp, err := s.client.Do(ctx, req, &zones)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn zones, resp, nil\n}", "func (p *Provider) ListZones() ([]string, error) {\n mZones, err := p.listMZones()\n if err != nil {\n return nil, fmt.Errorf(\"couldn't retrieve zone information from autodns, see: %v\", err)\n }\n\n zones := make([]string, 0)\n\n for _, mZone := range mZones {\n if mZone.Origin == nil {\n logrus.Warnf(\"found zone without origin, since we use it as unique identifier, this shouldn't have happend, see: %#v\", mZone)\n continue\n }\n\n zones = append(zones, *mZone.Origin)\n }\n\n return zones, nil\n}", "func (a *Client) ListOpenstackAvailabilityZonesNoCredentials(params *ListOpenstackAvailabilityZonesNoCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackAvailabilityZonesNoCredentialsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackAvailabilityZonesNoCredentialsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackAvailabilityZonesNoCredentials\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/projects/{project_id}/dc/{dc}/clusters/{cluster_id}/providers/openstack/availabilityzones\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackAvailabilityZonesNoCredentialsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackAvailabilityZonesNoCredentialsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackAvailabilityZonesNoCredentialsDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func GetZones(full bool, tenant string) []Zone {\n\ttenantStr := func() string {\n\t\tif len(tenant) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn \"-tenant=\" + tenant\n\t}()\n\tfullStr := func() string {\n\t\tif full {\n\t\t\treturn \"-full\"\n\t\t}\n\t\treturn \"\"\n\t}()\n\n\toutput := RunCmd(fmt.Sprintf(\"%s api -fetch-zone-apps %s %s\", ActlPath, fullStr, tenantStr))\n\tlistOfZones := []Zone{}\n\tyaml.Unmarshal([]byte(output), &listOfZones)\n\treturn listOfZones\n}", "func ExtractAvailabilityZones(r pagination.Page) ([]AvailabilityZone, error) {\n\tvar a struct {\n\t\tAvailabilityZone []AvailabilityZone `json:\"availability_zones\"`\n\t}\n\terr := (r.(AvailabilityZonePage)).ExtractInto(&a)\n\treturn a.AvailabilityZone, err\n}", "func (a *Client) ListOpenstackAvailabilityZonesNoCredentialsV2(params *ListOpenstackAvailabilityZonesNoCredentialsV2Params, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackAvailabilityZonesNoCredentialsV2OK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackAvailabilityZonesNoCredentialsV2Params()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackAvailabilityZonesNoCredentialsV2\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v2/projects/{project_id}/clusters/{cluster_id}/providers/openstack/availabilityzones\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackAvailabilityZonesNoCredentialsV2Reader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackAvailabilityZonesNoCredentialsV2OK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackAvailabilityZonesNoCredentialsV2Default)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (c *Client) ListFlavorZones(args *ListFlavorZonesArgs) (*ListZonesResult, error) {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn nil, jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ListFlavorZones(c, body)\n}", "func (a *Client) ListTransportZones(params *ListTransportZonesParams, authInfo runtime.ClientAuthInfoWriter) (*ListTransportZonesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListTransportZonesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListTransportZones\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/transport-zones\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListTransportZonesReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ListTransportZonesOK), nil\n\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := listURL(client)\n\tif opts != nil {\n\t\tquery, err := opts.ToRegionListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn RegionPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func (a *Client) ListProvidersByRegionShort(params *ListProvidersByRegionParams, authInfo runtime.ClientAuthInfoWriter) (*ListProvidersByRegionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListProvidersByRegionParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListProvidersByRegion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/dsmcontroller/public/providers/regions/{region}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListProvidersByRegionReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *ListProvidersByRegionOK:\n\t\treturn v, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func (c *Client) ListScanTimezones(httpClient *http.Client) (ScanTimezones, error) {\n\tc.debugln(\"ScanTimezones(): Building scan timezone list URL\")\n\turl := fmt.Sprintf(\"https://%s:%s/scans/timezones\", c.ip, c.port)\n\n\tstatusCode, body, err := c.get(httpClient, url)\n\tif err != nil {\n\t\treturn ScanTimezones{}, err\n\t}\n\n\tswitch statusCode {\n\tcase 200:\n\t\tvar scanTimezones ScanTimezones\n\t\terr = json.Unmarshal(body, &scanTimezones)\n\t\tif err != nil {\n\t\t\treturn ScanTimezones{}, err\n\t\t}\n\t\tc.debugln(\"ScanTimezones(): Successfully retrieved list of scan timezones.\")\n\t\treturn scanTimezones, nil\n\tdefault:\n\t\tvar err ErrorResponse\n\t\tunmarshalError := json.Unmarshal(body, &err)\n\t\tif unmarshalError != nil {\n\t\t\treturn ScanTimezones{}, unmarshalError\n\t\t}\n\t\tc.debugln(\"ScanTimezones(): Scan timezones list could not be retrieved.\")\n\t\treturn ScanTimezones{}, fmt.Errorf(\"%s\", err.Error)\n\t}\n}", "func (e Endpoints) ListRegions(ctx context.Context, token string) (regions []registry.Region, err error) {\n\trequest := ListRegionsRequest{Token: token}\n\tresponse, err := e.ListRegionsEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListRegionsResponse).Regions, response.(ListRegionsResponse).Err\n}", "func (z *FakeZoneLister) ListZones(_ utils.NodeConditionPredicate) ([]string, error) {\n\treturn z.Zones, nil\n}", "func (client IdentityClient) listRegions(ctx context.Context) (common.OCIResponse, error) {\n\thttpRequest := common.MakeDefaultHTTPRequest(http.MethodGet, \"/regions\")\n\tvar err error\n\n\tvar response ListRegionsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func ListTimezonesHandler(w http.ResponseWriter, r *http.Request) {\n\ttimezones, err := database.GetAllTimezones()\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresults, _ := json.Marshal(timezones)\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(results)\n}", "func (s *InMemoryInstanceTypeStore) GetZones(provider, service, region string) ([]string, error) {\n\treturn []string{}, nil\n}", "func (s *AppsServiceOp) ListRegions(ctx context.Context) ([]*AppRegion, *Response, error) {\n\tpath := fmt.Sprintf(\"%s/regions\", appsBasePath)\n\treq, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\troot := new(appRegionsRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn root.Regions, resp, nil\n}", "func GetZones(client *Client, userHome *UserHome) ([]*Zone, error) {\n\tresp, err := client.Request(http.MethodGet, apiURL(\"homes/%d/zones\", userHome.ID), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := isError(resp); err != nil {\n\t\treturn nil, fmt.Errorf(\"tado° API error: %w\", err)\n\t}\n\n\tzones := make([]*Zone, 0)\n\tif err := json.NewDecoder(resp.Body).Decode(&zones); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode tado° API response: %w\", err)\n\t}\n\n\treturn zones, nil\n}", "func (s *API) ListDNSZones(req *ListDNSZonesRequest, opts ...scw.RequestOption) (*ListDNSZonesResponse, error) {\n\tvar err error\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"domain\", req.Domain)\n\tparameter.AddToQuery(query, \"dns_zone\", req.DNSZone)\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/domain/v2alpha2/dns-zones\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDNSZonesResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (c *PDNSAPIClient) ListZones() (zones []pgo.Zone, resp *http.Response, err error) {\n\tfor i := 0; i < retryLimit; i++ {\n\t\tzones, resp, err = c.client.ZonesApi.ListZones(c.authCtx, defaultServerID)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Unable to fetch zones %v\", err)\n\t\t\tlog.Debugf(\"Retrying ListZones() ... %d\", i)\n\t\t\ttime.Sleep(retryAfterTime * (1 << uint(i)))\n\t\t\tcontinue\n\t\t}\n\t\treturn zones, resp, err\n\t}\n\n\tlog.Errorf(\"Unable to fetch zones. %v\", err)\n\treturn zones, resp, err\n}", "func (a *Amazon) AvailabilityZones() (availabiltyZones []string) {\n\tif a.availabilityZones != nil {\n\t\treturn *a.availabilityZones\n\t}\n\n\tsubnets := a.tarmak.Cluster().Subnets()\n\tzones := make(map[string]bool)\n\n\tfor _, subnet := range subnets {\n\t\tzones[subnet.Zone] = true\n\t}\n\n\ta.availabilityZones = &availabiltyZones\n\n\tfor zone, _ := range zones {\n\t\tavailabiltyZones = append(availabiltyZones, zone)\n\t}\n\n\tsort.Strings(availabiltyZones)\n\n\treturn availabiltyZones\n}", "func (s *EcsService) DescribeZone(id string) (zone map[string]interface{}, err error) {\n\tvar response map[string]interface{}\n\tconn, err := s.client.NewEcsClient()\n\tif err != nil {\n\t\treturn nil, WrapError(err)\n\t}\n\taction := \"DescribeZones\"\n\trequest := map[string]interface{}{\n\t\t\"RegionId\": s.client.RegionId,\n\t}\n\truntime := util.RuntimeOptions{}\n\truntime.SetAutoretry(true)\n\tresponse, err = conn.DoRequest(StringPointer(action), nil, StringPointer(\"POST\"), StringPointer(\"2014-05-26\"), StringPointer(\"AK\"), nil, request, &util.RuntimeOptions{})\n\tif err != nil {\n\t\terr = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)\n\t\treturn zone, err\n\t}\n\taddDebug(action, response, request)\n\tv, err := jsonpath.Get(\"$.Zones.Zone\", response)\n\tif err != nil {\n\t\treturn zone, WrapErrorf(err, FailedGetAttributeMsg, id, \"$\", response)\n\t}\n\n\tif len(v.([]interface{})) < 1 {\n\t\treturn zone, WrapError(Error(\"There is no any availability zone in region %s.\", s.client.RegionId))\n\t}\n\n\tzoneIds := []string{}\n\tfor _, z := range v.([]interface{}) {\n\t\ttmp := z.(map[string]interface{})\n\t\tif tmp[\"ZoneId\"].(string) == id {\n\t\t\treturn tmp, nil\n\t\t}\n\t\tzoneIds = append(zoneIds, tmp[\"ZoneId\"].(string))\n\t}\n\treturn zone, WrapError(Error(\"availability_zone %s not exists in region %s, all zones are %s\", id, s.client.RegionId, zoneIds))\n}", "func (s *API) ListDNSZones(req *ListDNSZonesRequest, opts ...scw.RequestOption) (*ListDNSZonesResponse, error) {\n\tvar err error\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\tparameter.AddToQuery(query, \"project_id\", req.ProjectID)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\tparameter.AddToQuery(query, \"domain\", req.Domain)\n\tparameter.AddToQuery(query, \"dns_zone\", req.DNSZone)\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/domain/v2beta1/dns-zones\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDNSZonesResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func getNodesOfZone(nodeList *v1.NodeList, availabilityZone string) []string {\n\tvar nodeNames []string\n\tfor _, node := range nodeList.Items {\n\t\tnodeLabels := node.Labels\n\t\tif nodeLabels[zoneKey] == availabilityZone {\n\t\t\tnodeNames = append(nodeNames, node.Name)\n\t\t}\n\t}\n\treturn nodeNames\n}", "func (w *ServerInterfaceWrapper) GetZones(ctx echo.Context) error {\n\tvar err error\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.GetZones(ctx)\n\treturn err\n}", "func (azc *azureZonesClient) Get(ctx context.Context, spec azure.ResourceSpecGetter) (result interface{}, err error) {\n\tctx, _, done := tele.StartSpanWithLogger(ctx, \"privatedns.azureZonesClient.Get\")\n\tdefer done()\n\tzone, err := azc.privatezones.Get(ctx, spec.ResourceGroupName(), spec.ResourceName())\n\tif err != nil {\n\t\treturn privatedns.PrivateZone{}, err\n\t}\n\treturn zone, nil\n}", "func (a *Client) DescribeRuntimeProviderZones(params *DescribeRuntimeProviderZonesParams, authInfo runtime.ClientAuthInfoWriter) (*DescribeRuntimeProviderZonesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDescribeRuntimeProviderZonesParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"DescribeRuntimeProviderZones\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/runtimes/zones\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DescribeRuntimeProviderZonesReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*DescribeRuntimeProviderZonesOK), nil\n\n}", "func GetRegionAZs(region string, azList *AZs) error {\n\n\tsess := session.Must(session.NewSession(&aws.Config{Region: aws.String(region)}))\n\tsvc := ec2.New(sess)\n\n\t// Create a context with a timeout that will abort the request if it takes too long\n\tctx, cancelFn := context.WithTimeout(context.Background(), time.Second*5)\n\tdefer cancelFn()\n\n\tresult, err := svc.DescribeAvailabilityZonesWithContext(ctx, nil)\n\n\tif err != nil {\n\t\t/*terminal.ErrorLine(\"Region AZ request timeout in [\" + region + \"], skipping...\")*/\n\t\treturn nil\n\t}\n\n\tazs := make(AZs, len(result.AvailabilityZones))\n\tfor i, az := range result.AvailabilityZones {\n\t\tazs[i] = AZ{\n\t\t\tName: aws.StringValue(az.ZoneName),\n\t\t\tRegion: aws.StringValue(az.RegionName),\n\t\t\tState: aws.StringValue(az.State),\n\t\t}\n\t}\n\n\t*azList = append(*azList, azs[:]...)\n\n\treturn nil\n}", "func (c *Client) ListZoneFlavors(args *ListZoneFlavorsArgs) (*ListFlavorInfosResult, error) {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn nil, jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ListZoneFlavors(c, body)\n}", "func (p *PowerDNS) GetZones() ([]Zone, error) {\n\tzones := make([]Zone, 0)\n\tmyError := new(Error)\n\tzonesSling := p.makeSling()\n\tresp, err := zonesSling.New().Get(\"servers/\"+p.VHost+\"/zones\").Receive(&zones, myError)\n\n\tif err == nil && resp.StatusCode >= 400 {\n\t\tmyError.Message = strings.Join([]string{resp.Status, myError.Message}, \" \")\n\t\treturn nil, myError\n\t}\n\n\tfor i := range zones {\n\t\tzones[i].PowerDNSHandle = p\n\t}\n\n\treturn zones, err\n}", "func (mr *MockClientMockRecorder) DescribeAvailabilityZones(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DescribeAvailabilityZones\", reflect.TypeOf((*MockClient)(nil).DescribeAvailabilityZones), arg0)\n}", "func NewListZonesRequest(server string) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/zone\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (r *Cluster) AvailabilityZones() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"availabilityZones\"])\n}", "func (*OktetoClusterHelper) List() (map[string]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (o GetAvailabilityZonesResultOutput) Names() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetAvailabilityZonesResult) []string { return v.Names }).(pulumi.StringArrayOutput)\n}", "func (m *VirtualEndpoint) GetSupportedRegions()([]CloudPcSupportedRegionable) {\n val, err := m.GetBackingStore().Get(\"supportedRegions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcSupportedRegionable)\n }\n return nil\n}", "func (a *CloudProviderCredentialsApiService) ListScalewayRegions(ctx _context.Context) ApiListScalewayRegionsRequest {\n\treturn ApiListScalewayRegionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (client IdentityClient) ListRegions(ctx context.Context) (response ListRegionsResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tociResponse, err = client.listRegions(ctx)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListRegionsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListRegionsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListRegionsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListRegionsResponse\")\n\t}\n\treturn\n}", "func (api *tenantAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Tenant, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Tenant().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Tenant\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Tenant)\n\t}\n\treturn ret, nil\n}", "func ListZones() (zones Zones, err error) {\n\tcfz, err := api.ListZones()\n\tif err != nil {\n\t\treturn\n\t}\n\tzones.translateFromCloudflare(cfz)\n\treturn\n}", "func (s *API) ListDNSZoneVersions(req *ListDNSZoneVersionsRequest, opts ...scw.RequestOption) (*ListDNSZoneVersionsResponse, error) {\n\tvar err error\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\n\tif fmt.Sprint(req.DNSZone) == \"\" {\n\t\treturn nil, errors.New(\"field DNSZone cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/domain/v2alpha2/dns-zones/\" + fmt.Sprint(req.DNSZone) + \"/versions\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDNSZoneVersionsResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func list_arches(w rest.ResponseWriter, r *rest.Request) {\n\t// Use caching to reduce calls to the Dropbox API\n\tcache_path := \"arches\"\n\tdata, found := cache_instance.Get(cache_path)\n\tif found {\n\t\tif cached, ok := data.([]string); ok {\n\t\t\tw.WriteJson(cached)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Println(\"Error: Unable to retrieve from cache\")\n\t\t}\n\t}\n\n\tarches := []string{}\n\tdirectories := get_directories(cache_instance, db, \"/\")\n\tfor _, arch := range directories {\n\t\tarches = append(arches, strings.Replace(arch.Path, \"/\", \"\", -1))\n\t}\n\tcache_instance.Set(cache_path, arches, 0)\n\tw.WriteJson(arches)\n}", "func (p *Provider) List() ([]string, error) {\n\treturn p.provider.ListClusters()\n}", "func (c APIClient) GetZones() ([]Zone, error) {\n\tvar zl []Zone\n\t_, err := c.doHTTPUnmarshal(\"GET\", \"https://api.nsone.net/v1/zones\", nil, &zl)\n\treturn zl, err\n}", "func runListServers(_ *cobra.Command, _ []string) {\n\tcfg, err := config.LoadFromFile()\n\tif err != nil {\n\t\texitWithError(err)\n\t}\n\n\tregions, err := checkRegions(*region)\n\tif err != nil {\n\t\texitWithError(err)\n\t}\n\n\tnameFilter := core.NewFilter(core.TagName, *name, core.Contains, *ignoreCase)\n\tenvFilter := core.NewFilter(core.TagEnv, *env, core.Equals, *ignoreCase)\n\tservers, err := core.GetAllServers(cfg.AWSCredentials, regions, nameFilter, envFilter)\n\tif err != nil {\n\t\texitWithError(err)\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)\n\tfmt.Fprintln(w, \"NAME\\tENVIRONMENT\\tPRIVATE IP\\tPUBLIC IP\")\n\tfor _, server := range servers {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", server.Name, server.Env, server.PrivateIP, server.PublicIP)\n\t}\n\tw.Flush()\n}", "func ListExchangesByRegion(account accounts.Interface, httpClient *http.Client) ExchangeRegionList {\n\tmoonpayRegions, moonpayError := GetMoonpaySupportedRegions(httpClient)\n\tlog := logging.Get().WithGroup(\"exchanges\")\n\tif moonpayError != nil {\n\t\tlog.Error(moonpayError)\n\t}\n\n\tpocketRegions, pocketError := GetPocketSupportedRegions(httpClient)\n\tif pocketError != nil {\n\t\tlog.Error(pocketError)\n\t}\n\n\tisMoonpaySupported := IsMoonpaySupported(account.Coin().Code())\n\tisPocketSupported := IsPocketSupported(account)\n\n\texchangeRegions := ExchangeRegionList{}\n\tfor _, code := range regionCodes {\n\t\t// default behavior is to show the exchange if the supported regions check fails.\n\t\tmoonpayEnabled, pocketEnabled := true, true\n\t\tif moonpayError == nil {\n\t\t\t_, moonpayEnabled = moonpayRegions[code]\n\t\t}\n\t\tif pocketError == nil {\n\t\t\t_, pocketEnabled = pocketRegions[code]\n\t\t}\n\t\texchangeRegions.Regions = append(exchangeRegions.Regions, ExchangeRegion{\n\t\t\tCode: code,\n\t\t\tIsMoonpayEnabled: moonpayEnabled && isMoonpaySupported,\n\t\t\tIsPocketEnabled: pocketEnabled && isPocketSupported,\n\t\t})\n\t}\n\n\treturn exchangeRegions\n}", "func (m *manager) List() ([]string, error) {\n\tvar igs []*compute.InstanceGroup\n\n\tzones, err := m.ListZones(utils.AllNodesPredicate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, zone := range zones {\n\t\tigsForZone, err := m.cloud.ListInstanceGroups(zone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, ig := range igsForZone {\n\t\t\tigs = append(igs, ig)\n\t\t}\n\t}\n\n\tvar names []string\n\tfor _, ig := range igs {\n\t\tif m.namer.NameBelongsToCluster(ig.Name) {\n\t\t\tnames = append(names, ig.Name)\n\t\t}\n\t}\n\n\treturn names, nil\n}", "func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}", "func ListKownAddresses() ([]KnownAddress, error){\n var knownAddresses []KnownAddress\n\n s, err := TezosDo(\"list\", \"known\", \"addresses\")\n if (err != nil){\n return knownAddresses, errors.New(\"Could not list known addresses: tezosDo(args ...string) failed: \" + err.Error())\n }\n\n parseKownAddresses := reListKownAddresses.FindAllStringSubmatch(s, -1)\n if (parseKownAddresses == nil){\n return knownAddresses, errors.New(\"Could not parse known addresses\")\n }\n\n for _, address := range parseKownAddresses{\n knownAddresses = append(knownAddresses, KnownAddress{Address:address[1],Alias:address[0],Sk:address[2]})\n }\n\n return knownAddresses, nil\n}", "func (a NumberregionsApi) ListAvailablePhoneNumberRegions(filtersCountryCode []string, filtersNpa []string, filtersNxx []string, filtersIsTollFree []string, filtersCity []string, filtersProvincePostalCode []string, filtersCountryPostalCode []string, sortCountryCode string, sortNpa string, sortNxx string, sortIsTollFree string, sortCity string, sortProvincePostalCode string, sortCountryPostalCode string, limit int32, offset int32, fields string, groupBy []string) (*ListPhoneNumbersRegions, *APIResponse, error) {\n\n\tvar localVarHttpMethod = strings.ToUpper(\"Get\")\n\t// create path and map variables\n\tlocalVarPath := a.Configuration.BasePath + \"/phone-numbers/available/regions\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := make(map[string]string)\n\tvar localVarPostBody interface{}\n\tvar localVarFileName string\n\tvar localVarFileBytes []byte\n\t// authentication '(apiKey)' required\n\t// set key with prefix in header\n\tlocalVarHeaderParams[\"Authorization\"] = a.Configuration.GetAPIKeyWithPrefix(\"Authorization\")\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\tlocalVarHeaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\tvar filtersCountryCodeCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[country_code]\", a.Configuration.APIClient.ParameterToString(filtersCountryCode, filtersCountryCodeCollectionFormat))\n\n\tvar filtersNpaCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[npa]\", a.Configuration.APIClient.ParameterToString(filtersNpa, filtersNpaCollectionFormat))\n\n\tvar filtersNxxCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[nxx]\", a.Configuration.APIClient.ParameterToString(filtersNxx, filtersNxxCollectionFormat))\n\n\tvar filtersIsTollFreeCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[is_toll_free]\", a.Configuration.APIClient.ParameterToString(filtersIsTollFree, filtersIsTollFreeCollectionFormat))\n\n\tvar filtersCityCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[city]\", a.Configuration.APIClient.ParameterToString(filtersCity, filtersCityCollectionFormat))\n\n\tvar filtersProvincePostalCodeCollectionFormat = \"multi\"\n\tlocalVarQueryParams.Add(\"filters[province_postal_code]\", a.Configuration.APIClient.ParameterToString(filtersProvincePostalCode, filtersProvincePostalCodeCollectionFormat))\n\n\tvar filtersCountryPostalCodeCollectionFormat = \"csv\"\n\tlocalVarQueryParams.Add(\"filters[country_postal_code]\", a.Configuration.APIClient.ParameterToString(filtersCountryPostalCode, filtersCountryPostalCodeCollectionFormat))\n\n\tlocalVarQueryParams.Add(\"sort[country_code]\", a.Configuration.APIClient.ParameterToString(sortCountryCode, \"\"))\n\tlocalVarQueryParams.Add(\"sort[npa]\", a.Configuration.APIClient.ParameterToString(sortNpa, \"\"))\n\tlocalVarQueryParams.Add(\"sort[nxx]\", a.Configuration.APIClient.ParameterToString(sortNxx, \"\"))\n\tlocalVarQueryParams.Add(\"sort[is_toll_free]\", a.Configuration.APIClient.ParameterToString(sortIsTollFree, \"\"))\n\tlocalVarQueryParams.Add(\"sort[city]\", a.Configuration.APIClient.ParameterToString(sortCity, \"\"))\n\tlocalVarQueryParams.Add(\"sort[province_postal_code]\", a.Configuration.APIClient.ParameterToString(sortProvincePostalCode, \"\"))\n\tlocalVarQueryParams.Add(\"sort[country_postal_code]\", a.Configuration.APIClient.ParameterToString(sortCountryPostalCode, \"\"))\n\tlocalVarQueryParams.Add(\"limit\", a.Configuration.APIClient.ParameterToString(limit, \"\"))\n\tlocalVarQueryParams.Add(\"offset\", a.Configuration.APIClient.ParameterToString(offset, \"\"))\n\tlocalVarQueryParams.Add(\"fields\", a.Configuration.APIClient.ParameterToString(fields, \"\"))\n\tvar groupByCollectionFormat = \"csv\"\n\tlocalVarQueryParams.Add(\"group_by\", a.Configuration.APIClient.ParameterToString(groupBy, groupByCollectionFormat))\n\n\n\tclearEmptyParams(localVarQueryParams)\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tvar successPayload = new(ListPhoneNumbersRegions)\n\tlocalVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\n\tvar localVarURL, _ = url.Parse(localVarPath)\n\tlocalVarURL.RawQuery = localVarQueryParams.Encode()\n\tvar localVarAPIResponse = &APIResponse{Operation: \"ListAvailablePhoneNumberRegions\", Method: localVarHttpMethod, RequestURL: localVarURL.String()}\n\tif localVarHttpResponse != nil {\n\t\tlocalVarAPIResponse.Response = localVarHttpResponse.RawResponse\n\t\tlocalVarAPIResponse.Payload = localVarHttpResponse.Body()\n\t}\n\n\tif err != nil {\n\t\treturn successPayload, localVarAPIResponse, err\n\t}\n\terr = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)\n\treturn successPayload, localVarAPIResponse, err\n}", "func (z *Zones) ListZones() []ClusterZone {\n\tzones := []ClusterZone{}\n\tz.db.DB().Find(&zones)\n\treturn zones\n}", "func (a *AvailabilityZoneSelector) SelectZones(regionName string) ([]string, error) {\n\tavailableZones, err := a.getZonesForRegion(regionName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusableZones := a.getUsableZones(availableZones)\n\n\treturn a.strategy.Select(usableZones), nil\n}", "func (s *API) ListDNSZoneVersions(req *ListDNSZoneVersionsRequest, opts ...scw.RequestOption) (*ListDNSZoneVersionsResponse, error) {\n\tvar err error\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\n\tif fmt.Sprint(req.DNSZone) == \"\" {\n\t\treturn nil, errors.New(\"field DNSZone cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/domain/v2beta1/dns-zones/\" + fmt.Sprint(req.DNSZone) + \"/versions\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDNSZoneVersionsResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (client IdentityClient) listRegionSubscriptions(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tenancies/{tenancyId}/regionSubscriptions\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListRegionSubscriptionsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (c *Client) GetAvailableWatchProviderRegions(\n\turlOptions map[string]string,\n) (*WatchRegionList, error) {\n\toptions := c.fmtOptions(urlOptions)\n\ttmdbURL := fmt.Sprintf(\n\t\t\"%s%sregions?api_key=%s%s\",\n\t\tbaseURL,\n\t\twatchProvidersURL,\n\t\tc.apiKey,\n\t\toptions,\n\t)\n\twatchRegionList := WatchRegionList{}\n\tif err := c.get(tmdbURL, &watchRegionList); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &watchRegionList, nil\n}", "func (api *tenantAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Tenant, error) {\n\tvar objlist []*Tenant\n\tobjs, err := api.ct.List(\"Tenant\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Tenant:\n\t\t\teobj := obj.(*Tenant)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Tenant\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func (s *API) ListDatabaseBackups(req *ListDatabaseBackupsRequest, opts ...scw.RequestOption) (*ListDatabaseBackupsResponse, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"name\", req.Name)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"instance_id\", req.InstanceID)\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\tparameter.AddToQuery(query, \"project_id\", req.ProjectID)\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/backups\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDatabaseBackupsResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (c *clientBackup) List(ctx context.Context, opt *BackupListOptions) (map[BackupID]BackupMeta, error) {\n\treq, err := c.conn.NewRequest(\"POST\", \"_admin/backup/list\")\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tapplyContextSettings(ctx, req)\n\tif opt != nil {\n\t\treq, err = req.SetBody(opt)\n\t\tif err != nil {\n\t\t\treturn nil, WithStack(err)\n\t\t}\n\t}\n\tresp, err := c.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tvar result struct {\n\t\tList map[BackupID]BackupMeta `json:\"list,omitempty\"`\n\t}\n\tif err := resp.ParseBody(\"result\", &result); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\treturn result.List, nil\n}", "func (s *dnsManagedZoneLister) List(selector labels.Selector) (ret []*v1alpha1.DnsManagedZone, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.DnsManagedZone))\n\t})\n\treturn ret, err\n}", "func (s *Server) GetZones(ctx context.Context, in *GetZonesRequest) (*GetZonesResponse, error) {\n\tvar zones []*Zone\n\tfor _, z := range s.service.GetZones() {\n\t\tvar speakers []*Speaker\n\t\tfor _, member := range z.Speakers {\n\t\t\tspeaker := &Speaker{Id: member.ID, DisplayName: member.DisplayName}\n\t\t\tspeakers = append(speakers, speaker)\n\t\t}\n\t\tzones = append(zones, &Zone{DisplayName: z.DisplayName, Id: z.ID, Speakers: speakers})\n\t}\n\treturn &GetZonesResponse{ReturnCode: 200, Zones: zones}, nil\n}", "func (d *instanceProvider) GetResource(ctx context.Context) (*schema.Resources, error) {\n\tlist := &schema.Resources{}\n\n\tfor _, zone := range scw.AllZones {\n\t\treq := &instance.ListServersRequest{\n\t\t\tZone: zone,\n\t\t}\n\t\tvar totalResults uint32\n\t\tfor {\n\t\t\tresp, err := d.instanceAPI.ListServers(req)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, server := range resp.Servers {\n\t\t\t\ttotalResults++\n\n\t\t\t\tvar ip4, privateIP4 string\n\t\t\t\tif server.PublicIP != nil && server.PublicIP.Address != nil {\n\t\t\t\t\tip4 = server.PublicIP.Address.String()\n\t\t\t\t}\n\t\t\t\tif server.PrivateIP != nil {\n\t\t\t\t\tprivateIP4 = *server.PrivateIP\n\t\t\t\t}\n\t\t\t\tlist.Append(&schema.Resource{\n\t\t\t\t\tProvider: providerName,\n\t\t\t\t\tPublicIPv4: ip4,\n\t\t\t\t\tProfile: d.profile,\n\t\t\t\t\tPrivateIpv4: privateIP4,\n\t\t\t\t\tPublic: ip4 != \"\",\n\t\t\t\t})\n\t\t\t}\n\t\t\tif resp.TotalCount == totalResults {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t*req.Page = *req.Page + 1\n\t\t}\n\t}\n\treturn list, nil\n}", "func (client *Client) GetRegionList(request *GetRegionListRequest) (response *GetRegionListResponse, err error) {\n\tresponse = CreateGetRegionListResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (afric africaDeprecatedTimeZones) Brazzaville() string { return \"Africa/Lagos\" }", "func (c *AppsServices) Browse() ([]interface{}, error) {\n\tu, err := url.Parse(c.client.BaseURL.String() + \"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.client.UseAuthKey = true\n\tresp, err := GET(u.String(), c.client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data []interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func NewListDNSZonesRequest(server string, params *ListDNSZonesParams) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/domain/v2alpha2/dns-zones\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryValues := queryUrl.Query()\n\n\tif params.Page != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"page\", *params.Page); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.PageSize != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"page_size\", *params.PageSize); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.OrderBy != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"order_by\", *params.OrderBy); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.Domain != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"domain\", *params.Domain); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.DnsZone != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"dns_zone\", *params.DnsZone); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.OrganizationId != nil {\n\n\t\tif queryFrag, err := runtime.StyleParam(\"form\", true, \"organization_id\", *params.OrganizationId); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tqueryUrl.RawQuery = queryValues.Encode()\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func getZones(zoneTable string) (zones []Zone, err error) {\n\tif !tableExists(zoneTable) {\n\t\treturn nil, fmt.Errorf(\"Table not found!\\n\")\n\t}\n\n\tquery := fmt.Sprintf(\"SELECT * FROM %s\", zoneTable)\n\trows, err := db.Query(query)\n\tdefer rows.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar id, start, end, offset int64\n\tvar name string\n\tvar isDST bool\n\n\tzones = make([]Zone, 0, 5)\n\tfor rows.Next() {\n\t\terr = rows.Scan(&id, &name, &start, &end, &offset, &isDST)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewZone := Zone{ID: id, Name: name, Start: start, End: end, Offset: offset, IsDST: isDST}\n\t\tzones = append(zones, newZone)\n\t}\n\n\treturn zones, nil\n}", "func getInfo(regionName string) (*RegionInfo, error) {\n // ex-1)\n // /cloud-info-spaces/regions/aws_region01/AWS/region [ap-northeast-2]\n // ex-2)\n // /cloud-info-spaces/regions/gcp_region02/GCP/region [us-east1]\n // /cloud-info-spaces/regions/gcp_region02/GCP/zone [us-east1-c]\n\n\t\n\tkey := \"/cloud-info-spaces/regions/\" + regionName\n\n\t// key is not the key of cb-store, so we have to use GetList()\n keyValueList, err := store.GetList(key, true)\n if err != nil {\n return nil, err\n }\n\n if len(keyValueList) < 1 {\n return nil, fmt.Errorf(regionName + \": does not exist!\")\n }\n\n // keyValueList should have ~/driverName/... or ~/driverName-01/...,\n // so we have to check the sameness of driverName.\n // and make a KeyValueList for only Target key\n var oneKeyValueList []icbs.KeyValue\n for _, kv := range keyValueList {\n if utils.GetNodeValue(kv.Key, 3) == regionName {\n oneKeyValueList = append(oneKeyValueList, *kv)\n }\n }\n\n if len(oneKeyValueList) < 1 {\n return nil, fmt.Errorf(regionName + \": does not exist!\")\n }\n\n var inKeyValueList []icbs.KeyValue\n // get ProviderName\n providerName := utils.GetNodeValue(oneKeyValueList[0].Key, 4)\n // get KeyValueList\n for _, kv := range oneKeyValueList {\n keyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n inKeyValueList = append(inKeyValueList, keyValue)\n }\n\treturn &RegionInfo{regionName, providerName, inKeyValueList}, nil \n}", "func (c *PDNSAPIClient) ListZone(zoneID string) (zone pgo.Zone, resp *http.Response, err error) {\n\tfor i := 0; i < retryLimit; i++ {\n\t\tzone, resp, err = c.client.ZonesApi.ListZone(c.authCtx, defaultServerID, zoneID)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Unable to fetch zone %v\", err)\n\t\t\tlog.Debugf(\"Retrying ListZone() ... %d\", i)\n\t\t\ttime.Sleep(retryAfterTime * (1 << uint(i)))\n\t\t\tcontinue\n\t\t}\n\t\treturn zone, resp, err\n\t}\n\n\tlog.Errorf(\"Unable to list zone. %v\", err)\n\treturn zone, resp, err\n}", "func (r ListAvailableZonesRequest) Send(ctx context.Context) (*ListAvailableZonesResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &ListAvailableZonesResponse{\n\t\tListAvailableZonesOutput: r.Request.Data.(*ListAvailableZonesOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (a *API) ListRegions() ([]string, error) {\n\trequest := ecs.CreateDescribeRegionsRequest()\n\trequest.Scheme = \"https\"\n\n\tresponse, err := a.ecs.DescribeRegions(request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"describing regions: %v\", err)\n\t}\n\tret := make([]string, 0, len(response.Regions.Region))\n\tfor _, region := range response.Regions.Region {\n\t\tret = append(ret, region.RegionId)\n\t}\n\tsort.Strings(ret)\n\treturn ret, nil\n}", "func FetchTimeZones(useCache bool) ([]*TimeZone, error) {\n\tgeonamesFile, err := downloadFile(geonamesUrls[\"time_zones\"], useCache)\n\tif err != nil {\n\t\treturn nil, stacktrace.Propagate(err, \"download geonames file with time zones\")\n\t}\n\n\ttimeZones := make([]*TimeZone, 0)\n\n\terr = parseCsvFile(geonamesFile, 1, '\\t', '#', func(raw []string) bool {\n\t\tif len(raw) != 5 {\n\t\t\tlogWarn(\"invalid (%d) count of fields\\n\\t=> %v\", len(raw), raw)\n\n\t\t\treturn true\n\t\t}\n\n\t\tgmtOffset, _ := strconv.ParseFloat(raw[2], 64)\n\t\tdstOffset, _ := strconv.ParseFloat(raw[3], 64)\n\t\trawOffset, _ := strconv.ParseFloat(raw[4], 64)\n\n\t\ttimeZones = append(timeZones, &TimeZone{\n\t\t\tCountryIso2Code: raw[0],\n\t\t\tTimeZoneId: raw[1],\n\t\t\tGmtOffset: time.Duration(gmtOffset) * time.Hour,\n\t\t\tDstOffset: time.Duration(dstOffset) * time.Hour,\n\t\t\tRawOffset: time.Duration(rawOffset) * time.Hour,\n\t\t})\n\n\t\treturn true\n\t})\n\n\tif err != nil {\n\t\treturn nil, stacktrace.Propagate(err, \"parse cav file with time zones\")\n\t}\n\n\treturn timeZones, nil\n}", "func (c *Client) TimeZones() ([]*models.TimeZone, error) {\n\tvar err error\n\tvar result []*models.TimeZone\n\n\tdata, err := c.httpGet(geonamesURL + timeZonesURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparse(data, 1, func(raw [][]byte) bool {\n\t\tif len(raw) != 5 {\n\t\t\treturn true\n\t\t}\n\n\t\tgmtOffset, _ := strconv.ParseFloat(string(raw[2]), 64)\n\t\tdstOffset, _ := strconv.ParseFloat(string(raw[3]), 64)\n\t\trawOffset, _ := strconv.ParseFloat(string(raw[4]), 64)\n\n\t\tresult = append(result, &models.TimeZone{\n\t\t\tCountryIso2Code: string(raw[0]),\n\t\t\tTimeZoneID: string(raw[1]),\n\t\t\tGmtOffset: time.Duration(gmtOffset) * time.Hour,\n\t\t\tDstOffset: time.Duration(dstOffset) * time.Hour,\n\t\t\tRawOffset: time.Duration(rawOffset) * time.Hour,\n\t\t})\n\n\t\treturn true\n\t})\n\n\treturn result, nil\n}", "func (vr *VirtualResource) ListAll() (*VirtualServerConfigList, error) {\n\tresp, err := vr.doRequest(\"GET\", \"\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := vr.readError(resp); err != nil {\n\t\treturn nil, err\n\t}\n\tvar vsc VirtualServerConfigList\n\tdec := json.NewDecoder(resp.Body)\n\tif err := dec.Decode(&vsc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &vsc, nil\n}", "func (client *AvailabilitySetsClient) List(resourceGroupName string, options *AvailabilitySetsListOptions) *AvailabilitySetsListPager {\n\treturn &AvailabilitySetsListPager{\n\t\tclient: client,\n\t\trequester: func(ctx context.Context) (*policy.Request, error) {\n\t\t\treturn client.listCreateRequest(ctx, resourceGroupName, options)\n\t\t},\n\t\tadvancer: func(ctx context.Context, resp AvailabilitySetsListResponse) (*policy.Request, error) {\n\t\t\treturn runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilitySetListResult.NextLink)\n\t\t},\n\t}\n}", "func List(ctx context.Context, client *v1.ServiceClient, clusterID string) ([]*View, *v1.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, v1.ResourceURLCluster, clusterID, v1.ResourceURLNodegroup}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract nodegroups from the response body.\n\tvar result struct {\n\t\tNodegroups []*View `json:\"nodegroups\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Nodegroups, responseResult, err\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := baseURL(client)\n\n\tif opts != nil {\n\t\tquery, err := opts.ToBackupListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\n\tpageFn := func(r pagination.PageResult) pagination.Page {\n\t\treturn BackupPage{pagination.SinglePageBase(r)}\n\t}\n\n\treturn pagination.NewPager(client, url, pageFn)\n}", "func (m *CountryNamedLocation) GetCountriesAndRegions()([]string) {\n val, err := m.GetBackingStore().Get(\"countriesAndRegions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func Explore(client *storage.Client, thinClient *ThinClient, bucket string, prefix string) ([]*Node, error) {\n // Combine bucket lifecycle to each node\n ctx := context.Background()\n lifecycle, err := thinClient.Lifecycle(ctx, bucket)\n if err != nil {\n return nil, err\n }\n\n objs, err := listq(client, bucket, prefix, \"/\", false, true)\n if err != nil {\n return nil, err\n }\n var nodes []*Node\n for _, element := range objs {\n var node Node\n node.Bucket = bucket\n node.Lifecycle = lifecycle\n if element.Name == \"\" && element.Prefix != \"\" {\n node.Ntype = \"DIR\"\n node.Name = element.Prefix\n node.FQPN = element.Prefix\n } else {\n node.Ntype = \"OBJ\"\n pathSlice := strings.Split(element.Name, \"/\")\n pathLength := len(pathSlice)\n node.Name = pathSlice[pathLength - 1]\n node.FQPN = element.Name\n }\n node.ACL = element.ACL\n node.Owner = element.Owner\n node.Size = element.Size\n\n nodes = append(nodes, &node)\n }\n return nodes, nil\n}", "func ListVPC(connectionName string, rsType string) ([]*cres.VPCInfo, error) {\n\tcblog.Info(\"call ListVPC()\")\n\n\t// check empty and trim user inputs\n connectionName, err := EmptyCheckAndTrim(\"connectionName\", connectionName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n\tcldConn, err := ccm.GetCloudConnection(connectionName)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\thandler, err := cldConn.CreateVPCHandler()\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (1) get IID:list\n\tiidInfoList, err := iidRWLock.ListIID(iidm.IIDSGROUP, connectionName, rsType)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tvar infoList []*cres.VPCInfo\n\tif iidInfoList == nil || len(iidInfoList) <= 0 {\n\t\tinfoList = []*cres.VPCInfo{}\n\t\treturn infoList, nil\n\t}\n\n\t// (2) Get VPCInfo-list with IID-list\n\twg := new(sync.WaitGroup)\n\tresultInfoList := []*cres.VPCInfo{}\n var retChanInfos []chan ResultVPCInfo\n for i:=0 ; i<len(iidInfoList); i++ {\n retChanInfos = append(retChanInfos, make(chan ResultVPCInfo))\n }\n\n for idx, iidInfo := range iidInfoList {\n\n wg.Add(1)\n\n go getVPCInfo(connectionName, handler, iidInfo.IId, retChanInfos[idx])\n\n wg.Done()\n\n }\n wg.Wait()\n\n var errList []string\n for idx, retChanInfo := range retChanInfos {\n chanInfo := <-retChanInfo\n\n if chanInfo.err != nil {\n if checkNotFoundError(chanInfo.err) {\n cblog.Info(chanInfo.err) } else {\n errList = append(errList, connectionName + \":VPC:\" + iidInfoList[idx].IId.NameId + \" # \" + chanInfo.err.Error())\n }\n } else {\n resultInfoList = append(resultInfoList, &chanInfo.vpcInfo)\n }\n\n close(retChanInfo)\n }\n\n if len(errList) > 0 {\n cblog.Error(strings.Join(errList, \"\\n\"))\n return nil, errors.New(strings.Join(errList, \"\\n\"))\n }\n\n return resultInfoList, nil\n}", "func ListProviders() {\n\n\theaders := make(map[string]string)\n\theaders[\"Content-Type\"] = \"application/json\"\n\n\tauthenticator := &core.IamAuthenticator{\n\t\tApiKey: apiKey,\n\t\tURL: url, //use for dev/preprod env\n\t}\n\tservice, _ := findingsapiv1.NewFindingsApiV1(&findingsapiv1.FindingsApiV1Options{\n\t\tAuthenticator: authenticator,\n\t\tURL: \"https://us-south.secadvisor.cloud.ibm.com/findings\", //Specify url or use default\n\t})\n\n\tvar listProvidersOptions = service.NewListProvidersOptions(accountID)\n\tlistProvidersOptions.SetLimit(5)\n\tlistProvidersOptions.SetStartProviderID(\"a\")\n\tlistProvidersOptions.SetEndProviderID(\"p\")\n\n\tres, _, err := service.ListProviders(listProvidersOptions)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to get list of providers: \", err)\n\t} else {\n\t\tfmt.Printf(`Found %d Providers between \"a\" and \"p\". Limit is set to 5 per page.`, len(res.Providers))\n\t\tfmt.Println()\n\t\tif len(res.Providers) > 0 {\n\t\t\tfmt.Println(\"Providers 1 id: \", *res.Providers[0].ID)\n\t\t\tfmt.Println(\"Providers 1 name: \", *res.Providers[0].Name)\n\n\t\t}\n\t}\n\n}", "func (c *Client) AvailabilityZone() (string, error) {\n\treturn c.get(\"/availability-zone\")\n}", "func (u *UpCloud) GetZones() (z *[]Zone, err error) {\n\tvar resp getZonesResponse\n\t// Make request to \"Get Zones\" route\n\tif err = u.request(\"GET\", RouteGetZone, nil, nil, &resp); err != nil {\n\t\treturn\n\t}\n\n\t// Set return value from response\n\tz = resp.Zones.Zone\n\treturn\n}" ]
[ "0.6645805", "0.6408122", "0.6389955", "0.6298702", "0.61984795", "0.6065202", "0.60170764", "0.5931714", "0.5891944", "0.5889495", "0.5877689", "0.57728183", "0.5748056", "0.5747089", "0.5746278", "0.5724729", "0.56708676", "0.5636212", "0.5588434", "0.55752647", "0.5562941", "0.5492764", "0.54714084", "0.5436832", "0.5430647", "0.5318257", "0.5304868", "0.52906346", "0.5216447", "0.516621", "0.5164714", "0.5162599", "0.5159692", "0.5152815", "0.5148088", "0.51413876", "0.51118505", "0.5105525", "0.50896126", "0.50804603", "0.5037077", "0.502845", "0.5003917", "0.49879766", "0.49771148", "0.4973761", "0.49729225", "0.49671733", "0.4962907", "0.49353492", "0.4926641", "0.49213436", "0.49173006", "0.48933423", "0.48901805", "0.487864", "0.4870081", "0.48630768", "0.48622805", "0.48609626", "0.48532245", "0.48481593", "0.48232734", "0.4819839", "0.48122662", "0.4802638", "0.47931156", "0.4791586", "0.4787307", "0.4784665", "0.47801533", "0.4758591", "0.4752583", "0.47274086", "0.4717755", "0.47120193", "0.47049344", "0.47027856", "0.46959212", "0.46833873", "0.4682168", "0.46808854", "0.46808377", "0.46722078", "0.46612653", "0.4652653", "0.4641252", "0.46407238", "0.4637295", "0.46331313", "0.46300894", "0.46246508", "0.46187723", "0.46139023", "0.46034822", "0.4603031", "0.4592937", "0.45898917", "0.45893586", "0.4589319" ]
0.76050305
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseAvailabilityZonesExecute(r ApiBrowseAvailabilityZonesRequest) (RegionsPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue RegionsPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseAvailabilityZones") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/availabilityZones" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
/ BrowseBucketFolders Method for BrowseBucketFolders
func (a *AmazonConnectionsApiService) BrowseBucketFolders(ctx _context.Context, amazonConnectionId string, bucketId string) ApiBrowseBucketFoldersRequest { return ApiBrowseBucketFoldersRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, bucketId: bucketId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseBucketFoldersExecute(r ApiBrowseBucketFoldersRequest) (BucketFoldersPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue BucketFoldersPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseBucketFolders\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/browseBucketFolders/{bucketId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucketId\"+\"}\", _neturl.PathEscape(parameterToString(r.bucketId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"Sort\", parameterToString(*r.sort, \"csv\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (s kw_rest_folder) Folders(params ...interface{}) (children []KiteObject, err error) {\n\tif len(params) == 0 {\n\t\tparams = SetParams(Query{\"deleted\": false})\n\t}\n\terr = s.DataCall(APIRequest{\n\t\tMethod: \"GET\",\n\t\tPath: SetPath(\"/rest/folders/%d/folders\", s.folder_id),\n\t\tOutput: &children,\n\t\tParams: SetParams(params, Query{\"with\": \"(path,currentUserRole)\"}),\n\t}, -1, 1000)\n\n\treturn\n}", "func remoteBucketList(remoteURLObj interface{}) (interface{}, error) {\n\tremoteURL := remoteURLObj.(string)\n\treturn couchbase.GetBucketList(remoteURL)\n}", "func ListBucket(a S3Account, bucket string) {\n\treq := NewRequest(a, \"GET\", bucket, \"/\", nil)\n\tbody := req.Send()\n\tlbr := ListBucketResult{}\n\txml.Unmarshal(body, &lbr)\n\tfor _,cp := range lbr.CommonPrefixes {\n\t\tcp.pp()\n\t}\n\tfor _,c := range lbr.Contents {\n\t\tc.pp()\n\t}\n}", "func (b *BigIP) Folders() (*Folders, error) {\n\tvar folders Folders\n\terr, _ := b.getForEntity(&folders, uriSys, uriFolder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &folders, nil\n}", "func (c *Client) ListBucket(bucket string, startAt string, maxKeys int) (items []*Item, err error) {\n\tif maxKeys < 0 {\n\t\treturn nil, errors.New(\"invalid negative maxKeys\")\n\t}\n\tmarker := startAt\n\tfor len(items) < maxKeys {\n\t\tfetchN := maxKeys - len(items)\n\t\tif fetchN > maxList {\n\t\t\tfetchN = maxList\n\t\t}\n\t\tvar bres listBucketResults\n\n\t\turl_ := fmt.Sprintf(\"%s?marker=%s&max-keys=%d\",\n\t\t\tc.bucketURL(bucket), url.QueryEscape(marker), fetchN)\n\n\t\t// Try the enumerate three times, since Amazon likes to close\n\t\t// https connections a lot, and Go sucks at dealing with it:\n\t\t// https://code.google.com/p/go/issues/detail?id=3514\n\t\tconst maxTries = 5\n\t\tfor try := 1; try <= maxTries; try++ {\n\t\t\ttime.Sleep(time.Duration(try-1) * 100 * time.Millisecond)\n\t\t\treq := newReq(url_)\n\t\t\tc.Auth.SignRequest(req)\n\t\t\tres, err := c.transport().RoundTrip(req)\n\t\t\tif err != nil {\n\t\t\t\tif try < maxTries {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif res.StatusCode != http.StatusOK {\n\t\t\t\tif res.StatusCode < 500 {\n\t\t\t\t\tbody, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20))\n\t\t\t\t\taerr := &Error{\n\t\t\t\t\t\tOp: \"ListBucket\",\n\t\t\t\t\t\tCode: res.StatusCode,\n\t\t\t\t\t\tBody: body,\n\t\t\t\t\t\tHeader: res.Header,\n\t\t\t\t\t}\n\t\t\t\t\taerr.parseXML()\n\t\t\t\t\tres.Body.Close()\n\t\t\t\t\treturn nil, aerr\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbres = listBucketResults{}\n\t\t\t\tvar logbuf bytes.Buffer\n\t\t\t\terr = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error parsing s3 XML response: %v for %q\", err, logbuf.Bytes())\n\t\t\t\t} else if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker {\n\t\t\t\t\terr = fmt.Errorf(\"Unexpected parse from server: %#v from: %s\", bres, logbuf.Bytes())\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.Body.Close()\n\t\t\tif err != nil {\n\t\t\t\tif try < maxTries-1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tfor _, it := range bres.Contents {\n\t\t\tif it.Key == marker && it.Key != startAt {\n\t\t\t\t// Skip first dup on pages 2 and higher.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif it.Key < startAt {\n\t\t\t\treturn nil, fmt.Errorf(\"Unexpected response from Amazon: item key %q but wanted greater than %q\", it.Key, startAt)\n\t\t\t}\n\t\t\titems = append(items, it)\n\t\t\tmarker = it.Key\n\t\t}\n\t\tif !bres.IsTruncated {\n\t\t\t// log.Printf(\"Not truncated. so breaking. items = %d; len Contents = %d, url = %s\", len(items), len(bres.Contents), url_)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn items, nil\n}", "func (o *ObjectStorage) ListTopLevelObjectsInBucket(bucket *string) (*s3.ListObjectsOutput, error) {\n\tdelimiter := \"/\"\n\tlistObjectInput := &s3.ListObjectsInput{\n\t\tBucket: bucket,\n\t\tDelimiter: &delimiter,\n\t}\n\n\treturn o.Client.ListObjects(listObjectInput)\n}", "func (s3ops *S3Operations) GetBucketItems(bucket string, prefix string, index int) (items []string, probs bool) {\n\n\tsess, _ := session.NewSession()\n\tvar config = &aws.Config{}\n\tif os.Getenv(\"AWS_WEB_IDENTITY_TOKEN_FILE\") != \"\" {\n\t\teksCreds := awscredentials.Credentials{}\n\t\tcreds := *eksCreds.GetWebIdentityCredentials()\n\t\tconfig = &aws.Config{\n\t\t\tRegion: aws.String(\"eu-west-1\"),\n\t\t\tCredentials: credentials.NewStaticCredentials(*creds.AccessKeyId, *creds.SecretAccessKey, *creds.SessionToken),\n\t\t}\n\t} else {\n\t\tconfig = &aws.Config{\n\t\t\tRegion: aws.String(\"eu-west-1\"),\n\t\t}\n\t}\n\n\t// Create a client from just a config.r\n\tclient := s3.New(sess, config)\n\n\tlog.WithFields(log.Fields{\n\t\t\"Bucket\": bucket,\n\t\t\"Prefix\": prefix,\n\t}).Info(\"------ FETCHING BUCKET DETAILS ----\")\n\tparams := &s3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String(prefix)}\n\ttenants := make(map[string]struct{})\n\t// Example iterating over at most 3 pages of a ListObjectsV2 operation.\n\terr := client.ListObjectsV2Pages(params,\n\t\tfunc(page *s3.ListObjectsV2Output, lastPage bool) bool {\n\t\t\tfor _, content := range page.Contents {\n\t\t\t\tparts := strings.Split(*content.Key, \"/\")\n\t\t\t\t// you can use the ,ok idiom to check for existing keys\n\t\t\t\tif _, ok := tenants[parts[index]]; !ok {\n\t\t\t\t\ttenants[parts[index]] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn lastPage != true\n\t\t})\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"Bucket\": bucket,\n\t\t\t\"Prefix\": prefix,\n\t\t}).Error(\"Problems Getting Bucket Details\")\n\t\tprobs = true\n\t} else {\n\n\t\tkeys := make([]string, 0, len(tenants))\n\t\tfor k := range tenants {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\titems = keys\n\t\tprobs = false\n\t}\n\treturn\n}", "func getBucketObjects(svc *s3.S3, sess *session.Session, bucketName string) {\n\n\tquery := &s3.ListObjectsV2Input{\n\t\tBucket: aws.String(bucketName),\n\t\tPrefix: aws.String(prefix),\n\t}\n\n\t// Pagination Flag used to check if we need to go further (default is 1000 otherwise)\n\ttruncatedListing := true\n\tpageCount := 0\n\n\tfor truncatedListing && pageCount < maxPages {\n\t\tresp, err := svc.ListObjectsV2(query)\n\t\tpageCount++\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t\t// Get all objects for this page\n\t\tgetObjectsPage(resp, svc, bucketName)\n\n\t\t// Set continuation token\n\t\tquery.ContinuationToken = resp.NextContinuationToken\n\t\ttruncatedListing = *resp.IsTruncated\n\n\t\tif verbose == \"y\" {\n\t\t\tfmt.Printf(\"page Num %d, recCount %d \\n\", pageCount, numberOfRetrievedFiles)\n\t\t}\n\t}\n\n}", "func (instance *Host) Browse(ctx context.Context, callback func(*abstract.HostCore) fail.Error) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif instance == nil {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(ctx, func(buf []byte) (innerXErr fail.Error) {\n\t\tahc := abstract.NewHostCore()\n\t\tvar inErr fail.Error\n\t\tif inErr = ahc.Deserialize(buf); inErr != nil {\n\t\t\treturn inErr\n\t\t}\n\n\t\treturn callback(ahc)\n\t})\n}", "func (_DappboxManager *DappboxManagerSession) ReturnAllDappboxSubFolders(dappboxAddress common.Address, index *big.Int) (string, string, *big.Int, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxSubFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func browseFolderCallback(hwnd win.HWND, msg uint32, lp, wp uintptr) uintptr {\n\tconst BFFM_SELCHANGED = 2\n\tif msg == BFFM_SELCHANGED {\n\t\t_, err := pathFromPIDL(lp)\n\t\tvar enabled uintptr\n\t\tif err == nil {\n\t\t\tenabled = 1\n\t\t}\n\n\t\tconst BFFM_ENABLEOK = win.WM_USER + 101\n\n\t\twin.SendMessage(hwnd, BFFM_ENABLEOK, 0, enabled)\n\t}\n\n\treturn 0\n}", "func (_DappboxManager *DappboxManagerCallerSession) ReturnAllDappboxSubFolders(dappboxAddress common.Address, index *big.Int) (string, string, *big.Int, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxSubFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func (b *Bucket) ChkBucket() (bool, error) {\n\t// set session\n\tsess, err := b.setSession()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// list buckets\n\tsvc := b.newS3func(sess)\n\tresult, err := svc.ListBuckets(nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tklog.Info(\"Buckets:\")\n\tfound := false\n\tfor _, bu := range result.Buckets {\n\t\tklog.Infof(\"-- %s created on %s\\n\", aws.StringValue(bu.Name), aws.TimeValue(bu.CreationDate))\n\t\tif aws.StringValue(bu.Name) == b.BucketName {\n\t\t\tfound = true\n\t\t}\n\t}\n\n\treturn found, nil\n}", "func ListObjects(w http.ResponseWriter, r *http.Request) {\n\n\tsvc := s3.New(sess)\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\n\tif len(pageVars.BName) <= 0 {\n\t\tif len(pageVars.ErrorM) <= 0 {\n\t\t\tpageVars.ErrorM = \"Invalid bucket name\"\n\t\t}\n\t\trender(w, \"objectlist\", pageVars)\n\t} else {\n\n\t\tif len(pageVars.Prefix) <= 0 {\n\t\t\tpageVars.Prefix = \"\"\n\t\t}\n\n\t\tif len(pageVars.Delimiter) <= 0 {\n\t\t\tpageVars.Delimiter = \"\"\n\t\t}\n\n\t\t// Get the list of items\n\t\tresp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{\n\t\t\tBucket: aws.String(pageVars.BName),\n\t\t\tPrefix: aws.String(pageVars.Prefix),\n\t\t\tDelimiter: aws.String(pageVars.Delimiter),\n\t\t})\n\n\t\tif err != nil {\n\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\tpageVars.ErrorM = awsErr.Message()\n\t\t\t} else {\n\t\t\t\tpageVars.ErrorM = \"Failed to get objects\"\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, o := range resp.Contents {\n\t\t\t\tvar shouldAdd = true\n\t\t\t\t// check how many / in prefix\n\t\t\t\tns := strings.Count(pageVars.Prefix, \"/\")\n\t\t\t\t// check if its folder\n\t\t\t\tif strings.HasSuffix(*o.Key, \"/\") {\t\t\t\t\t\n\t\t\t\t\t// check if its top level folder\n\t\t\t\t\tif strings.Count(*o.Key, \"/\") == (ns + 1) {\n\t\t\t\t\t\tshouldAdd = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tshouldAdd = false\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// check if its top level folder\n\t\t\t\t\tif strings.Count(*o.Key, \"/\") == ns {\n\t\t\t\t\t\tshouldAdd = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tshouldAdd = false\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\n\t\t\t\tif shouldAdd {\n\t\t\t\t\tname := *o.Key\t\t\t\t\t\n\t\t\t\t\tif len(pageVars.Prefix) > 0 {\n\t\t\t\t\t\tname = strings.Replace(name, pageVars.Prefix, \"\", -1)\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasSuffix(*o.Key, \"/\") {\n\t\t\t\t\t\tod := ObjectDetails{*o.Key, name, *o.LastModified, *o.Size, *o.StorageClass, \"Folder\"}\n\t\t\t\t\t\tpageVars.OList = append(pageVars.OList, od)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tod := ObjectDetails{*o.Key, name, *o.LastModified, *o.Size, *o.StorageClass, \"File\"}\n\t\t\t\t\t\tpageVars.OList = append(pageVars.OList, od)\n\t\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\t// add folder names f prefix ends with /\n\t\t\tsl := strings.Split(pageVars.Prefix, \"/\")\n\t\t\tpp := \"\"\n\t\t\t// remove last element as its empy due to trailing /\n\t\t\tif len(sl) > 0 {\n\t\t\t\tsl = sl[:len(sl)-1]\n\t\t\t\tfor _, fld := range sl {\n\t\t\t\t\tpp = pp+fld+\"/\"\n\t\t\t\t\tpageVars.FList = append(pageVars.FList, FolderDetails{fld, pp})\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpageVars.FCount = len(pageVars.FList)\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\trender(w, \"objectlist\", pageVars)\n\t}\n\n}", "func ListBuckets(w http.ResponseWriter, r *http.Request) *appError {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n response, _ := s3Request(s3, \"\", \"GET\", \"/\", make(map[string][]string), \"\")\n listBucketsResp := &ListBucketsResp{}\n xml.NewDecoder(strings.NewReader(response.Body)).Decode(listBucketsResp)\n buckets := []string{}\n for _, bucket := range listBucketsResp.Buckets {\n buckets = append(buckets, bucket.Name)\n }\n rendering.JSON(w, http.StatusOK, buckets)\n\n return nil\n}", "func ListBuckets(w http.ResponseWriter, r *http.Request) *appError {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n response, _ := s3Request(s3, \"\", \"GET\", \"/\", make(map[string][]string), \"\")\n listBucketsResp := &ListBucketsResp{}\n xml.NewDecoder(strings.NewReader(response.Body)).Decode(listBucketsResp)\n buckets := []string{}\n for _, bucket := range listBucketsResp.Buckets {\n buckets = append(buckets, bucket.Name)\n }\n rendering.JSON(w, http.StatusOK, buckets)\n\n return nil\n}", "func (_DappboxManager *DappboxManagerCaller) ReturnAllDappboxSubFolders(opts *bind.CallOpts, dappboxAddress common.Address, index *big.Int) (string, string, *big.Int, bool, bool, error) {\n\tvar (\n\t\tret0 = new(string)\n\t\tret1 = new(string)\n\t\tret2 = new(*big.Int)\n\t\tret3 = new(bool)\n\t\tret4 = new(bool)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"returnAllDappboxSubFolders\", dappboxAddress, index)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, err\n}", "func TestFolders(t *testing.T) {\n api := New(*login, *password, *port, *verbose)\n\n Log(\"Testing AddFolder\")\n\n addFolderResponse, err := api.AddFolder(TmpDir)\n\n if err != nil {\n t.Errorf(\"Error making request to add new folder: %s\", err)\n return\n }\n\n if addFolderResponse.Error != 0 {\n t.Errorf(\"Error adding new folder\")\n return\n }\n\n Log(\"Testing GetFolders\")\n\n getFoldersResponse, err := api.GetFolders()\n\n if err != nil {\n t.Errorf(\"Error making request to get all folders: %s\", err)\n return\n }\n\n if len(*getFoldersResponse) == 0 {\n t.Errorf(\"Expected at least 1 folder\")\n return\n }\n\n found := false\n var testDir Folder\n for _, v := range *getFoldersResponse {\n if v.Dir == TmpDir {\n found = true\n testDir = v\n }\n }\n\n if !found {\n t.Errorf(\"Expected to find %s\", TmpDir)\n return\n }\n\n Log(\"Testing GetFolder\")\n\n getFolderResponse, err := api.GetFolder(testDir.Secret)\n if err != nil {\n t.Errorf(\"Error making request to get a single folder: %s\", err)\n return\n }\n\n if len(*getFolderResponse) != 1 {\n t.Errorf(\"Expected a single folder in response\")\n return\n }\n\n if (*getFolderResponse)[0].Dir != TmpDir {\n t.Errorf(\"Expected %s to be %s\", (*getFolderResponse)[0].Dir, TmpDir)\n return\n }\n\n Debug(\"Sleeping for 15 seconds to allow BTSync to pick up new file.\")\n\n time.Sleep(15000 * time.Millisecond)\n\n Log(\"Testing GetFiles\")\n\n getFilesResponse, err := api.GetFiles(testDir.Secret)\n if err != nil {\n t.Errorf(\"Error making request to get files: %s\", err)\n return\n }\n\n if len(*getFilesResponse) != 1 {\n t.Errorf(\"Expected 1 file\")\n return\n }\n\n if (*getFilesResponse)[0].Name != path.Base(TmpFile.Name()) {\n t.Errorf(\"Expected %s to be %s\", (*getFilesResponse)[0].Name, path.Base(TmpFile.Name()))\n return\n }\n\n Log(\"Testing SetFilePrefs\")\n\n setFilePrefsResponse, err := api.SetFilePrefs(testDir.Secret, path.Base(TmpFile.Name()), 1)\n if err != nil {\n t.Errorf(\"Error making request to set file preferences: %s\", err)\n return\n }\n\n if len(*setFilePrefsResponse) != 1 {\n t.Errorf(\"Expected response to have a length of 1\")\n }\n\n if (*setFilePrefsResponse)[0].State != \"created\" {\n t.Errorf(\"Expected file object in response\")\n return\n }\n\n Log(\"Testing GetFolderPeers\")\n _, err = api.GetFolderPeers(testDir.Secret)\n if err != nil {\n t.Errorf(\"Error making request to get folder peers: %s\", err)\n return\n }\n\n Log(\"Testing GetSecrets\")\n\n getSecretsResponse, err := api.GetSecrets(true)\n if err != nil {\n t.Errorf(\"Error requesting secrets\")\n return\n }\n\n if getSecretsResponse.Encryption == \"\" {\n t.Errorf(\"Expected response to have an encrypted key\")\n return\n }\n\n getSecretsResponse, err = api.GetSecretsForSecret(getSecretsResponse.ReadOnly)\n if err != nil {\n t.Errorf(\"Error requesting secrets for secret: %s\", getSecretsResponse.ReadOnly)\n return\n }\n\n if getSecretsResponse.ReadOnly == \"\" {\n t.Errorf(\"Expected response to have a read only key\")\n return\n }\n\n Log(\"Testing GetFolderPrefs\")\n\n getFolderPrefsResponse, err := api.GetFolderPrefs(testDir.Secret)\n if err != nil {\n t.Errorf(\"Error requesting prefs for folder\")\n return\n }\n\n if getFolderPrefsResponse.SearchLAN != 1 {\n t.Errorf(\"Exepected search_lan to be 1\")\n return\n }\n\n Log(\"Testing SetFolderPrefs\")\n\n prefs := &FolderPreferences{\n SearchLAN: 1,\n SelectiveSync: 1,\n UseDHT: 1,\n UseHosts: 1,\n UseRelayServer: 1,\n UseSyncTrash: 1,\n UseTracker: 1,\n }\n\n _, err = api.SetFolderPrefs(testDir.Secret, prefs)\n if err != nil {\n t.Errorf(\"Error making request to set folder preferences\")\n return\n }\n\n}", "func (_DappboxManager *DappboxManagerSession) ReturnAllDappboxFolders(dappboxAddress common.Address, index *big.Int) (string, string, common.Address, *big.Int, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func GetFolderBucketView(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *FolderBucketViewState, opts ...pulumi.ResourceOption) (*FolderBucketView, error) {\n\tvar resource FolderBucketView\n\terr := ctx.ReadResource(\"google-native:logging/v2:FolderBucketView\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *S3) BucketTree(bucket string) (string, error) {\n\toutputs, err := s.listObjects(bucket, \"/\")\n\tif err != nil || outputs == nil {\n\t\treturn \"\", err\n\t}\n\tvar contents []*s3.Object\n\tvar prefixes []*s3.CommonPrefix\n\tfor _, output := range outputs {\n\t\tcontents = append(contents, output.Contents...)\n\t\tprefixes = append(prefixes, output.CommonPrefixes...)\n\t}\n\ttree := treeprint.New()\n\t// Add top-level files.\n\tfor _, object := range contents {\n\t\ttree.AddNode(aws.StringValue(object.Key))\n\t}\n\t// Recursively add folders and their children.\n\tif err := s.addNodes(tree, prefixes, bucket); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tree.String(), nil\n}", "func recursiveFolderScanning(folder string) []string {\n\treturn scanGitFolders(make([]string, 0), folder)\n}", "func (c *Client) ListS3TopLevelDirs(bucket string) ([]string, error) {\n\t// find first top-level directory\n\ts3Objects, err := c.ListS3Prefix(bucket, \"\", false, pointer.Int64(1), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdirs := []string{}\n\tfor _, prefix := range ConvertS3ObjectsToKeys(s3Objects...) {\n\t\tdirs = append(dirs, files.GetTopLevelDirectory(prefix))\n\t}\n\n\t// detect all remaining top-level dirs\n\tfor {\n\t\tif len(dirs) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tpreviousDir := dirs[len(dirs)-1]\n\t\ts3Objects, err := c.ListS3Prefix(\n\t\t\tbucket,\n\t\t\t\"\",\n\t\t\ttrue,\n\t\t\tpointer.Int64(1),\n\t\t\tpointer.String(filepath.Join(previousDir, \"~~~\")),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(ConvertS3ObjectsToKeys(s3Objects...)) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tfor _, prefix := range ConvertS3ObjectsToKeys(s3Objects...) {\n\t\t\tdirs = append(dirs, files.GetTopLevelDirectory(prefix))\n\t\t}\n\t}\n\n\treturn dirs, nil\n}", "func (_DappboxManager *DappboxManagerCallerSession) ReturnAllDappboxFolders(dappboxAddress common.Address, index *big.Int) (string, string, common.Address, *big.Int, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func (c *AppsServices) Browse() ([]interface{}, error) {\n\tu, err := url.Parse(c.client.BaseURL.String() + \"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.client.UseAuthKey = true\n\tresp, err := GET(u.String(), c.client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data []interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func (i *Item) Browse(callback func([]byte) error) error {\n\treturn i.BrowseInto(\".\", callback)\n}", "func (instance *Network) Browse(ctx context.Context, callback func(*abstract.Network) fail.Error) (xerr fail.Error) {\n\tdefer fail.OnPanic(&xerr)\n\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\ttask, xerr := concurrency.TaskFromContext(ctx)\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tif task.Aborted() {\n\t\treturn fail.AbortedError(nil, \"aborted\")\n\t}\n\n\tinstance.lock.RLock()\n\tdefer instance.lock.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(func(buf []byte) fail.Error {\n\t\tif task.Aborted() {\n\t\t\treturn fail.AbortedError(nil, \"aborted\")\n\t\t}\n\n\t\tan := abstract.NewNetwork()\n\t\txerr := an.Deserialize(buf)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn xerr\n\t\t}\n\n\t\treturn callback(an)\n\t})\n}", "func (t *targetrunner) listbucket(w http.ResponseWriter, r *http.Request, bucket string) (tag string, ok bool) {\n\tvar (\n\t\tjsbytes []byte\n\t\terrstr string\n\t\terrcode int\n\t)\n\tislocal := t.bmdowner.get().islocal(bucket)\n\terrstr, errcode = t.checkLocalQueryParameter(bucket, r, islocal)\n\tif errstr != \"\" {\n\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\treturn\n\t}\n\tuseCache, errstr, errcode := t.checkCacheQueryParameter(r)\n\tif errstr != \"\" {\n\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\treturn\n\t}\n\tmsg := &GetMsg{}\n\tif t.readJSON(w, r, msg) != nil {\n\t\treturn\n\t}\n\tif islocal {\n\t\ttag = \"local\"\n\t\tif errstr, ok = t.doLocalBucketList(w, r, bucket, msg); errstr != \"\" {\n\t\t\tt.invalmsghdlr(w, r, errstr)\n\t\t}\n\t\treturn // ======================================>\n\t}\n\t// cloud bucket\n\tif useCache {\n\t\ttag = \"cloud cached\"\n\t\tjsbytes, errstr, errcode = t.listCachedObjects(bucket, msg)\n\t} else {\n\t\ttag = \"cloud\"\n\t\tjsbytes, errstr, errcode = getcloudif().listbucket(t.contextWithAuth(r), bucket, msg)\n\t}\n\tif errstr != \"\" {\n\t\tif errcode == 0 {\n\t\t\tt.invalmsghdlr(w, r, errstr)\n\t\t} else {\n\t\t\tt.invalmsghdlr(w, r, errstr, errcode)\n\t\t}\n\t\treturn\n\t}\n\tok = t.writeJSON(w, r, jsbytes, \"listbucket\")\n\treturn\n}", "func (s *S3Store) ListBucketFiles(bucket, prefix string) (prefixs []string, keys []KeyInfo, err error) {\n\tvar req s3.ListObjectsInput\n\tvar resp *s3.ListObjectsOutput\n\treq.SetBucket(bucket)\n\treq.SetPrefix(prefix)\n\treq.SetDelimiter(\"/\")\n\tif resp, err = s.svc.ListObjects(&req); err != nil {\n\t\treturn\n\t}\n\tfor _, c := range resp.Contents {\n\t\tvar info KeyInfo\n\t\tinfo.Key = aws.StringValue(c.Key)\n\t\tinfo.Size = aws.Int64Value(c.Size)\n\t\tinfo.Stamp = aws.TimeValue(c.LastModified)\n\t\tkeys = append(keys, info)\n\t}\n\tfor _, c := range resp.CommonPrefixes {\n\t\tprefixs = append(prefixs, aws.StringValue(c.Prefix))\n\t}\n\treturn\n}", "func (c *Client) Browse(code, filepath string) ([]string, error) {\n\t// TODO: Decide, based on the code, which provider to choose\n\treturn c.googledrive.Browse(code, filepath)\n}", "func (_DappboxManager *DappboxManagerSession) ReturnAllDappboxRemoteFolders(dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxRemoteFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func List(sess *session.Session, bucket string, prefix string) ([]S3Item, error) {\n\tsvc := s3.New(sess)\n\n\tdelimiter := \"/\"\n\n\tresp, err := svc.ListObjects(&s3.ListObjectsInput{\n\t\tBucket: aws.String(bucket),\n\t\tPrefix: aws.String(prefix),\n\t\tDelimiter: &delimiter,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := make([]S3Item, 0)\n\n\tfor _, p := range resp.CommonPrefixes {\n\t\tif strings.TrimSuffix(*(p.Prefix), \"/\") == strings.TrimSuffix(prefix, \"/\") {\n\t\t\tcontinue\n\t\t}\n\t\tpstr := *(p.Prefix)\n\t\tcutprefix := pstr[0 : len(pstr)-1]\n\t\tidxDelimiter := strings.LastIndex(cutprefix, \"/\")\n\t\tif idxDelimiter < 0 {\n\t\t\tidxDelimiter = -1\n\t\t}\n\t\titems = append(items, S3Item{\n\t\t\tType: \"directory\",\n\t\t\tName: cutprefix[idxDelimiter+1:],\n\t\t\tFullpath: *(p.Prefix),\n\t\t\tSize: sprintSize(0),\n\t\t\tLastModified: \"\",\n\t\t})\n\t}\n\tfor _, content := range resp.Contents {\n\t\tif strings.TrimSuffix(*(content.Key), \"/\") == strings.TrimSuffix(prefix, \"/\") {\n\t\t\tcontinue\n\t\t}\n\t\tkey := *(content.Key)\n\t\tidxDelimiter := strings.LastIndex(key, \"/\")\n\t\tif idxDelimiter < 0 {\n\t\t\tidxDelimiter = -1\n\t\t}\n\t\titems = append(items, S3Item{\n\t\t\tType: \"file\",\n\t\t\tName: key[idxDelimiter+1:],\n\t\t\tFullpath: key,\n\t\t\tSize: sprintSize(*(content.Size)),\n\t\t\tLastModified: content.LastModified.Format(\"2006-01-02 15:04:05\"),\n\t\t})\n\t}\n\n\treturn items, nil\n}", "func (_DappboxManager *DappboxManagerCallerSession) ReturnAllDappboxRemoteFolders(dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\treturn _DappboxManager.Contract.ReturnAllDappboxRemoteFolders(&_DappboxManager.CallOpts, dappboxAddress, index)\n}", "func (*hdfsProvider) ListBuckets(cmn.QueryBcks) (buckets cmn.Bcks, errCode int, err error) {\n\tdebug.Assert(false)\n\treturn\n}", "func (p *bucketProvider) ListObjects(ctx context.Context, bucket, path string, recursive bool) (buckets.ObjectIterator, error) {\n\tbkt := p.client.Bucket(bucket)\n\tif path != \"\" && !strings.HasSuffix(path, \"/\") {\n\t\t// An object can have the same name as a path prefix. Append a\n\t\t// \"/\" to make sure we don't include it.\n\t\tpath = path + \"/\"\n\t}\n\n\tvar delimiter string\n\tif recursive {\n\t\tdelimiter = \"\"\n\t} else {\n\t\tdelimiter = \"/\"\n\t}\n\n\tquery := &storage.Query{\n\t\tDelimiter: delimiter,\n\t\tPrefix: path,\n\t\tVersions: false,\n\t}\n\tit := bkt.Objects(ctx, query)\n\n\treturn &iteratorAdapter{\n\t\tit: it,\n\t\tbucket: bucket,\n\t}, nil\n}", "func (_DappboxManager *DappboxManagerCaller) ReturnAllDappboxFolders(opts *bind.CallOpts, dappboxAddress common.Address, index *big.Int) (string, string, common.Address, *big.Int, bool, bool, error) {\n\tvar (\n\t\tret0 = new(string)\n\t\tret1 = new(string)\n\t\tret2 = new(common.Address)\n\t\tret3 = new(*big.Int)\n\t\tret4 = new(bool)\n\t\tret5 = new(bool)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t\tret5,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"returnAllDappboxFolders\", dappboxAddress, index)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, *ret5, err\n}", "func getSageBucketGeneric(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\n\tsageBucketID := vars[\"bucket\"]\n\tif len(sageBucketID) != 36 {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"bucket id (%s) invalid (%d)\", sageBucketID, len(sageBucketID))\n\t\treturn\n\t}\n\n\tusername := vars[\"username\"]\n\n\t// r.URL.Path example: /api/v1/objects/6dd46856-c871-4089-b1bc-a12b44e92c81\n\n\t//pathArray := strings.SplitN(r.URL.Path, \"/\", 6)\n\n\t//keyPath := pathArray[5]\n\n\t_, sagePath, err := getSagePath(r.URL.Path)\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\n\t}\n\n\t// bucket permission\n\trawQuery := strings.ToLower(r.URL.RawQuery) // this is ugle, .Values() does not handle ?permissions as it has no value\n\n\t//log.Printf(\"rawQuery: %s\", rawQuery)\n\tif sagePath == \"\" && strings.Contains(rawQuery, \"permissions\") {\n\n\t\tallowed, err := userHasBucketPermission(username, sageBucketID, \"READ_ACP\")\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t\tif !allowed {\n\t\t\trespondJSONError(w, http.StatusUnauthorized, \"Access to bucket permissions denied (%s, %s)\", username, sageBucketID)\n\t\t\treturn\n\t\t}\n\n\t\tpermissions, err := ListBucketPermissions(sageBucketID)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\trespondJSON(w, http.StatusOK, permissions)\n\t\treturn\n\n\t}\n\n\t// bucket of directory listing\n\n\tallowed, err := userHasBucketPermission(username, sageBucketID, \"READ\")\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tif !allowed {\n\t\trespondJSONError(w, http.StatusUnauthorized, \"Read access to bucket denied (username: \\\"%s\\\", sageBucketID: \\\"%s\\\")\", username, sageBucketID)\n\t\treturn\n\t}\n\n\tif sagePath == \"\" {\n\t\t// bucket listing\n\t\tbucket, err := GetSageBucket(sageBucketID)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\trespondJSON(w, http.StatusOK, bucket)\n\t\treturn\n\t}\n\n\t// directory listing\n\tif strings.HasSuffix(sagePath, \"/\") {\n\n\t\t// _, sagePath, err := getSagePath(r.URL.Path)\n\t\t// if err != nil {\n\t\t// \trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t// \treturn\n\n\t\t// }\n\n\t\trecursive := false\n\t\tif strings.Contains(rawQuery, \"recursive\") {\n\t\t\tif !strings.Contains(rawQuery, \"recursive=false\") {\n\t\t\t\trecursive = true\n\t\t\t}\n\n\t\t}\n\t\tcontinuationToken, err := getQueryField(r, \"ContinuationToken\")\n\t\tif err != nil {\n\t\t\tcontinuationToken = \"\"\n\t\t}\n\n\t\tlimit, err := getQueryFieldInt64(r, \"limit\", 0)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error parsing query field limit: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif false {\n\t\t\tfiles, directories, newContinuationToken, err := listSageBucketContentDepreccated(sageBucketID, sagePath, recursive, 0, \"\", continuationToken)\n\n\t\t\tif err != nil {\n\t\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error listing bucket contents (sageBucketID: %s, sagePath: %s): %s\", sageBucketID, sagePath, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfiles = append(files, directories...)\n\n\t\t\t// Repsonse has some similiarity to https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html#API_ListObjectsV2_ResponseSyntax\n\n\t\t\tdata := make(map[string]interface{})\n\t\t\tdata[\"Contents\"] = files\n\n\t\t\tif newContinuationToken != \"\" {\n\t\t\t\tdata[\"NextContinuationToken\"] = newContinuationToken\n\t\t\t\tdata[\"IsTruncated\"] = true\n\t\t\t} else {\n\t\t\t\tdata[\"IsTruncated\"] = false\n\t\t\t}\n\n\t\t\trespondJSON(w, http.StatusOK, data)\n\t\t}\n\n\t\tlistObject, err := listSageBucketContent(sageBucketID, sagePath, recursive, limit, \"\", continuationToken)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error listing bucket contents (sageBucketID: %s, sagePath: %s): %s\", sageBucketID, sagePath, err.Error())\n\t\t\treturn\n\t\t}\n\t\trespondJSON(w, http.StatusOK, listObject)\n\n\t\treturn\n\t}\n\n\t// a file download\n\n\t//uuidStr := vars[\"bucket\"]\n\t//sageKey := vars[\"key\"]\n\n\t// convert SAGE specifiers to S3 specifiers\n\t//sageBucketID := s3BucketPrefix + sageBucketID[0:2]\n\n\ts3BucketID := getS3BucketID(sageBucketID) //s3BucketPrefix + sageBucketID[0:2]\n\n\ts3key := path.Join(sageBucketID, sagePath)\n\n\tsageFilename := path.Base(sagePath)\n\tif sageFilename == \".\" || sageFilename == \"/\" {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"Invalid filename (%s)\", sageFilename)\n\t\treturn\n\t}\n\n\tobjectInput := s3.GetObjectInput{\n\t\tBucket: &s3BucketID,\n\t\tKey: &s3key,\n\t}\n\n\tout, err := svc.GetObject(&objectInput)\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"Error getting data, svc.GetObject returned: %s\", err.Error())\n\t\treturn\n\t}\n\tdefer out.Body.Close()\n\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+sageFilename)\n\t//w.Header().Set(\"Content-Length\", FileSize)\n\n\tbuffer := make([]byte, 1024*1024)\n\tw.WriteHeader(http.StatusOK)\n\tfor {\n\t\tn, err := out.Body.Read(buffer)\n\t\tif err != nil {\n\n\t\t\tif err == io.EOF {\n\t\t\t\tw.Write(buffer[:n]) //should handle any remainding bytes.\n\t\t\t\tfileDownloadByteSize.Add(float64(n))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"Error getting data: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tw.Write(buffer[0:n])\n\t\tfileDownloadByteSize.Add(float64(n))\n\t}\n\n\treturn\n}", "func (s *synchronizer) restoreBucket(ctx context.Context, bucketSlug string) error {\n\n\tlocalBucket, err := s.getBucket(ctx, bucketSlug)\n\tif err != nil {\n\t\tlog.Error(\"Error in getBucket\", err)\n\t\treturn err\n\t}\n\n\tmirrorBucket, err := s.getMirrorBucket(ctx, bucketSlug)\n\tif err != nil {\n\t\tlog.Error(\"Error in getMirrorBucket\", err)\n\t\treturn err\n\t}\n\n\titerator := func(c context.Context, b *bucket.Bucket, itemPath string) error {\n\t\texists, _ := localBucket.FileExists(c, itemPath)\n\n\t\tif exists {\n\t\t\tnewerBucket, err := s.newerBucketPath(c, localBucket, mirrorBucket, itemPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif newerBucket == localBucket {\n\t\t\t\t// do not overwrite: mirror is not newer\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tbucketModel, err := s.model.FindBucket(ctx, bucketSlug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\titem, err := mirrorBucket.ListDirectory(ctx, itemPath)\n\t\tif s.eventNotifier != nil && err == nil {\n\t\t\tinfo := utils.MapDirEntryToFileInfo(api_buckets_pb.ListPathResponse(*item), itemPath)\n\t\t\tinfo.BackedUp = true\n\t\t\tinfo.LocallyAvailable = exists\n\t\t\tinfo.RestoreInProgress = true\n\t\t\ts.eventNotifier.SendFileEvent(events.NewFileEvent(info, events.FileRestoring, bucketSlug, bucketModel.DbID))\n\t\t}\n\n\t\ts.NotifyFileRestore(bucketSlug, itemPath)\n\t\treturn nil\n\t}\n\n\tif _, err = mirrorBucket.Each(ctx, \"\", iterator, true); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (*WorkspaceFoldersResponse_WorkspaceFolders) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{10, 0}\n}", "func listFiles(prefix, delimiter, marker string, maxKeys int, b *s3.Bucket) (files []s3.Key, err error) {\n\tresp, err := b.List(prefix, delimiter, marker, maxKeys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// append to files\n\tfor _, fl := range resp.Contents {\n\t\tif strings.Contains(fl.Key, \"index.html\") || strings.Contains(fl.Key, \"static\") || strings.Contains(fl.Key, \"logs\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tfiles = append(files, fl)\n\t}\n\n\t// recursion for the recursion god\n\tif resp.IsTruncated && resp.NextMarker != \"\" {\n\t\tf, err := listFiles(resp.Prefix, resp.Delimiter, resp.NextMarker, resp.MaxKeys, b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// append to files\n\t\tfiles = append(files, f...)\n\t}\n\n\treturn files, nil\n}", "func (b *Bucket) Bucket(name string) *Bucket { panic(\"n/i\") }", "func (c *storageClient) forEachObject(bucket, prefix string, recursive bool, fn func(*s3types.Object) error) error {\n\t// The \"/\" value can be used at command-level to mean that we want to\n\t// list from the root of the bucket, but the actual bucket root is an\n\t// empty prefix.\n\tif prefix == \"/\" {\n\t\tprefix = \"\"\n\t}\n\n\tdirs := make(map[string]struct{})\n\n\tvar ct string\n\tfor {\n\t\tres, err := c.ListObjectsV2(gContext, &s3.ListObjectsV2Input{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tPrefix: aws.String(prefix),\n\t\t\tContinuationToken: aws.String(ct),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tct = aws.ToString(res.NextContinuationToken)\n\n\t\tfor _, o := range res.Contents {\n\t\t\t// If not invoked in recursive mode, split object keys on the \"/\" separator and skip\n\t\t\t// objects \"below\" the base directory prefix.\n\t\t\tparts := strings.SplitN(strings.TrimPrefix(aws.ToString(o.Key), prefix), \"/\", 2)\n\t\t\tif len(parts) > 1 && !recursive {\n\t\t\t\tdir := path.Base(parts[0])\n\t\t\t\tif _, ok := dirs[dir]; !ok {\n\t\t\t\t\tdirs[dir] = struct{}{}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If the prefix doesn't end with a trailing prefix separator (\"/\"),\n\t\t\t// consider it as a single object key and match only one exact result\n\t\t\t// (except in recursive mode, where the prefix is expected to be a\n\t\t\t// \"directory\").\n\t\t\tif !recursive && !strings.HasSuffix(prefix, \"/\") && aws.ToString(o.Key) != prefix {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\to := o\n\t\t\tif err := fn(&o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif !res.IsTruncated {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *FoldersService) List() *FoldersListCall {\n\tc := &FoldersListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\treturn c\n}", "func syncBucket(name string) {\n\tobjects, err := s3.ListBucket(name, \"\")\n\tif err != nil {\n\t\tlog.Printf(\"Can't list objects in bucket: %v\", err)\n\t}\n\t// download each file that we don't have yet locally:\n\tfor _, object := range objects {\n\t\tlocalfile := filepath.Join(galleryPath, object)\n\t\tif _, err := os.Stat(localfile); err != nil {\n\t\t\terr = s3.DownloadFromBucket(\"gallery\", object, localfile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Can't download file %v: %v\", object, err)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Printf(\"Done downloading missing files from bucket %v\", name)\n\n\t// upload metadata files that are not yet remote:\n\tfiles, err := ioutil.ReadDir(galleryPath)\n\tif err != nil {\n\t\tlog.Printf(\"Can't scan local gallery for metadata: %v\", err)\n\t\treturn\n\t}\n\tfor _, f := range files {\n\t\tif strings.HasSuffix(f.Name(), \"meta\") {\n\t\t\tif !has(objects, f.Name()) {\n\t\t\t\terr = s3.UploadToBucket(\"gallery\", f.Name(), filepath.Join(galleryPath, f.Name()), \"text/plain\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Can't upload metadata file %v: %v\", f.Name(), err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (pstFile *File) GetSubFolders(folder Folder, formatType string) ([]Folder, error) {\n\ttableContext, err := pstFile.GetSubFolderTableContext(folder, formatType)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar subFolders []Folder\n\n\tfor _, tableContextRows := range tableContext {\n\t\thasSubFolders := false\n\n\t\tfor _, tableContextColumn := range tableContextRows {\n\t\t\tif tableContextColumn.PropertyID == 12289 {\n\t\t\t\tlog.Infof(\"Display name: %s\", string(tableContextColumn.Data))\n\t\t\t} else if tableContextColumn.PropertyID == 13834 {\n\t\t\t\thasSubFolders = tableContextColumn.ReferenceHNID == 1\n\t\t\t} else if tableContextColumn.PropertyID == 26610 {\n\t\t\t\tif !hasSubFolders {\n\t\t\t\t\t// This is supposed to be a sub-folder but\n\t\t\t\t\t// if there are actually no sub-folders this references a folder that doesn't exist.\n\t\t\t\t\t// This caused an issue where the table context was not found (because the folder doesn't exist).\n\t\t\t\t\t// References go-pst issue #1.\n\t\t\t\t\t// java-libpst doesn't perform this check so I assumed \"26610\" always indicated there is a sub-folder.\n\t\t\t\t\t// Special thanks to James McLeod (https://github.com/Jmcleodfoss/pstreader) for telling me to check if there are actually sub-folders.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tidentifierType := tableContextColumn.ReferenceHNID & 0x1F\n\n\t\t\t\tif identifierType == IdentifierTypeNormalFolder || identifierType == IdentifierTypeSearchFolder {\n\t\t\t\t\t// Find the data node from the reference HNID.\n\t\t\t\t\tnodeBTreeOffset, err := pstFile.GetNodeBTreeOffset(formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tnode, err := pstFile.FindBTreeNode(nodeBTreeOffset, tableContextColumn.ReferenceHNID, formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tdataIdentifier, err := node.GetDataIdentifier(formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tblockBTreeOffset, err := pstFile.GetBlockBTreeOffset(formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tdataNode, err := pstFile.FindBTreeNode(blockBTreeOffset, dataIdentifier, formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\theapOnNode, err := pstFile.GetHeapOnNode(dataNode, formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tpropertyContext, err := pstFile.GetPropertyContext(heapOnNode, formatType)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tsubFolders = append(subFolders, Folder{\n\t\t\t\t\t\tIdentifier: tableContextColumn.ReferenceHNID,\n\t\t\t\t\t\tPropertyContext: propertyContext,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"It's a message!\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn subFolders, nil\n}", "func (s *IMAPConnection) Folders() ([]string, error) {\n\n\tvar res []string\n\n\tmailboxes := make(chan *imap.MailboxInfo, 15)\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- s.conn.List(\"\", \"*\", mailboxes)\n\t}()\n\n\t// For each result save the name\n\tfor m := range mailboxes {\n\t\tres = append(res, m.Name)\n\t}\n\n\t// Wait for completion\n\tif err := <-done; err != nil {\n\t\treturn res, err\n\t}\n\n\t//\n\t// Sort the list of mailboxes in a case-insensitive fashion.\n\t//\n\tsort.Slice(res, func(i, j int) bool {\n\t\treturn strings.ToLower(res[i]) < strings.ToLower(res[j])\n\t})\n\n\treturn res, nil\n}", "func (i *Item) GetBucket() objectstorage.Bucket {\n\treturn i.folder.GetBucket()\n}", "func listBuckets(sess *session.Session, prefix string, t *testing.T) error {\n\t// Create S3 service client\n\tsvc := s3.New(sess)\n\n\tresult, err := svc.ListBuckets(nil)\n\tif err != nil {\n\t\tt.Log(\"Could not list buckets\")\n\t\treturn err\n\t}\n\n\tfor _, b := range result.Buckets {\n\t\tif strings.HasPrefix(*b.Name, prefix) {\n\t\t\tt.Log(*b.Name)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ScanForRepositories(directoryPath string) ([]string, error) {\n repoFolders := make([]string, 0)\n files, err := ioutil.ReadDir(directoryPath)\n if err == nil {\n for _, f := range files {\n if f.IsDir() {\n repoFolders = append(repoFolders, filepath.Join(directoryPath, f.Name()))\n }\n }\n }\n return repoFolders, err\n}", "func (g *gcsclient) AllFilesInDirectory(ctx context.Context, prefix string, callback func(item *storage.ObjectAttrs)) error {\n\ttotal := 0\n\tq := &storage.Query{Prefix: prefix, Versions: false}\n\tit := g.client.Bucket(g.bucket).Objects(ctx, q)\n\tfor obj, err := it.Next(); err != iterator.Done; obj, err = it.Next() {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Problem reading from Google Storage: %v\", err)\n\t\t}\n\t\ttotal++\n\t\tcallback(obj)\n\t}\n\treturn nil\n}", "func listFiles(prefix, delimiter, marker string, maxKeys int, b *s3.Bucket) (files []s3.Key, err error) {\n\tresp, err := b.List(prefix, delimiter, marker, maxKeys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// append to files\n\tfiles = append(files, resp.Contents...)\n\n\t// recursion for the recursion god\n\tif resp.IsTruncated && resp.NextMarker != \"\" {\n\t\tf, err := listFiles(resp.Prefix, resp.Delimiter, resp.NextMarker, resp.MaxKeys, b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// append to files\n\t\tfiles = append(files, f...)\n\t}\n\n\treturn files, nil\n}", "func (me *XsdGoPkgHasElems_Folder) Walk() (err error) {\r\n\tif fn := WalkHandlers.XsdGoPkgHasElems_Folder; me != nil {\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor _, x := range me.Folders {\r\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func Explore(client *storage.Client, thinClient *ThinClient, bucket string, prefix string) ([]*Node, error) {\n // Combine bucket lifecycle to each node\n ctx := context.Background()\n lifecycle, err := thinClient.Lifecycle(ctx, bucket)\n if err != nil {\n return nil, err\n }\n\n objs, err := listq(client, bucket, prefix, \"/\", false, true)\n if err != nil {\n return nil, err\n }\n var nodes []*Node\n for _, element := range objs {\n var node Node\n node.Bucket = bucket\n node.Lifecycle = lifecycle\n if element.Name == \"\" && element.Prefix != \"\" {\n node.Ntype = \"DIR\"\n node.Name = element.Prefix\n node.FQPN = element.Prefix\n } else {\n node.Ntype = \"OBJ\"\n pathSlice := strings.Split(element.Name, \"/\")\n pathLength := len(pathSlice)\n node.Name = pathSlice[pathLength - 1]\n node.FQPN = element.Name\n }\n node.ACL = element.ACL\n node.Owner = element.Owner\n node.Size = element.Size\n\n nodes = append(nodes, &node)\n }\n return nodes, nil\n}", "func (s kw_rest_folder) Find(path string, params ...interface{}) (result KiteObject, err error) {\n\tif len(params) == 0 {\n\t\tparams = SetParams(Query{\"deleted\": false})\n\t}\n\n\tfolder_path := SplitPath(path)\n\n\tvar current []KiteObject\n\n\tif s.folder_id <= 0 {\n\t\tcurrent, err = s.TopFolders(params)\n\t} else {\n\t\tcurrent, err = s.Folder(s.folder_id).Contents(params)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar found bool\n\n\tfolder_len := len(folder_path) - 1\n\n\tfor i, f := range folder_path {\n\t\tfound = false\n\t\tfor _, c := range current {\n\t\t\tif strings.ToLower(f) == strings.ToLower(c.Name) {\n\t\t\t\tresult = c\n\t\t\t\tif i < folder_len && c.Type == \"d\" {\n\t\t\t\t\tcurrent, err = s.Folder(c.ID).Contents(params)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t} else if i == folder_len {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif found == false {\n\t\t\treturn result, ErrNotFound\n\t\t}\n\t}\n\n\treturn result, ErrNotFound\n}", "func (p *FileInf) DlFolders() error {\r\n\tif p.Progress {\r\n\t\tif p.ShowFileInf {\r\n\t\t\tfmt.Printf(\"File finformation is retrieved from a folder '%s'.\\n\", p.FileName)\r\n\t\t} else {\r\n\t\t\tfmt.Printf(\"Files are downloaded from a folder '%s'.\\n\", p.FileName)\r\n\t\t}\r\n\t\tfmt.Println(\"Getting values to download.\")\r\n\t}\r\n\tfolT := &folderTree{}\r\n\tif p.getOwner() {\r\n\t\tq := \"mimeType='application/vnd.google-apps.folder' and trashed=false\"\r\n\t\tfields := \"files(id,mimeType,name,parents,size),nextPageToken\"\r\n\t\tfm := p.GetListLoop(q, fields)\r\n\t\tfT1 := &folderTr{Search: p.FileID}\r\n\t\tfolT = createFolderTreeID(fm, p.FileID, []string{}, fT1).getDlFoldersS(p.FileName)\r\n\t} else {\r\n\t\tfT2 := &folderTr{Search: p.FileID}\r\n\t\tfolT = p.getAllfoldersRecursively(p.FileID, []string{}, fT2).getDlFoldersS(p.FileName)\r\n\t}\r\n\tfileList := p.getFilesFromFolder(folT)\r\n\tp.dupChkFoldersFiles(fileList)\r\n\tif p.ShowFileInf {\r\n\t\tp.FolderTree = fileList\r\n\t\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"File list in folder '%s' was retrieved.\", p.FileName))\r\n\t\treturn nil\r\n\t}\r\n\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"Files were downloaded from folder '%s'.\", p.FileName))\r\n\tdlres := p.initDownload(fileList)\r\n\tif dlres != nil {\r\n\t\treturn dlres\r\n\t}\r\n\treturn nil\r\n}", "func (sb S3Buckets) emptyBucket(bucketName *string, isVersioned bool) error {\n\t// Since the error may happen in the inner function handler for the pager, we need a function scoped variable that\n\t// the inner function can set when there is an error.\n\tvar errOut error\n\tpageId := 1\n\n\t// Handle versioned buckets.\n\tif isVersioned {\n\t\terr := sb.Client.ListObjectVersionsPages(\n\t\t\t&s3.ListObjectVersionsInput{\n\t\t\t\tBucket: bucketName,\n\t\t\t\tMaxKeys: aws.Int64(int64(sb.MaxBatchSize())),\n\t\t\t},\n\t\t\tfunc(page *s3.ListObjectVersionsOutput, lastPage bool) (shouldContinue bool) {\n\t\t\t\tlogging.Logger.Debugf(\"Deleting page %d of object versions (%d objects) from bucket %s\", pageId, len(page.Versions), aws.StringValue(bucketName))\n\t\t\t\tif err := sb.deleteObjectVersions(bucketName, page.Versions); err != nil {\n\t\t\t\t\tlogging.Logger.Errorf(\"Error deleting objects versions for page %d from bucket %s: %s\", pageId, aws.StringValue(bucketName), err)\n\t\t\t\t\terrOut = err\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tlogging.Logger.Debugf(\"[OK] - deleted page %d of object versions (%d objects) from bucket %s\", pageId, len(page.Versions), aws.StringValue(bucketName))\n\n\t\t\t\tlogging.Logger.Debugf(\"Deleting page %d of deletion markers (%d deletion markers) from bucket %s\", pageId, len(page.DeleteMarkers), aws.StringValue(bucketName))\n\t\t\t\tif err := sb.deleteDeletionMarkers(bucketName, page.DeleteMarkers); err != nil {\n\t\t\t\t\tlogging.Logger.Debugf(\"Error deleting deletion markers for page %d from bucket %s: %s\", pageId, aws.StringValue(bucketName), err)\n\t\t\t\t\terrOut = err\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tlogging.Logger.Debugf(\"[OK] - deleted page %d of deletion markers (%d deletion markers) from bucket %s\", pageId, len(page.DeleteMarkers), aws.StringValue(bucketName))\n\n\t\t\t\tpageId++\n\t\t\t\treturn true\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif errOut != nil {\n\t\t\treturn errOut\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Handle non versioned buckets.\n\terr := sb.Client.ListObjectsV2Pages(\n\t\t&s3.ListObjectsV2Input{\n\t\t\tBucket: bucketName,\n\t\t\tMaxKeys: aws.Int64(int64(sb.MaxBatchSize())),\n\t\t},\n\t\tfunc(page *s3.ListObjectsV2Output, lastPage bool) (shouldContinue bool) {\n\t\t\tlogging.Logger.Debugf(\"Deleting object page %d (%d objects) from bucket %s\", pageId, len(page.Contents), aws.StringValue(bucketName))\n\t\t\tif err := sb.deleteObjects(bucketName, page.Contents); err != nil {\n\t\t\t\tlogging.Logger.Errorf(\"Error deleting objects for page %d from bucket %s: %s\", pageId, aws.StringValue(bucketName), err)\n\t\t\t\terrOut = err\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tlogging.Logger.Debugf(\"[OK] - deleted object page %d (%d objects) from bucket %s\", pageId, len(page.Contents), aws.StringValue(bucketName))\n\n\t\t\tpageId++\n\t\t\treturn true\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif errOut != nil {\n\t\treturn errOut\n\t}\n\treturn nil\n}", "func ListS3Bucket(awsregion string) string {\n\t// aws session credentials\n\taws_session := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// s3 session\n\ts3_session := s3.New(aws_session, aws.NewConfig().WithRegion(awsregion))\n\n\t// create bucket\n\tinput := &s3.ListBucketsInput{}\n\tresult, err := s3_session.ListBuckets(input)\n\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\tif len(result.Buckets) == 0 {\n\t\treturn \"Bucket list is empty\"\n\t}\n\treturn result.String()\n}", "func showFolder(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"<html>\\n<p>\" + folder + \"</p><pre>\\n\"))\n\tfor _, f := range images {\n\t\tw.Write([]byte(\"<a href=\\\"http://localhost:8080/folder/\" + f + \"\\\">\" + f + \"</a>\\n\"))\n\t}\n\tw.Write([]byte(\"</pre>\\n</html>\\n\"))\n}", "func (s *Syncthing) WaitForScanning(ctx context.Context, local bool) error {\n\tfor _, folder := range s.Folders {\n\t\tif err := s.waitForFolderScanning(ctx, folder, local); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (_DappboxManager *DappboxManagerCaller) ReturnAllDappboxRemoteFolders(opts *bind.CallOpts, dappboxAddress common.Address, index *big.Int) (string, common.Address, common.Address, bool, bool, error) {\n\tvar (\n\t\tret0 = new(string)\n\t\tret1 = new(common.Address)\n\t\tret2 = new(common.Address)\n\t\tret3 = new(bool)\n\t\tret4 = new(bool)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t}\n\terr := _DappboxManager.contract.Call(opts, out, \"returnAllDappboxRemoteFolders\", dappboxAddress, index)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, err\n}", "func (client *Client) ListBucketsWithCallback(request *ListBucketsRequest, callback func(response *ListBucketsResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ListBucketsResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ListBuckets(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func main() {\n\n\tfolders, err := ioutil.ReadDir(\"/tmp/a\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, folder := range folders {\n\t\tif !strings.HasPrefix(folder.Name(), \".\") {\n\t\t\tfmt.Println(folder.Name())\n\t\t}\n\t}\n}", "func (m *Main) LoadBucketContents() {\n\t// Use the commented line to restrict the number of files loaded (for local testing)\n\t//resp, err := m.S3svc.ListObjects(&s3.ListObjectsInput{Bucket: aws.String(m.Bucket), Prefix: aws.String(m.Prefix),MaxKeys: aws.Int64(10)})\n\tresp, err := m.S3svc.ListObjects(&s3.ListObjectsInput{Bucket: aws.String(m.Bucket), Prefix: aws.String(m.Prefix)})\n\tif err != nil {\n\t\texitErrorf(\"Unable to list items in bucket %q, %v\", m.Bucket, err)\n\t}\n\tm.S3files = resp.Contents\n}", "func GetBucketObjects(ctx *pulumi.Context, args *GetBucketObjectsArgs, opts ...pulumi.InvokeOption) (*GetBucketObjectsResult, error) {\n\tvar rv GetBucketObjectsResult\n\terr := ctx.Invoke(\"aws:s3/getBucketObjects:getBucketObjects\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (p *FileInf) getFilesFromFolder(folderTree *folderTree) *fileListDl {\r\n\tf := &fileListDl{}\r\n\tf.SearchedFolder.ID = p.FileID\r\n\tf.SearchedFolder.Name = p.FileName\r\n\tf.SearchedFolder.MimeType = p.MimeType\r\n\tf.SearchedFolder.Owners = p.Owners\r\n\tf.SearchedFolder.CreatedTime = p.CreatedTime\r\n\tf.SearchedFolder.ModifiedTime = p.ModifiedTime\r\n\tf.FolderTree = folderTree\r\n\tvar mType string\r\n\tif len(p.InputtedMimeType) > 0 {\r\n\t\tfor i, e := range p.InputtedMimeType {\r\n\t\t\tif i == 0 {\r\n\t\t\t\tmType = \" and (mimeType='\" + e + \"'\"\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tmType += \" or mimeType='\" + e + \"'\"\r\n\t\t}\r\n\t\tmType += \")\"\r\n\t}\r\n\tfor i, id := range folderTree.Folders {\r\n\t\tq := \"'\" + id + \"' in parents and mimeType != 'application/vnd.google-apps.folder' and trashed=false\" + mType\r\n\t\tfields := \"files(createdTime,description,id,mimeType,modifiedTime,name,owners,parents,permissions,shared,size,webContentLink,webViewLink),nextPageToken\"\r\n\t\tfm := p.GetListLoop(q, fields)\r\n\t\tvar fe fileListEle\r\n\t\tfe.FolderTree = folderTree.IDs[i]\r\n\t\tfe.Files = append(fe.Files, fm.Files...)\r\n\t\tf.FileList = append(f.FileList, fe)\r\n\t}\r\n\tf.TotalNumberOfFolders = int64(len(f.FolderTree.Folders))\r\n\tf.TotalNumberOfFiles = func() int64 {\r\n\t\tvar c int64\r\n\t\tfor _, e := range f.FileList {\r\n\t\t\tc += int64(len(e.Files))\r\n\t\t}\r\n\t\treturn c\r\n\t}()\r\n\treturn f\r\n}", "func (*ListFoldersRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_resourcemanager_v1_folder_service_proto_rawDescGZIP(), []int{1}\n}", "func (*ListFoldersResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_resourcemanager_v1_folder_service_proto_rawDescGZIP(), []int{2}\n}", "func restGetBucketPath(w http.ResponseWriter, r *http.Request) {\n\tbucketName := r.FormValue(\"name\")\n\tif len(bucketName) < 1 {\n\t\thttp.Error(w, \"bucket name is too short or is missing\", 400)\n\t\treturn\n\t}\n\tpath, err := BucketPath(bucketName)\n\tif err != nil {\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"could not compute BucketPath for name: %v, err: %v\",\n\t\t\t\tbucketName, err), 400)\n\t\treturn\n\t}\n\tw.Write([]byte(path))\n}", "func (service *S3Service) ListBuckets() ([]*S3Bucket,error) {\n request := service.newS3Request().prepare()\n response,err := request.execute(service.client)\n if err != nil {\n return nil, err\n }\n\n defer response.Close()\n\n // FIXME - process list of buckets\n return make([]*S3Bucket,0),nil\n}", "func (service *FolderServiceImpl) GetAll(username string, sortBy string, sortOrder string) ([]models.Folder, error) {\n\tfolders := make([]models.Folder, 0, len(service.folders))\n\tfor _, value := range service.folders {\n\t\tfolders = append(folders, *value)\n\t}\n\n\tif sortBy == \"sort_name\" {\n\t\tsort.Slice(folders, func(i, j int) bool {\n\t\t\tif sortOrder == \"asc\" {\n\t\t\t\treturn folders[i].Name < folders[j].Name\n\t\t\t} else if sortOrder == \"dsc\" {\n\t\t\t\treturn folders[i].Name > folders[j].Name\n\t\t\t} else {\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t} else if sortBy == \"sort_time\" {\n\t\tsort.Slice(folders, func(i, j int) bool {\n\t\t\tif sortOrder == \"asc\" {\n\t\t\t\treturn folders[i].CreatedAt.Before(folders[j].CreatedAt)\n\t\t\t} else if sortOrder == \"dsc\" {\n\t\t\t\treturn folders[i].CreatedAt.After(folders[j].CreatedAt)\n\t\t\t} else {\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t} else {\n\t\tsort.Slice(folders, func(i, j int) bool {\n\t\t\treturn folders[i].Name < folders[j].Name\n\t\t})\n\t}\n\n\treturn folders, nil\n}", "func cleanupBucket(bucketName string, c *minio.Client) error {\n\t// Create a done channel to control 'ListObjectsV2' go routine.\n\tdoneCh := make(chan struct{})\n\t// Exit cleanly upon return.\n\tdefer close(doneCh)\n\t// Iterate over all objects in the bucket via listObjectsV2 and delete\n\tfor objCh := range c.ListObjects(context.Background(), bucketName, minio.ListObjectsOptions{Recursive: true}) {\n\t\tif objCh.Err != nil {\n\t\t\treturn objCh.Err\n\t\t}\n\t\tif objCh.Key != \"\" {\n\t\t\terr := c.RemoveObject(context.Background(), bucketName, objCh.Key, minio.RemoveObjectOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor objPartInfo := range c.ListIncompleteUploads(context.Background(), bucketName, \"\", true) {\n\t\tif objPartInfo.Err != nil {\n\t\t\treturn objPartInfo.Err\n\t\t}\n\t\tif objPartInfo.Key != \"\" {\n\t\t\terr := c.RemoveIncompleteUpload(context.Background(), bucketName, objPartInfo.Key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\t// objects are already deleted, clear the buckets now\n\terr := c.RemoveBucket(context.Background(), bucketName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (i *Item) BrowseInto(path string, callback func([]byte) error) error {\n\tif callback == nil {\n\t\treturn fail.InvalidParameterError(\"callback\", \"cannot be nil!\")\n\t}\n\n\tif path == \"\" {\n\t\tpath = \".\"\n\t}\n\treturn i.folder.Browse(path, callback)\n}", "func (bucket Bucket) ListObjects(options ...Option) (ListObjectsResult, error) {\n\tvar out ListObjectsResult\n\n\toptions = append(options, EncodingType(\"url\"))\n\tparams, err := getRawParams(options)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\n\tresp, err := bucket.do(\"GET\", \"\", params, options, nil, nil)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\tdefer resp.Body.Close()\n\n\terr = xmlUnmarshal(resp.Body, &out)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\n\terr = decodeListObjectsResult(&out)\n\treturn out, err\n}", "func (b Bucket) ListObject(args ...Params) (*ListBucketResult, error) {\n\tv := new(ListBucketResult)\n\n\terr := b.Do(\"GET\", \"\", nil, v, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (api *API) GetFolders(ids []types.FolderID, params *parameters.GetFolders) (*types.Folders, error) {\n\ts := make([]string, 0, len(ids))\n\tfor _, id := range ids {\n\t\ts = append(s, string(id))\n\t}\n\tpath := fmt.Sprintf(\"/folders/%s\", strings.Join(s, \",\"))\n\n\tqp, err := query.Values(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := api.get(path, &qp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn types.NewFoldersFromJSON(data)\n}", "func NextBucket(dbPath, bucket string) (data db.Data, code int, err error) {\n\tif _, ok := allDB[dbPath]; !ok {\n\t\treturn data, http.StatusBadRequest, errors.New(\"There's no any db with such path (\" + dbPath + \")\")\n\t}\n\n\tdata, err = allDB[dbPath].Next(bucket)\n\tif err != nil {\n\t\treturn data, http.StatusInternalServerError, err\n\t}\n\n\treturn data, http.StatusOK, nil\n}", "func (storage *B2Storage) ListFiles(threadIndex int, dir string) (files []string, sizes []int64, err error) {\n for len(dir) > 0 && dir[len(dir) - 1] == '/' {\n dir = dir[:len(dir) - 1]\n }\n length := len(dir) + 1\n\n includeVersions := false\n if dir == \"chunks\" {\n includeVersions = true\n }\n\n entries, err := storage.clients[threadIndex].ListFileNames(dir, false, includeVersions)\n if err != nil {\n return nil, nil, err\n }\n\n if dir == \"snapshots\" {\n\n subDirs := make(map[string]bool)\n\n for _, entry := range entries {\n name := entry.FileName[length:]\n subDir := strings.Split(name, \"/\")[0]\n subDirs[subDir + \"/\"] = true\n }\n\n for subDir, _ := range subDirs {\n files = append(files, subDir)\n }\n } else if dir == \"chunks\" {\n lastFile := \"\"\n for _, entry := range entries {\n if entry.FileName == lastFile {\n continue\n }\n lastFile = entry.FileName\n if entry.Action == \"hide\" {\n files = append(files, entry.FileName[length:] + \".fsl\")\n } else {\n files = append(files, entry.FileName[length:])\n }\n sizes = append(sizes, entry.Size)\n }\n } else {\n for _, entry := range entries {\n files = append(files, entry.FileName[length:])\n }\n }\n\n return files, sizes, nil\n}", "func (api *bucketAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Bucket, error) {\n\tvar objlist []*Bucket\n\tobjs, err := api.ct.List(\"Bucket\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Bucket:\n\t\t\teobj := obj.(*Bucket)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Bucket\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func bucketParts(bucket string) (bucketname, path string) {\n\ts3Prefix := \"s3://\"\n\tif strings.HasPrefix(bucket, s3Prefix) {\n\t\tbucket = strings.Replace(bucket, s3Prefix, \"\", 1)\n\t}\n\tparts := strings.SplitN(bucket, \"/\", 2)\n\n\tif len(parts) <= 1 {\n\t\tpath = \"\"\n\t} else {\n\t\tpath = parts[1]\n\t}\n\treturn parts[0], path\n}", "func (mgr bucketsWatcher) Watch() {\n\twatchChan := mgr.client.Watch(context.Background(), mgr.bucketPathPrefix, etcd.WithPrefix(), etcd.WithPrevKV())\n\tgo func() {\n\t\tfor {\n\t\t\tresp, ok := <-watchChan\n\t\t\tif !ok || resp.Err() != nil {\n\t\t\t\tif ok {\n\t\t\t\t\tglog.Errorf(\"Watching channel returns: %v\", resp.Err())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Warningf(\"Watching channel closed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, evt := range resp.Events {\n\t\t\t\tswitch evt.Type {\n\t\t\t\tcase mvccpb.PUT:\n\t\t\t\t\tbkt, err := model.NewBucketFromBytes((*evt.Kv).Value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmgr.onBucketChanged(*bkt)\n\t\t\t\tcase mvccpb.DELETE:\n\t\t\t\t\tglog.V(3).Infof(\"deleted key: %s\", string((*evt.PrevKv).Key))\n\t\t\t\t\tglog.V(3).Infof(\"deleted value: %s\", string((*evt.PrevKv).Value))\n\t\t\t\t\tbkt, err := model.NewBucketFromBytes((*evt.PrevKv).Value)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tglog.V(2).Infof(\"Delete ACLs of bucket: %v\", bkt)\n\t\t\t\t\tmgr.onBucketDeleted(*bkt)\n\n\t\t\t\tdefault:\n\t\t\t\t\tglog.V(2).Infof(\"Unknown Etcd event: %v\", *evt)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif glog.V(3) {\n\t\t\t\tglog.Info(\"Bucket store: \")\n\t\t\t\tfor name, bkt := range mgr.bucketMap {\n\t\t\t\t\tglog.Infof(\"%s: %v\", name, bkt)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func (o *ObjectNode) getBucketV1Handler(w http.ResponseWriter, r *http.Request) {\n\t// check args\n\t_, bucket, _, vl, err := o.parseRequestParams(r)\n\tif err != nil {\n\t\tlog.LogErrorf(\"getBucketV1Handler: parse request parameters fail, requestID(%v) err(%v)\",\n\t\t\tRequestIDFromRequest(r), err)\n\t\t_ = NoSuchBucket.ServeResponse(w, r)\n\t\treturn\n\t}\n\n\t// get options\n\tmarker := r.URL.Query().Get(ParamMarker)\n\tprefix := r.URL.Query().Get(ParamPrefix)\n\tmaxKeys := r.URL.Query().Get(ParamMaxKeys)\n\tdelimiter := r.URL.Query().Get(ParamPartDelimiter)\n\n\tvar maxKeysInt uint64\n\tif maxKeys != \"\" {\n\t\tmaxKeysInt, err = strconv.ParseUint(maxKeys, 10, 16)\n\t\tif err != nil {\n\t\t\tlog.LogErrorf(\"getBucketV1Handler: parse max key fail, requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\t\treturn\n\t\t}\n\t\tif maxKeysInt > MaxKeys {\n\t\t\tmaxKeysInt = MaxKeys\n\t\t}\n\t} else {\n\t\tmaxKeysInt = uint64(MaxKeys)\n\t}\n\n\tlistBucketRequest := &ListBucketRequestV1{\n\t\tprefix: prefix,\n\t\tdelimiter: delimiter,\n\t\tmarker: marker,\n\t\tmaxKeys: maxKeysInt,\n\t}\n\n\tfsFileInfos, nextMarker, isTruncated, prefixes, err := vl.ListFilesV1(listBucketRequest)\n\tif err != nil {\n\t\tlog.LogErrorf(\"getBucketV1Handler: list file fail, requestID(%v), err(%v)\", r.URL, err)\n\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\treturn\n\t}\n\n\t// get owner\n\taceesKey, _ := vl.OSSSecure()\n\tbucketOwner := NewBucketOwner(aceesKey)\n\tvar contents = make([]*Content, 0)\n\tif len(fsFileInfos) > 0 {\n\t\tfor _, fsFileInfo := range fsFileInfos {\n\t\t\tcontent := &Content{\n\t\t\t\tKey: fsFileInfo.Path,\n\t\t\t\tLastModified: formatTimeISO(fsFileInfo.ModifyTime),\n\t\t\t\tETag: fsFileInfo.ETag,\n\t\t\t\tSize: int(fsFileInfo.Size),\n\t\t\t\tStorageClass: StorageClassStandard,\n\t\t\t\tOwner: bucketOwner,\n\t\t\t}\n\t\t\tcontents = append(contents, content)\n\t\t}\n\t}\n\n\tvar commonPrefixes = make([]*CommonPrefix, 0)\n\tfor _, prefix := range prefixes {\n\t\tcommonPrefix := &CommonPrefix{\n\t\t\tPrefix: prefix,\n\t\t}\n\t\tcommonPrefixes = append(commonPrefixes, commonPrefix)\n\t}\n\n\tlistBucketResult := &ListBucketResult{\n\t\tBucket: bucket,\n\t\tPrefix: prefix,\n\t\tMarker: marker,\n\t\tMaxKeys: int(maxKeysInt),\n\t\tDelimiter: delimiter,\n\t\tIsTruncated: isTruncated,\n\t\tNextMarker: nextMarker,\n\t\tContents: contents,\n\t\tCommonPrefixes: commonPrefixes,\n\t}\n\n\tvar bytes []byte\n\tvar marshalError error\n\tif bytes, marshalError = MarshalXMLEntity(listBucketResult); marshalError != nil {\n\t\tlog.LogErrorf(\"getBucketV1Handler: marshal result fail, requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\treturn\n\t}\n\n\t// set response header\n\tw.Header().Set(HeaderNameContentType, HeaderValueContentTypeXML)\n\tw.Header().Set(HeaderNameContentLength, strconv.Itoa(len(bytes)))\n\tw.Write(bytes)\n\n\treturn\n}", "func ListObjects(bucketName string, keyPrefix string) (keysList []*string, err error) {\n\tsvc := s3.New(sessionutils.Session)\n\tres, err := svc.ListObjects(&s3.ListObjectsInput{\n\t\tBucket: aws.String(bucketName),\n\t\tPrefix: aws.String(keyPrefix),\n\t})\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error listing bucket:\\n%v\\n\", err)\n\t\treturn keysList, err\n\t}\n\n\tif len(res.Contents) > 0 {\n\t\tfor _, obj := range res.Contents {\n\t\t\tkeysList = append(keysList, obj.Key)\n\t\t}\n\t}\n\n\treturn keysList, nil\n\n}", "func getObjectsPage(bucketObjectsList *s3.ListObjectsV2Output, s3Client *s3.S3, bucketName string) {\n\n\t// Iterate through the files inside the bucket\n\tfor _, key := range bucketObjectsList.Contents {\n\t\ts3Key := *key.Key\n\n\t\tcount++\n\n\t\ts3Prefix, videoID, parseErr := parseS3Key(s3Key)\n\t\tif parseErr != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif count%1000 == 0 {\n\t\t\tfmt.Printf(\"s3key: count %d, key %s, s3prefix %s, videoID %s\\n\", count, s3Key, s3Prefix, videoID)\n\t\t}\n\n\t\t_, dberr := db.Exec(sqlInsertStmt,\n\t\t\tvideoID,\n\t\t\ts3BucketName,\n\t\t\ts3Prefix,\n\t\t\ts3Key)\n\t\tif dberr != nil {\n\t\t\tfmt.Println(\"DB insert Error\", dberr)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func list_arches(w rest.ResponseWriter, r *rest.Request) {\n\t// Use caching to reduce calls to the Dropbox API\n\tcache_path := \"arches\"\n\tdata, found := cache_instance.Get(cache_path)\n\tif found {\n\t\tif cached, ok := data.([]string); ok {\n\t\t\tw.WriteJson(cached)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Println(\"Error: Unable to retrieve from cache\")\n\t\t}\n\t}\n\n\tarches := []string{}\n\tdirectories := get_directories(cache_instance, db, \"/\")\n\tfor _, arch := range directories {\n\t\tarches = append(arches, strings.Replace(arch.Path, \"/\", \"\", -1))\n\t}\n\tcache_instance.Set(cache_path, arches, 0)\n\tw.WriteJson(arches)\n}", "func (c *FoldersSearchCall) Pages(ctx context.Context, f func(*SearchFoldersResponse) error) error {\n\tc.ctx_ = ctx\n\tdefer func(pt string) { c.searchfoldersrequest.PageToken = pt }(c.searchfoldersrequest.PageToken) // reset paging to original point\n\tfor {\n\t\tx, err := c.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f(x); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif x.NextPageToken == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tc.searchfoldersrequest.PageToken = x.NextPageToken\n\t}\n}", "func getRemoteFolder(uid string) (*grizzly.Resource, error) {\n\tclient := new(http.Client)\n\th := FolderHandler{}\n\tif uid == \"General\" || uid == \"general\" {\n\t\tfolder := Folder{\n\t\t\t\"id\": 0.0,\n\t\t\t\"uid\": uid,\n\t\t\t\"title\": \"General\",\n\t\t}\n\t\tresource := grizzly.NewResource(h.APIVersion(), h.Kind(), uid, folder)\n\t\treturn &resource, nil\n\t}\n\tgrafanaURL, err := getGrafanaURL(\"api/folders/\" + uid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", grafanaURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif grafanaToken, ok := getGrafanaToken(); ok {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+grafanaToken)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tswitch {\n\tcase resp.StatusCode == http.StatusNotFound:\n\t\treturn nil, fmt.Errorf(\"couldn't fetch folder '%s' from remote: %w\", uid, grizzly.ErrNotFound)\n\tcase resp.StatusCode >= 400:\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\n\tdata, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar f Folder\n\tif err := json.Unmarshal(data, &f); err != nil {\n\t\treturn nil, grizzly.APIErr{Err: err, Body: data}\n\t}\n\tresource := grizzly.NewResource(h.APIVersion(), h.Kind(), uid, f)\n\treturn &resource, nil\n}", "func (fl *FolderList) ReadDirAll(ctx context.Context) (res []fuse.Dirent, err error) {\n\tfl.fs.vlog.CLogf(ctx, libkb.VLog1, \"FL ReadDirAll\")\n\tdefer func() {\n\t\terr = fl.fs.processError(ctx, libkbfs.ReadMode, err)\n\t}()\n\tsession, err := fl.fs.config.KBPKI().GetCurrentSession(ctx)\n\tisLoggedIn := err == nil\n\n\tvar favs []favorites.Folder\n\tif isLoggedIn {\n\t\tfavs, err = fl.fs.config.KBFSOps().GetFavorites(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres = make([]fuse.Dirent, 0, len(favs))\n\tfor _, fav := range favs {\n\t\tif fav.Type != fl.tlfType {\n\t\t\tcontinue\n\t\t}\n\t\tpname, err := tlf.CanonicalToPreferredName(\n\t\t\tsession.Name, tlf.CanonicalName(fav.Name))\n\t\tif err != nil {\n\t\t\tfl.fs.log.Errorf(\"CanonicalToPreferredName: %q %v\", fav.Name, err)\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, fuse.Dirent{\n\t\t\tType: fuse.DT_Dir,\n\t\t\tName: string(pname),\n\t\t})\n\t}\n\treturn res, nil\n}", "func GetBucket(tx *bolt.Tx, path Path) (b *bolt.Bucket) {\n\tif len(path) == 0 {\n\t\tpanic(\"Path must have at least one element\")\n\t}\n\tb = tx.Bucket(path[0])\n\tif len(path) == 1 || b == nil {\n\t\treturn\n\t}\n\tfor _, bucket := range path[1:] {\n\t\tif b = b.Bucket(bucket); b == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (rpcMethod *RPCMethod) listKeys(response *ResponseParameters) error {\n\n\t//open a read transaction\n\trpcMethod.rpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\n\t\t//append to reselt the list of buckets\n\t\tresponse.Result = make([]interface{}, 0, 10)\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\trpcMethod.rpcServer.logger.Println(\"BUCKET \", string(k))\n\t\t\tresponse.Result = append(response.Result, string(k))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tresponse.Error = nil\n\n\treturn nil\n\n}", "func (rpcMethod *RPCMethod) listKeys(response *ResponseParameters) error {\n\n\t//open a read transaction\n\trpcMethod.rpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\n\t\t//append to reselt the list of buckets\n\t\tresponse.Result = make([]interface{}, 0, 10)\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\trpcMethod.rpcServer.logger.Println(\"BUCKET \", string(k))\n\t\t\tresponse.Result = append(response.Result, string(k))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tresponse.Error = nil\n\n\treturn nil\n\n}", "func GetSubFolderList(root string) (folderList []string) {\n\tfiles, err := ioutil.ReadDir(root)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfor _, file := range files {\n\t\tif file.IsDir() {\n\t\t\tfolderList = append(folderList, file.Name())\n\t\t}\n\t}\n\treturn\n}", "func (b *Bucket) Iter(_ context.Context, dir string, f func(string) error) error {\n\tunique := map[string]struct{}{}\n\n\tfor filename := range b.objects {\n\t\tif !strings.HasPrefix(filename, dir) {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitAfter(filename, \"/\")\n\t\tunique[parts[0]] = struct{}{}\n\t}\n\tvar keys []string\n\tfor n := range unique {\n\t\tkeys = append(keys, n)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tif err := f(k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o MicrosoftGraphMailSearchFolder) MarshalJSON() ([]byte, error) {\n\ttoSerialize := map[string]interface{}{}\n\tif o.Id != nil {\n\t\ttoSerialize[\"id\"] = o.Id\n\t}\n\tif o.DisplayName == nil {\n\t\tif o.isExplicitNullDisplayName {\n\t\t\ttoSerialize[\"displayName\"] = o.DisplayName\n\t\t}\n\t} else {\n\t\ttoSerialize[\"displayName\"] = o.DisplayName\n\t}\n\tif o.ParentFolderId == nil {\n\t\tif o.isExplicitNullParentFolderId {\n\t\t\ttoSerialize[\"parentFolderId\"] = o.ParentFolderId\n\t\t}\n\t} else {\n\t\ttoSerialize[\"parentFolderId\"] = o.ParentFolderId\n\t}\n\tif o.ChildFolderCount == nil {\n\t\tif o.isExplicitNullChildFolderCount {\n\t\t\ttoSerialize[\"childFolderCount\"] = o.ChildFolderCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"childFolderCount\"] = o.ChildFolderCount\n\t}\n\tif o.UnreadItemCount == nil {\n\t\tif o.isExplicitNullUnreadItemCount {\n\t\t\ttoSerialize[\"unreadItemCount\"] = o.UnreadItemCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"unreadItemCount\"] = o.UnreadItemCount\n\t}\n\tif o.TotalItemCount == nil {\n\t\tif o.isExplicitNullTotalItemCount {\n\t\t\ttoSerialize[\"totalItemCount\"] = o.TotalItemCount\n\t\t}\n\t} else {\n\t\ttoSerialize[\"totalItemCount\"] = o.TotalItemCount\n\t}\n\tif o.SingleValueExtendedProperties != nil {\n\t\ttoSerialize[\"singleValueExtendedProperties\"] = o.SingleValueExtendedProperties\n\t}\n\tif o.MultiValueExtendedProperties != nil {\n\t\ttoSerialize[\"multiValueExtendedProperties\"] = o.MultiValueExtendedProperties\n\t}\n\tif o.Messages != nil {\n\t\ttoSerialize[\"messages\"] = o.Messages\n\t}\n\tif o.MessageRules != nil {\n\t\ttoSerialize[\"messageRules\"] = o.MessageRules\n\t}\n\tif o.ChildFolders != nil {\n\t\ttoSerialize[\"childFolders\"] = o.ChildFolders\n\t}\n\tif o.IsSupported == nil {\n\t\tif o.isExplicitNullIsSupported {\n\t\t\ttoSerialize[\"isSupported\"] = o.IsSupported\n\t\t}\n\t} else {\n\t\ttoSerialize[\"isSupported\"] = o.IsSupported\n\t}\n\tif o.IncludeNestedFolders == nil {\n\t\tif o.isExplicitNullIncludeNestedFolders {\n\t\t\ttoSerialize[\"includeNestedFolders\"] = o.IncludeNestedFolders\n\t\t}\n\t} else {\n\t\ttoSerialize[\"includeNestedFolders\"] = o.IncludeNestedFolders\n\t}\n\tif o.SourceFolderIds != nil {\n\t\ttoSerialize[\"sourceFolderIds\"] = o.SourceFolderIds\n\t}\n\tif o.FilterQuery == nil {\n\t\tif o.isExplicitNullFilterQuery {\n\t\t\ttoSerialize[\"filterQuery\"] = o.FilterQuery\n\t\t}\n\t} else {\n\t\ttoSerialize[\"filterQuery\"] = o.FilterQuery\n\t}\n\treturn json.Marshal(toSerialize)\n}", "func get_directories(cache *cache.Cache, db *dropbox.Dropbox, path string) []dropbox.Entry {\n\treturn get(cache, db, path, true)\n}", "func getBucketListByCand(candName string, offset, limit uint32) error {\n\tbl, err := getBucketListByCandidateName(candName, offset, limit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar bucketlist []*bucket\n\tfor _, b := range bl.Buckets {\n\t\tbucket, err := newBucket(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbucketlist = append(bucketlist, bucket)\n\t}\n\tmessage := bucketlistMessage{\n\t\tNode: config.ReadConfig.Endpoint,\n\t\tBucketlist: bucketlist,\n\t}\n\tfmt.Println(message.String())\n\treturn nil\n}", "func (fs *MediaScan) Folders()\t(string, string)\t{\n\treturn fs.baseFolder, fs.subFolder\n}", "func (o *OrgHelper) GetFolders(orgId string) (map[string]string, error) {\n\tlog := zapr.NewLogger(zap.L())\n\t// Map from the name of the folder to an id in the form folders/{folder_id} which is what delete expects\n\tfolders := map[string]string{}\n\n\taddToMap := func(r *crmV2.ListFoldersResponse) error {\n\t\tfor _, f := range r.Folders {\n\t\t\tfolders[f.DisplayName] = f.Name\n\t\t}\n\t\treturn nil\n\t}\n\terr := o.CrmV2.Folders.List().Parent(orgId).Pages(context.Background(), addToMap)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Error listing folders\")\n\t\treturn nil, err\n\t}\n\treturn folders, nil\n}", "func (s *Server) getMusicFolders(w http.ResponseWriter, r *http.Request) {\n\twriteXML(w, func(c *container) {\n\t\tc.MusicFolders = &musicFoldersContainer{\n\t\t\tMusicFolders: []musicFolder{{\n\t\t\t\tID: 0,\n\t\t\t\tName: filepath.Base(s.cfg.MusicDirectory),\n\t\t\t}},\n\t\t}\n\t})\n}", "func (b *fakeBosClient) ListBuckets() (*api.ListBucketsResult, error) {\n\treturn nil, fmt.Errorf(\"test\")\n}" ]
[ "0.70128626", "0.6111621", "0.57208186", "0.56158614", "0.5615491", "0.56025773", "0.55973977", "0.55546415", "0.5527702", "0.5513741", "0.5493884", "0.54737747", "0.54476845", "0.54204756", "0.5355094", "0.53297883", "0.53297883", "0.5266897", "0.52652836", "0.525378", "0.52460086", "0.5242307", "0.5234564", "0.5233253", "0.52170295", "0.5215807", "0.5210468", "0.51941437", "0.5189291", "0.5163016", "0.5155896", "0.5135758", "0.5085357", "0.50675815", "0.50672364", "0.506577", "0.505509", "0.50354165", "0.5012738", "0.50090486", "0.5006982", "0.4992382", "0.49815702", "0.49713174", "0.49582988", "0.4953542", "0.49422154", "0.4932506", "0.49225032", "0.49192", "0.491867", "0.49167556", "0.48983198", "0.4890916", "0.48836476", "0.48792827", "0.4877854", "0.4866947", "0.4857483", "0.48527178", "0.48446426", "0.4842421", "0.48392606", "0.48189977", "0.48187155", "0.48183557", "0.4802622", "0.4802583", "0.4790379", "0.4782661", "0.47815102", "0.47782856", "0.47751474", "0.47722748", "0.4771633", "0.4762907", "0.47518027", "0.4747576", "0.47452953", "0.47384962", "0.47378075", "0.47237086", "0.4717952", "0.47176751", "0.4709097", "0.47070467", "0.47007415", "0.4700127", "0.46999925", "0.4696665", "0.4696665", "0.4682844", "0.4675283", "0.46750945", "0.46702436", "0.46702138", "0.466661", "0.46623856", "0.46584675", "0.46582577" ]
0.78961796
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseBucketFoldersExecute(r ApiBrowseBucketFoldersRequest) (BucketFoldersPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue BucketFoldersPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseBucketFolders") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/browseBucketFolders/{bucketId}" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarPath = strings.Replace(localVarPath, "{"+"bucketId"+"}", _neturl.PathEscape(parameterToString(r.bucketId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.offset != nil { localVarQueryParams.Add("Offset", parameterToString(*r.offset, "")) } if r.limit != nil { localVarQueryParams.Add("Limit", parameterToString(*r.limit, "")) } if r.sort != nil { localVarQueryParams.Add("Sort", parameterToString(*r.sort, "csv")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.7777472", "0.7582237", "0.741292", "0.7358592", "0.7292706", "0.72179556", "0.72150666", "0.7154164", "0.7144244", "0.70236844", "0.6968861", "0.69574517", "0.6857601", "0.68203115", "0.6786843", "0.67499226", "0.6732799", "0.6726702", "0.664588", "0.66373837", "0.66341907", "0.66192603", "0.6618354", "0.65951604", "0.6592189", "0.6544029", "0.65052474", "0.6500035", "0.6499713", "0.6493198", "0.6459492", "0.64537424", "0.64339274", "0.64231", "0.6411837", "0.6354237", "0.6342012", "0.6331562", "0.63293886", "0.63235724", "0.63210624", "0.63129383", "0.63012326", "0.62950426", "0.62711006", "0.6269801", "0.62694305", "0.62559414", "0.62376016", "0.61896044", "0.61866677", "0.6157971", "0.61576515", "0.6157038", "0.61556566", "0.6138981", "0.61365765", "0.61309266", "0.61302364", "0.61298376", "0.6119938", "0.61105776", "0.6102657", "0.6093387", "0.609142", "0.6079346", "0.6078881", "0.6075695", "0.6045966", "0.6045463", "0.60427797", "0.6032737", "0.603158", "0.6027389", "0.60167104", "0.60026646", "0.5987349", "0.5974702", "0.5971437", "0.59703684", "0.5965762", "0.59478134", "0.5939073", "0.59338975", "0.59321105", "0.5925759", "0.5913415", "0.59012485", "0.58960927", "0.5890233", "0.5883923", "0.58764994", "0.5875759", "0.58713603", "0.58534265", "0.5852063", "0.5849181", "0.58465594", "0.5846279", "0.58363706", "0.58326805" ]
0.0
-1
/ BrowseCloudNetworks Method for BrowseCloudNetworks
func (a *AmazonConnectionsApiService) BrowseCloudNetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudNetworksRequest { return ApiBrowseCloudNetworksRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseCloudNetworksExecute(r ApiBrowseCloudNetworksRequest) (CloudNetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudNetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudNetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudNetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSubnetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSubnetworksRequest {\n\treturn ApiBrowseCloudSubnetworksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (s *Stack) ListNetworks() ([]*abstract.Network, fail.Error) {\n\tvar networks []*abstract.Network\n\n\tcompuService := s.ComputeService\n\n\ttoken := \"\"\n\tfor paginate := true; paginate; {\n\t\tresp, err := compuService.Networks.List(s.GcpConfig.ProjectID).PageToken(token).Do()\n\t\tif err != nil {\n\t\t\treturn networks, fail.Errorf(fmt.Sprintf(\"cannot list networks ...: %s\", err), err)\n\t\t}\n\n\t\tfor _, nett := range resp.Items {\n\t\t\tnewNet := abstract.NewNetwork()\n\t\t\tnewNet.Name = nett.Name\n\t\t\tnewNet.ID = strconv.FormatUint(nett.Id, 10)\n\t\t\tnewNet.CIDR = nett.IPv4Range\n\n\t\t\tnetworks = append(networks, newNet)\n\t\t}\n\t\ttoken := resp.NextPageToken\n\t\tpaginate = token != \"\"\n\t}\n\n\ttoken = \"\"\n\tfor paginate := true; paginate; {\n\t\tresp, err := compuService.Subnetworks.List(s.GcpConfig.ProjectID, s.GcpConfig.Region).PageToken(token).Do()\n\t\tif err != nil {\n\t\t\treturn networks, fail.Errorf(fmt.Sprintf(\"cannot list subnetworks ...: %s\", err), err)\n\t\t}\n\n\t\tfor _, nett := range resp.Items {\n\t\t\tnewNet := abstract.NewNetwork()\n\t\t\tnewNet.Name = nett.Name\n\t\t\tnewNet.ID = strconv.FormatUint(nett.Id, 10)\n\t\t\tnewNet.CIDR = nett.IpCidrRange\n\n\t\t\tnetworks = append(networks, newNet)\n\t\t}\n\t\ttoken := resp.NextPageToken\n\t\tpaginate = token != \"\"\n\t}\n\n\treturn networks, nil\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSubnetworksExecute(r ApiBrowseCloudSubnetworksRequest) (CloudSubnetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSubnetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSubnetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSubnetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.availabilityZone != nil {\n\t\tlocalVarQueryParams.Add(\"availabilityZone\", parameterToString(*r.availabilityZone, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c *Client) GetAllNetworks() ([]byte, error) {\n\treturn c.doGet(master.GetNetworksRESTEndpoint)\n}", "func (instance *Network) Browse(ctx context.Context, callback func(*abstract.Network) fail.Error) (xerr fail.Error) {\n\tdefer fail.OnPanic(&xerr)\n\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\ttask, xerr := concurrency.TaskFromContext(ctx)\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tif task.Aborted() {\n\t\treturn fail.AbortedError(nil, \"aborted\")\n\t}\n\n\tinstance.lock.RLock()\n\tdefer instance.lock.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(func(buf []byte) fail.Error {\n\t\tif task.Aborted() {\n\t\t\treturn fail.AbortedError(nil, \"aborted\")\n\t\t}\n\n\t\tan := abstract.NewNetwork()\n\t\txerr := an.Deserialize(buf)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn xerr\n\t\t}\n\n\t\treturn callback(an)\n\t})\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroups(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSecurityGroupsRequest {\n\treturn ApiBrowseCloudSecurityGroupsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func handleNetworks(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {\n\tcursor := getCursor(r.URL)\n\twr, err := sm.WatchNetworks(ctx, cursor)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprint(w, err)\n\t\treturn\n\t}\n\n\tswitch wr.Cursor.(type) {\n\tcase string:\n\tcase fmt.Stringer:\n\t\twr.Cursor = wr.Cursor.(fmt.Stringer).String()\n\tdefault:\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprint(w, fmt.Errorf(\"internal error: watch cursor is of unknown type\"))\n\t\treturn\n\t}\n\n\tjsonResponse(w, http.StatusOK, wr)\n}", "func (c *TestClient) ListNetworks(project string, opts ...ListCallOption) ([]*compute.Network, error) {\n\tif c.ListNetworksFn != nil {\n\t\treturn c.ListNetworksFn(project, opts...)\n\t}\n\treturn c.client.ListNetworks(project, opts...)\n}", "func networkListExample() string {\n\treturn `$ pouch network ls\nNETWORK ID NAME DRIVER SCOPE\n6f7aba8a58 net2 bridge\n55f134176c net3 bridge\ne495f50913 net1 bridge\n`\n}", "func (c *TestClient) ListSubnetworks(project, region string, opts ...ListCallOption) ([]*compute.Subnetwork, error) {\n\tif c.ListSubnetworksFn != nil {\n\t\treturn c.ListSubnetworksFn(project, region, opts...)\n\t}\n\treturn c.client.ListSubnetworks(project, region, opts...)\n}", "func TestGetNetworks(t *testing.T) {\n\trecord(t, \"getnetworks\", func(t *testing.T, svc *Service) {\n\t\t_, err := createServer(svc, \"TestGetNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworks, err := svc.GetNetworks()\n\t\trequire.NoError(t, err)\n\n\t\tassert.NotEmpty(t, networks.Networks)\n\n\t\tassert.NotEmpty(t, networks.Networks[0].IPNetworks)\n\t\tassert.NotEmpty(t, networks.Networks[0].Name)\n\t\tassert.NotEmpty(t, networks.Networks[0].Type)\n\t\tassert.NotEmpty(t, networks.Networks[0].UUID)\n\t\tassert.NotEmpty(t, networks.Networks[0].Zone)\n\n\t\t// Find a network with a server\n\t\tvar found bool\n\t\tfor _, n := range networks.Networks {\n\t\t\tif len(n.Servers) > 0 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(t, found)\n\t})\n}", "func (c *Client) PrivateNetworks() (string, error) {\n\treturn c.get(\"/private-networks\")\n}", "func (l *Libvirt) ConnectListNetworks(Maxnames int32) (rNames []string, err error) {\n\tvar buf []byte\n\n\targs := ConnectListNetworksArgs {\n\t\tMaxnames: Maxnames,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(38, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Names: []string\n\t_, err = dec.Decode(&rNames)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func TestGetServerNetworks(t *testing.T) {\n\trecord(t, \"getservernetworks\", func(t *testing.T, svc *Service) {\n\t\tserverDetails, err := createServer(svc, \"TestGetServerNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworking, err := svc.GetServerNetworks(&request.GetServerNetworksRequest{\n\t\t\tServerUUID: serverDetails.UUID,\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tsdNetworking := upcloud.Networking(serverDetails.Networking)\n\t\tassert.Equal(t, &sdNetworking, networking)\n\t})\n}", "func (c Container) connectNetworks(conf dkrtypes.ContainerJSON) error {\n\tfor _, endPtConfig := range conf.NetworkSettings.Networks {\n\t\t_, err := c.dkrClient.NetworkInspect(context.TODO(), endPtConfig.NetworkID, dkrtypes.NetworkInspectOptions{})\n\t\tif err != nil {\n\t\t\tif dkrclient.IsErrNotFound(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Bridge networks cannot be inspected\n\t\t\t// todo should be fixed in swarm api?\n\t\t\treturn bosherr.Errorf(\"Did not find network '%s'\", endPtConfig.NetworkID)\n\t\t}\n\n\t\terr = c.dkrClient.NetworkConnect(\n\t\t\tcontext.TODO(), endPtConfig.NetworkID, c.id.AsString(), endPtConfig)\n\t\tif err != nil {\n\t\t\treturn bosherr.WrapError(err, \"Connecting container to network\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func NetworkGet(w http.ResponseWriter, r *http.Request) {\n\tresp, err := goreq.Request{\n\t\tMethod: \"GET\",\n\t\tUri: remoteURL + \"/networks/current\",\n\t}.Do()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(resp.StatusCode)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tw.Write(body)\n}", "func ExtractNetworks(r pagination.Page) ([]Network, error) {\n\tvar s struct {\n\t\tNetworks []Network `json:\"networks\"`\n\t}\n\terr := (r.(NetworkPage)).ExtractInto(&s)\n\treturn s.Networks, err\n}", "func GetAllNetworks(l DigestStore) ([]string, error) {\n\tdigestInfos, err := l.GetDigests([]string{}, clock.Now().Unix())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnetworks := digestInfos.Networks()\n\tnetworksUniq := funk.UniqString(networks)\n\treturn networksUniq, nil\n}", "func (s *BoltState) GetNetworks(ctr *Container) (map[string]types.PerNetworkOptions, error) {\n\tif !s.valid {\n\t\treturn nil, define.ErrDBClosed\n\t}\n\n\tif !ctr.valid {\n\t\treturn nil, define.ErrCtrRemoved\n\t}\n\n\t// if the network mode is not bridge return no networks\n\tif !ctr.config.NetMode.IsBridge() {\n\t\treturn nil, nil\n\t}\n\n\tctrID := []byte(ctr.ID())\n\n\tdb, err := s.getDBCon()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer s.deferredCloseDBCon(db)\n\n\tnetworks := make(map[string]types.PerNetworkOptions)\n\n\tvar convertDB bool\n\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tctrBucket, err := getCtrBucket(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdbCtr := ctrBucket.Bucket(ctrID)\n\t\tif dbCtr == nil {\n\t\t\tctr.valid = false\n\t\t\treturn fmt.Errorf(\"container %s does not exist in database: %w\", ctr.ID(), define.ErrNoSuchCtr)\n\t\t}\n\n\t\tctrNetworkBkt := dbCtr.Bucket(networksBkt)\n\t\tif ctrNetworkBkt == nil {\n\t\t\t// convert if needed\n\t\t\tconvertDB = true\n\t\t\treturn nil\n\t\t}\n\n\t\treturn ctrNetworkBkt.ForEach(func(network, v []byte) error {\n\t\t\topts := types.PerNetworkOptions{}\n\t\t\tif err := json.Unmarshal(v, &opts); err != nil {\n\t\t\t\t// special case for backwards compat\n\t\t\t\t// earlier version used the container id as value so we set a\n\t\t\t\t// special error to indicate the we have to migrate the db\n\t\t\t\tif !bytes.Equal(v, ctrID) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tconvertDB = true\n\t\t\t}\n\t\t\tnetworks[string(network)] = opts\n\t\t\treturn nil\n\t\t})\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif convertDB {\n\t\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t\tctrBucket, err := getCtrBucket(tx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdbCtr := ctrBucket.Bucket(ctrID)\n\t\t\tif dbCtr == nil {\n\t\t\t\tctr.valid = false\n\t\t\t\treturn fmt.Errorf(\"container %s does not exist in database: %w\", ctr.ID(), define.ErrNoSuchCtr)\n\t\t\t}\n\n\t\t\tvar networkList []string\n\n\t\t\tctrNetworkBkt := dbCtr.Bucket(networksBkt)\n\t\t\tif ctrNetworkBkt == nil {\n\t\t\t\tctrNetworkBkt, err = dbCtr.CreateBucket(networksBkt)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"creating networks bucket for container %s: %w\", ctr.ID(), err)\n\t\t\t\t}\n\t\t\t\t// the container has no networks in the db lookup config and write to the db\n\t\t\t\tnetworkList = ctr.config.NetworksDeprecated\n\t\t\t\t// if there are no networks we have to add the default\n\t\t\t\tif len(networkList) == 0 {\n\t\t\t\t\tnetworkList = []string{ctr.runtime.config.Network.DefaultNetwork}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = ctrNetworkBkt.ForEach(func(network, v []byte) error {\n\t\t\t\t\tnetworkList = append(networkList, string(network))\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// the container has no networks in the db lookup config and write to the db\n\t\t\tfor i, network := range networkList {\n\t\t\t\tvar intName string\n\t\t\t\tif ctr.state.NetInterfaceDescriptions != nil {\n\t\t\t\t\teth, exists := ctr.state.NetInterfaceDescriptions.getInterfaceByName(network)\n\t\t\t\t\tif !exists {\n\t\t\t\t\t\treturn fmt.Errorf(\"no network interface name for container %s on network %s\", ctr.config.ID, network)\n\t\t\t\t\t}\n\t\t\t\t\tintName = eth\n\t\t\t\t} else {\n\t\t\t\t\tintName = fmt.Sprintf(\"eth%d\", i)\n\t\t\t\t}\n\t\t\t\tgetAliases := func(network string) []string {\n\t\t\t\t\tvar aliases []string\n\t\t\t\t\tctrAliasesBkt := dbCtr.Bucket(aliasesBkt)\n\t\t\t\t\tif ctrAliasesBkt == nil {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\tnetAliasesBkt := ctrAliasesBkt.Bucket([]byte(network))\n\t\t\t\t\tif netAliasesBkt == nil {\n\t\t\t\t\t\t// No aliases for this specific network.\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\t// let's ignore the error here there is nothing we can do\n\t\t\t\t\t_ = netAliasesBkt.ForEach(func(alias, v []byte) error {\n\t\t\t\t\t\taliases = append(aliases, string(alias))\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t})\n\t\t\t\t\t// also add the short container id as alias\n\t\t\t\t\treturn aliases\n\t\t\t\t}\n\n\t\t\t\tnetOpts := &types.PerNetworkOptions{\n\t\t\t\t\tInterfaceName: intName,\n\t\t\t\t\t// we have to add the short id as alias for docker compat\n\t\t\t\t\tAliases: append(getAliases(network), ctr.config.ID[:12]),\n\t\t\t\t}\n\t\t\t\t// only set the static ip/mac on the first network\n\t\t\t\tif i == 0 {\n\t\t\t\t\tif ctr.config.StaticIP != nil {\n\t\t\t\t\t\tnetOpts.StaticIPs = []net.IP{ctr.config.StaticIP}\n\t\t\t\t\t}\n\t\t\t\t\tnetOpts.StaticMAC = ctr.config.StaticMAC\n\t\t\t\t}\n\n\t\t\t\toptsBytes, err := json.Marshal(netOpts)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// insert into network map because we need to return this\n\t\t\t\tnetworks[network] = *netOpts\n\n\t\t\t\terr = ctrNetworkBkt.Put([]byte(network), optsBytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn networks, nil\n}", "func (r *ProjectsLocationsNetworksService) List(parent string) *ProjectsLocationsNetworksListCall {\n\tc := &ProjectsLocationsNetworksListCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\treturn c\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroupsExecute(r ApiBrowseCloudSecurityGroupsRequest) (CloudSecurityGroupsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSecurityGroupsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSecurityGroups\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSecurityGroups\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (o *GetClientConfig200ResponseDenylist) GetNetworksOk() (*GetClientConfig200ResponseNetworks1, bool) {\n\tif o == nil || o.Networks == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Networks, true\n}", "func (c *Client) CloudInfoNetworkPrivate(projectID string) ([]types.CloudNetwork, error) {\n\tnetwork := []types.CloudNetwork{}\n\terr := c.Get(queryEscape(\"/cloud/project/%s/network/private\", projectID), &network)\n\treturn network, err\n}", "func (o *GetClientConfig200ResponseDenylist) GetNetworks() GetClientConfig200ResponseNetworks1 {\n\tif o == nil || o.Networks == nil {\n\t\tvar ret GetClientConfig200ResponseNetworks1\n\t\treturn ret\n\t}\n\treturn *o.Networks\n}", "func (client *CraneDockerClient) filterStackNetwork(namespace string) ([]docker.Network, error) {\n\tfilter := docker.NetworkFilterOpts{\"label\": map[string]bool{LabelNamespace: true}}\n\tnetworks, err := client.ListNetworks(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stackNetwork []docker.Network\n\tfor _, network := range networks {\n\t\tif network.Labels == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name, ok := network.Labels[LabelNamespace]; !ok || name != namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tstackNetwork = append(stackNetwork, network)\n\t}\n\n\treturn stackNetwork, nil\n}", "func (client Client) VirtualNetworks() network.VirtualNetworksClient {\n\tif client.networks == nil {\n\t\tclnt := network.NewVirtualNetworksClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.networks = &clnt\t\t\n\t}\t\n\treturn *client.networks\n}", "func (a *Client) ListOpenstackNetworks(params *ListOpenstackNetworksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackNetworksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackNetworksParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackNetworks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/providers/openstack/networks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackNetworksReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackNetworksOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackNetworksDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func main() {\n opts := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: \"http://10.169.41.188/identity\",\n\t\tUsername: \"admin\",\n\t\tPassword: \"password\",\n\t\tTenantID: \"01821bd38f2f474489491adb0da7efaf\",\n\t\tDomainID: \"default\",\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tfmt.Println(err)\n\tif err != nil {\n\t\tfmt.Errorf(\"Sending get container group request failed: %v\", err)\n\t\treturn\n\t}\n client, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{\n\t\tRegion: \"RegionOne\",\n\t})\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to create a network client: %v\", err)\n\t}\n\tallPages, err := subnets.List(client, nil).AllPages()\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to list subnets: %v\", err)\n\t}\n\n\tallSubnets, err := subnets.ExtractSubnets(allPages)\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to extract subnets: %v\", err)\n\t}\n\n\tfor _, subnet := range allSubnets {\n\t b, _ := json.MarshalIndent(subnet, \"\", \" \")\n fmt.Printf(\"%s\", string(b))\n }\n\n}", "func (d *Dry) ShowNetworks() {\n\tif networks, err := d.dockerDaemon.Networks(); err == nil {\n\t\td.changeViewMode(Networks)\n\t\td.networks = networks\n\t} else {\n\t\td.appmessage(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Could not retrieve network list: %s \", err.Error()))\n\t}\n}", "func (c *Client) CloudInfoNetworkPublic(projectID string) ([]types.CloudNetwork, error) {\n\tnetwork := []types.CloudNetwork{}\n\terr := c.Get(queryEscape(\"/cloud/project/%s/network/public\", projectID), &network)\n\treturn network, err\n}", "func (a *Client) GetPlatformNetworks(params *GetPlatformNetworksParams) (*GetPlatformNetworksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetPlatformNetworksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getPlatformNetworks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/networks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetPlatformNetworksReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetPlatformNetworksOK), nil\n\n}", "func (n *NetworkServiceHandler) List(ctx context.Context) ([]Network, error) {\n\turi := \"/v1/network/list\"\n\n\treq, err := n.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar networkMap map[string]Network\n\terr = n.client.DoWithContext(ctx, req, &networkMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar networks []Network\n\tfor _, network := range networkMap {\n\t\tnetworks = append(networks, network)\n\t}\n\n\treturn networks, nil\n}", "func (l *Libvirt) ConnectListDefinedNetworks(Maxnames int32) (rNames []string, err error) {\n\tvar buf []byte\n\n\targs := ConnectListDefinedNetworksArgs {\n\t\tMaxnames: Maxnames,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(36, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Names: []string\n\t_, err = dec.Decode(&rNames)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *client) GetVipNetworks() ([]*models.AviVipNetwork, error) {\n\tif c.Network == nil {\n\t\treturn nil, errors.Errorf(\"unable to make API calls before authentication\")\n\t}\n\n\tvar page = 1\n\tnetworks := make([]*models.AviVipNetwork, 0)\n\tfor {\n\t\tall, err := c.Network.GetAll(session.SetParams(map[string]string{\"fields\": \"name,uuid,cloud_ref,configured_subnets\", \"page\": strconv.Itoa(page), \"page_size\": pageSizeMax}))\n\t\tif err != nil {\n\t\t\tif page == 1 {\n\t\t\t\treturn nil, errors.Wrap(err, \"unable to get all Networks from avi controller due to error\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, seg := range all {\n\t\t\tsubnets := make([]*models.AviSubnet, 0)\n\t\t\tfor _, temp := range seg.ConfiguredSubnets {\n\t\t\t\tsubnets = append(subnets, &models.AviSubnet{\n\t\t\t\t\tSubnet: *temp.Prefix.IPAddr.Addr + \"/\" + strconv.Itoa(int(*temp.Prefix.Mask)),\n\t\t\t\t\tFamily: *temp.Prefix.IPAddr.Type,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tnetwork := &models.AviVipNetwork{\n\t\t\t\tUUID: *seg.UUID,\n\t\t\t\tName: *seg.Name,\n\t\t\t\tCloud: c.getCloudID(*seg.CloudRef),\n\t\t\t\tConfigedSubnets: subnets,\n\t\t\t}\n\n\t\t\tnetworks = append(networks, network)\n\t\t}\n\n\t\tpage++\n\t}\n\treturn networks, nil\n}", "func (in *Database) GetNetworks() ([]*types.Network, error) {\n\trec := []*types.Network{}\n\ttxn := in.db.Txn(false)\n\tdefer txn.Abort()\n\tit, err := txn.Get(\"network\", \"id\")\n\tif err != nil {\n\t\treturn rec, err\n\t}\n\tfor obj := it.Next(); obj != nil; obj = it.Next() {\n\t\trec = append(rec, obj.(*types.Network))\n\t}\n\treturn rec, nil\n}", "func (vcd *TestVCD) Test_GetNetworkList(check *C) {\n\tfmt.Printf(\"Running: %s\\n\", check.TestName())\n\tnetworkName := vcd.config.VCD.Network.Net1\n\tif networkName == \"\" {\n\t\tcheck.Skip(\"no network name provided\")\n\t}\n\tnetworks, err := vcd.vdc.GetNetworkList()\n\tcheck.Assert(err, IsNil)\n\tfound := false\n\tfor _, net := range networks {\n\t\t// Check that we don't get invalid fields\n\t\tknownType := net.LinkType == 0 || net.LinkType == 1 || net.LinkType == 2\n\t\tcheck.Assert(knownType, Equals, true)\n\t\t// Check that the `ConnectTo` field is not empty\n\t\tcheck.Assert(net.ConnectedTo, Not(Equals), \"\")\n\t\tif net.Name == networkName {\n\t\t\tfound = true\n\t\t}\n\t}\n\tcheck.Assert(found, Equals, true)\n}", "func (esr *etcdSubnetRegistry) getNetworks(ctx context.Context) ([]string, uint64, error) {\n\tresp, err := esr.client().Get(ctx, esr.etcdCfg.Prefix, &etcd.GetOptions{Recursive: true})\n\n\tnetworks := []string{}\n\n\tif err == nil {\n\t\tfor _, node := range resp.Node.Nodes {\n\t\t\t// Look for '/config' on the child nodes\n\t\t\tfor _, child := range node.Nodes {\n\t\t\t\tnetname, isConfig := esr.parseNetworkKey(child.Key)\n\t\t\t\tif isConfig {\n\t\t\t\t\tnetworks = append(networks, netname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn networks, resp.Index, nil\n\t}\n\n\tif etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeKeyNotFound {\n\t\t// key not found: treat it as empty set\n\t\treturn networks, etcdErr.Index, nil\n\t}\n\n\treturn nil, 0, err\n}", "func getNetworkNames(\n\tinfraStatus *apisgcp.InfrastructureStatus,\n\tcp *extensionsv1alpha1.ControlPlane,\n) (string, string) {\n\tnetworkName := infraStatus.Networks.VPC.Name\n\tif networkName == \"\" {\n\t\tnetworkName = cp.Namespace\n\t}\n\n\tsubNetworkName := \"\"\n\tsubnet, _ := apihelper.FindSubnetForPurpose(infraStatus.Networks.Subnets, apisgcp.PurposeInternal)\n\tif subnet != nil {\n\t\tsubNetworkName = subnet.Name\n\t}\n\n\treturn networkName, subNetworkName\n}", "func (d *driver) getNetworks() []*bridgeNetwork {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tls := make([]*bridgeNetwork, 0, len(d.networks))\n\tfor _, nw := range d.networks {\n\t\tls = append(ls, nw)\n\t}\n\treturn ls\n}", "func (d *driver) getNetworks() []*network {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tls := make([]*network, 0, len(d.networks))\n\tfor _, nw := range d.networks {\n\t\tls = append(ls, nw)\n\t}\n\n\treturn ls\n}", "func (vns *VirtualNetworkService) List(ctx context.Context, pageOffset int, pageSize int,\n\tfilter OwnershipFilter) ([]*resources.VirtualNetwork, error) {\n\treturn vns.list(ctx, int(filter), (pageOffset-1)*pageSize, -pageSize)\n}", "func (f *FakeInstance) ListPrivateNetworks(_ context.Context, _ string, _ *govultr.ListOptions) ([]govultr.PrivateNetwork, *govultr.Meta, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func (a *Client) ListOpenstackNetworksNoCredentials(params *ListOpenstackNetworksNoCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackNetworksNoCredentialsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackNetworksNoCredentialsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackNetworksNoCredentials\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/projects/{project_id}/dc/{dc}/clusters/{cluster_id}/providers/openstack/networks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackNetworksNoCredentialsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackNetworksNoCredentialsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackNetworksNoCredentialsDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (client StorageGatewayClient) listCloudSyncs(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/storageGateways/{storageGatewayId}/cloudSyncs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListCloudSyncsResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NetworkResourceGet(w http.ResponseWriter, r *http.Request) {\n\tnrID := mux.Vars(r)[\"nr_id\"]\n\tcp := r.URL.Query().Get(\"cloud_provider\")\n\tif nrID == \"\" || cp == \"\" {\n\t\thandleError(w, http.StatusBadRequest,\n\t\t\t\"url params 'nr_id' or 'cloud_provider' is missing\")\n\t\treturn\n\t}\n\n\tnetwork, err := ctr.GetStorageResource(nrID)\n\tif err != nil {\n\t\thandleError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\n\thandleResult(w, http.StatusOK, network)\n\treturn\n}", "func TestGetNetworksInZone(t *testing.T) {\n\trecord(t, \"getnetworksinzone\", func(t *testing.T, svc *Service) {\n\t\t_, err := createServer(svc, \"TestGetNetworksInZone\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworks, err := svc.GetNetworksInZone(&request.GetNetworksInZoneRequest{\n\t\t\tZone: \"fi-hel2\",\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tassert.NotEmpty(t, networks)\n\n\t\tassert.NotEmpty(t, networks.Networks[0].IPNetworks)\n\t\tassert.NotEmpty(t, networks.Networks[0].Name)\n\t\tassert.NotEmpty(t, networks.Networks[0].Type)\n\t\tassert.NotEmpty(t, networks.Networks[0].UUID)\n\n\t\t// Find a network with a server\n\t\tvar found bool\n\t\tvar foundNetwork *upcloud.Network\n\t\tfor _, n := range networks.Networks {\n\t\t\tif len(n.Servers) > 0 {\n\t\t\t\tfoundNetwork = &n\n\t\t\t\tfound = true\n\t\t\t}\n\t\t\t// Make sure all the networks are in the right zone.\n\t\t\tassert.Equal(t, \"fi-hel2\", n.Zone)\n\t\t}\n\t\tassert.True(t, found)\n\t\trequire.NotNil(t, foundNetwork)\n\n\t\tnetwork, err := svc.GetNetworkDetails(&request.GetNetworkDetailsRequest{\n\t\t\tUUID: foundNetwork.UUID,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, foundNetwork, network)\n\t})\n}", "func (a *AmazonConnectionsApiService) BrowseAvailabilityZones(ctx _context.Context, amazonConnectionId string) ApiBrowseAvailabilityZonesRequest {\n\treturn ApiBrowseAvailabilityZonesRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (c *DockerCommand) RefreshNetworks() ([]*Network, error) {\n\tnetworks, err := c.Client.NetworkList(context.Background(), dockerTypes.NetworkListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\townNetworks := make([]*Network, len(networks))\n\n\tfor i, network := range networks {\n\t\townNetworks[i] = &Network{\n\t\t\tName: network.Name,\n\t\t\tNetwork: network,\n\t\t\tClient: c.Client,\n\t\t\tOSCommand: c.OSCommand,\n\t\t\tLog: c.Log,\n\t\t\tDockerCommand: c,\n\t\t}\n\t}\n\n\treturn ownNetworks, nil\n}", "func (a *BillingNetworkApiService) BillingnetworksGet(ctx _context.Context, localVarOptionals *BillingnetworksGetOpts) ([]BillingNetwork, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []BillingNetwork\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/billingnetworks/\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.ResellerId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"reseller_id\", parameterToString(localVarOptionals.ResellerId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Ip.IsSet() {\n\t\tlocalVarQueryParams.Add(\"ip\", parameterToString(localVarOptionals.Ip.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Name.IsSet() {\n\t\tlocalVarQueryParams.Add(\"name\", parameterToString(localVarOptionals.Name.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.OrderBy.IsSet() {\n\t\tlocalVarQueryParams.Add(\"order_by\", parameterToString(localVarOptionals.OrderBy.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.OrderByDirection.IsSet() {\n\t\tlocalVarQueryParams.Add(\"order_by_direction\", parameterToString(localVarOptionals.OrderByDirection.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Page.IsSet() {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Rows.IsSet() {\n\t\tlocalVarQueryParams.Add(\"rows\", parameterToString(localVarOptionals.Rows.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c *ContainerContext) Networks() string {\n\treturn strings.Join(c.c.Networks, \",\")\n}", "func (instance *Host) Browse(ctx context.Context, callback func(*abstract.HostCore) fail.Error) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif instance == nil {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(ctx, func(buf []byte) (innerXErr fail.Error) {\n\t\tahc := abstract.NewHostCore()\n\t\tvar inErr fail.Error\n\t\tif inErr = ahc.Deserialize(buf); inErr != nil {\n\t\t\treturn inErr\n\t\t}\n\n\t\treturn callback(ahc)\n\t})\n}", "func SearchNetwork(term string, service service.Network, unique bool) ([]*upcloud.Network, error) {\n\tvar result []*upcloud.Network\n\n\tif len(cachedNetworks) == 0 {\n\t\tnetworks, err := service.GetNetworks()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcachedNetworks = networks.Networks\n\t}\n\n\tfor _, n := range cachedNetworks {\n\t\tnetwork := n\n\t\tif network.UUID == term || network.Name == term {\n\t\t\tresult = append(result, &network)\n\t\t}\n\t}\n\tif len(result) == 0 {\n\t\treturn nil, fmt.Errorf(\"no network was found with %s\", term)\n\t}\n\tif len(result) > 1 && unique {\n\t\treturn nil, fmt.Errorf(\"multiple networks matched to query %q, use UUID to specify\", term)\n\t}\n\n\treturn result, nil\n}", "func (c *AppsServices) Browse() ([]interface{}, error) {\n\tu, err := url.Parse(c.client.BaseURL.String() + \"apps\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.client.UseAuthKey = true\n\tresp, err := GET(u.String(), c.client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar data []interface{}\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func (*ListNetworksRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{1}\n}", "func (a *Client) ListOpenstackNetworksNoCredentialsV2(params *ListOpenstackNetworksNoCredentialsV2Params, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackNetworksNoCredentialsV2OK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackNetworksNoCredentialsV2Params()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackNetworksNoCredentialsV2\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v2/projects/{project_id}/clusters/{cluster_id}/providers/openstack/networks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackNetworksNoCredentialsV2Reader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackNetworksNoCredentialsV2OK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackNetworksNoCredentialsV2Default)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (ctx *DevModelParallels) Networks() []*config.NetworkConfig {\n\treturn ctx.networks\n}", "func (*ListNetworksRequest) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{1}\n}", "func (c *ProjectsLocationsNetworksListCall) PageSize(pageSize int64) *ProjectsLocationsNetworksListCall {\n\tc.urlParams_.Set(\"pageSize\", fmt.Sprint(pageSize))\n\treturn c\n}", "func (o *PcloudNetworksGetallParams) WithTimeout(timeout time.Duration) *PcloudNetworksGetallParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (s *StackEbrc) ListVolumes() ([]abstract.Volume, fail.Error) {\n\tlogrus.Debug(\"ebrc.Client.ListVolumes() called\")\n\tdefer logrus.Debug(\"ebrc.Client.ListVolumes() done\")\n\n\tvar volumes []abstract.Volume\n\n\torg, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn volumes, fail.Wrap(err, fmt.Sprintf(\"Error listing volumes\"))\n\t}\n\n\t// Check if network is already there\n\trefs, err := getLinks(org, \"vnd.vmware.vcloud.disk+xml\")\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error recovering network information\"))\n\t}\n\tfor _, ref := range refs {\n\t\t// FIXME: Add data\n\t\tdr, err := vdc.QueryDisk(ref.Name)\n\t\tif err == nil {\n\t\t\tthed, err := vdc.FindDiskByHREF(dr.Disk.HREF)\n\t\t\tif err == nil {\n\t\t\t\tvolumes = append(volumes, abstract.Volume{Name: ref.Name, ID: ref.ID, Size: thed.Disk.Size})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn volumes, nil\n}", "func (*ListNetworksResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{2}\n}", "func (m *TenantMutation) Networks() (r []string, exists bool) {\n\tv := m.networks\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o *PcloudPvminstancesNetworksGetParams) WithTimeout(timeout time.Duration) *PcloudPvminstancesNetworksGetParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func GetMultiNetworks(nad []string, ns string, podName string) *corev1.Pod {\n\tpod := GetPodDefinition(ns, podName)\n\tpod.Annotations = map[string]string{\"k8s.v1.cni.cncf.io/networks\": strings.Join(nad, \",\")}\n\treturn pod\n}", "func (c *Cluster) getVnets(nodeo Node, m map[string]string, region, st string) (map[string]string, string, error) {\n\tres := make(map[string]string)\n\tnets, err := c.GetVNetPool(region)\n\tif err != nil {\n\t\treturn res, \"\", err\n\t}\n\n\tfor k, v := range nodeo.Clusters {\n\t\tif v[constants.STORAGE_TYPE][0] == st && !c.isVOne(v[constants.VONE_CLOUD]) {\n\t\t\tfor i, j := range nodeo.Clusters[k] {\n\t\t\t\tif m[i] == constants.TRUE {\n\t\t\t\t\tavail, err := c.availableNet(nets, j, i)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn res, \"\", err\n\t\t\t\t\t}\n\t\t\t\t\tres[i] = avail\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn res, k, nil\n\t\t}\n\t}\n\treturn res, \"\", fmt.Errorf(\"Storage (%s) unavailable in selected region (%s)\", st, region)\n}", "func (n *NetworkListCommand) runNetworkList(args []string) error {\n\tlogrus.Debugf(\"list the networks\")\n\n\tctx := context.Background()\n\tapiClient := n.cli.Client()\n\trespNetworkResource, err := apiClient.NetworkList(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisplay := n.cli.NewTableDisplay()\n\tdisplay.AddRow([]string{\"NETWORK ID\", \"NAME\", \"DRIVER\", \"SCOPE\"})\n\tfor _, network := range respNetworkResource {\n\t\tdisplay.AddRow([]string{\n\t\t\tnetwork.ID[:10],\n\t\t\tnetwork.Name,\n\t\t\tnetwork.Driver,\n\t\t\tnetwork.Scope,\n\t\t})\n\t}\n\n\tdisplay.Flush()\n\treturn nil\n}", "func (*ListNetworksResponse) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{2}\n}", "func (l *Libvirt) ConnectListStoragePools(Maxnames int32) (rNames []string, err error) {\n\tvar buf []byte\n\n\targs := ConnectListStoragePoolsArgs {\n\t\tMaxnames: Maxnames,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(72, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Names: []string\n\t_, err = dec.Decode(&rNames)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *Client) Browse(code, filepath string) ([]string, error) {\n\t// TODO: Decide, based on the code, which provider to choose\n\treturn c.googledrive.Browse(code, filepath)\n}", "func ValidateNetworks(Validations Validations, Service types.ServiceConfig) error {\n\tfor Network := range Service.Networks {\n\t\tif !goutil.StringInSlice(Network, Validations.Networks) {\n\t\t\treturn fmt.Errorf(\"Network '%s' not in the whitelist\", Network)\n\t\t}\n\t}\n\treturn nil\n}", "func Explore(client *storage.Client, thinClient *ThinClient, bucket string, prefix string) ([]*Node, error) {\n // Combine bucket lifecycle to each node\n ctx := context.Background()\n lifecycle, err := thinClient.Lifecycle(ctx, bucket)\n if err != nil {\n return nil, err\n }\n\n objs, err := listq(client, bucket, prefix, \"/\", false, true)\n if err != nil {\n return nil, err\n }\n var nodes []*Node\n for _, element := range objs {\n var node Node\n node.Bucket = bucket\n node.Lifecycle = lifecycle\n if element.Name == \"\" && element.Prefix != \"\" {\n node.Ntype = \"DIR\"\n node.Name = element.Prefix\n node.FQPN = element.Prefix\n } else {\n node.Ntype = \"OBJ\"\n pathSlice := strings.Split(element.Name, \"/\")\n pathLength := len(pathSlice)\n node.Name = pathSlice[pathLength - 1]\n node.FQPN = element.Name\n }\n node.ACL = element.ACL\n node.Owner = element.Owner\n node.Size = element.Size\n\n nodes = append(nodes, &node)\n }\n return nodes, nil\n}", "func (client IdentityClient) listNetworkSources(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/networkSources\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListNetworkSourcesResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func List(ctx context.Context, svc iaas.Service, networkID string, all bool, terraform bool) ([]*abstract.Subnet, fail.Error) {\n\tif !terraform {\n\t\treturn operations.ListSubnets(ctx, svc, networkID, all)\n\t}\n\n\tvar neptune []*abstract.Subnet\n\traw, err := operations.ListTerraformSubnets(ctx, svc, networkID, \"\", terraform)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, val := range raw { // FIXME: Another mapping problem\n\t\tns := abstract.NewSubnet()\n\t\tns.ID = val.Identity\n\t\tns.Name = val.Name\n\t\tneptune = append(neptune, ns)\n\t}\n\n\treturn neptune, nil\n}", "func ScanNetworks(subnetsToScan []string, site []string) {\n\tconcurrency := viper.GetInt(\"scanner.concurrency\")\n\n\tcc := make(chan *ToScan, concurrency)\n\twg := sync.WaitGroup{}\n\tdb := storage.InitDB()\n\n\twg.Add(concurrency)\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func(input <-chan *ToScan, db *gorm.DB, wg *sync.WaitGroup) {\n\t\t\tdefer wg.Done()\n\t\t\tscan(input, db)\n\t\t}(cc, db, &wg)\n\t}\n\n\tsubnets := LoadSubnets(viper.GetString(\"scanner.subnet_source\"), subnetsToScan, site)\n\n\tfor idx := range subnets {\n\t\tcc <- subnets[idx]\n\t}\n\n\tclose(cc)\n\twg.Wait()\n}", "func (a *AllApiService) NetworkGetNetworkConfigurations(ctx _context.Context, body NetworkGetNetworkConfigurations) ([]NetworkGetNetworkConfigurationsResultItem, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []NetworkGetNetworkConfigurationsResultItem\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/network/getNetworkConfigurations\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v []NetworkGetNetworkConfigurationsResultItem\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (u *Unifi) Networks(site *Site) ([]Network, error) {\n\tvar response struct {\n\t\tData []Network\n\t\tMeta meta\n\t}\n\terr := u.parse(site, \"rest/networkconf\", nil, &response)\n\treturn response.Data, err\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := listURL(client)\n\tif opts != nil {\n\t\tquery, err := opts.ToRegionListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn RegionPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func (h *httpCloud) List(filter string) ([]string, error) {\n\tvar resp []string\n\tif err := h.get(h.instancesURL+path.Join(InstancesPath, filter), &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (s *logicalNetworkLister) List(selector labels.Selector) (ret []*v1.LogicalNetwork, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LogicalNetwork))\n\t})\n\treturn ret, err\n}", "func (sdk *SDK) ListNodes() ([]*cloudsvr.CloudNode, error) {\n\t// query all regions\n\tregions, err := sdk.ListRegions()\n\tif err != nil {\n\t\tlog.Errorf(\"sdk.ListNodes.ListRegions() error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tret []*cloudsvr.CloudNode\n\t\tmux sync.Mutex\n\t\twg sync.WaitGroup\n\t)\n\n\t// query each region's ecs instances\n\twg.Add(len(regions))\n\tfor _, reg := range regions {\n\t\tgo func(reg RegionType) {\n\t\t\tdefer wg.Done()\n\t\t\tecses, err := sdk.ListEcses(reg.RegionID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"sdk.ListNodes.ListEcses() on %s error: %v\", reg.RegionID, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, ecsAttr := range ecses {\n\t\t\t\ttags := ecsAttr.Tags.Tag\n\t\t\t\tif len(tags) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar ipaddr string\n\t\t\t\tif ipaddrs := ecsAttr.PublicIPAddress.IPAddress; len(ipaddrs) > 0 {\n\t\t\t\t\tipaddr = ipaddrs[0]\n\t\t\t\t}\n\n\t\t\t\tkey, val := tags[0].TagKey, tags[0].TagValue\n\t\t\t\tif key == cloudsvr.CLOUDFLAGKEY && val == CloudType {\n\t\t\t\t\tmux.Lock()\n\t\t\t\t\tret = append(ret, &cloudsvr.CloudNode{\n\t\t\t\t\t\tID: ecsAttr.InstanceID,\n\t\t\t\t\t\tRegionOrZoneID: ecsAttr.RegionID,\n\t\t\t\t\t\tInstanceType: ecsAttr.InstanceType,\n\t\t\t\t\t\tCloudSvrType: sdk.Type(),\n\t\t\t\t\t\tIPAddr: ipaddr,\n\t\t\t\t\t\tCreatTime: ecsAttr.CreationTime,\n\t\t\t\t\t\tStatus: ecsAttr.Status,\n\t\t\t\t\t})\n\t\t\t\t\tmux.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(reg)\n\t}\n\twg.Wait()\n\n\treturn ret, nil\n}", "func (c *MockVirtualNetworksClient) List(ctx context.Context, resourceGroupName string) ([]network.VirtualNetwork, error) {\n\tvar l []network.VirtualNetwork\n\tfor _, vnet := range c.VNets {\n\t\tl = append(l, vnet)\n\t}\n\treturn l, nil\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetNetworksOk() ([]VirtualizationBaseNetworkRelationship, bool) {\n\tif o == nil || o.Networks == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Networks, true\n}", "func (digestInfos DigestInfos) Networks() []string {\n\tret := []string{}\n\tfor _, digestInfo := range digestInfos {\n\t\tret = append(ret, digestInfo.Network)\n\t}\n\treturn ret\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetNetworks() []VirtualizationBaseNetworkRelationship {\n\tif o == nil {\n\t\tvar ret []VirtualizationBaseNetworkRelationship\n\t\treturn ret\n\t}\n\treturn o.Networks\n}", "func networkInspectExample() string {\n\treturn `$ pouch network inspect net1\nName: net1\nScope: \nDriver: bridge\nEnableIPV6: false\nID: c33c2646dc8ce9162faa65d17e80582475bbe53dc70ba0dc4def4b71e44551d6\nInternal: false`\n}", "func (i *Item) Browse(callback func([]byte) error) error {\n\treturn i.BrowseInto(\".\", callback)\n}", "func (client WorkloadNetworksClient) ListGateways(ctx context.Context, resourceGroupName string, privateCloudName string) (result WorkloadNetworkGatewayListPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/WorkloadNetworksClient.ListGateways\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.wngl.Response.Response != nil {\n\t\t\t\tsc = result.wngl.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: client.SubscriptionID,\n\t\t\tConstraints: []validation.Constraint{{Target: \"client.SubscriptionID\", Name: validation.MinLength, Rule: 1, Chain: nil}}},\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"avs.WorkloadNetworksClient\", \"ListGateways\", err.Error())\n\t}\n\n\tresult.fn = client.listGatewaysNextResults\n\treq, err := client.ListGatewaysPreparer(ctx, resourceGroupName, privateCloudName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"avs.WorkloadNetworksClient\", \"ListGateways\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListGatewaysSender(req)\n\tif err != nil {\n\t\tresult.wngl.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"avs.WorkloadNetworksClient\", \"ListGateways\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.wngl, err = client.ListGatewaysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"avs.WorkloadNetworksClient\", \"ListGateways\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.wngl.hasNextLink() && result.wngl.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func NetworkPost(w http.ResponseWriter, r *http.Request) {\n\tvar newNet swl.NetworkCreate\n\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif !swl.ValidateAndUnmarshalJSON(body, &newNet, w) {\n\t\treturn\n\t}\n\n\tresp, err := goreq.Request{\n\t\tMethod: \"POST\",\n\t\tUri: remoteURL + \"/networks\",\n\t\tBody: body,\n\t}.Do()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(resp.StatusCode)\n\tresbody, _ := ioutil.ReadAll(resp.Body)\n\tw.Write(resbody)\n}", "func (o *GetClientConfig200ResponseDenylist) HasNetworks() bool {\n\tif o != nil && o.Networks != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r Virtual_Guest) GetNetworkStorage() (resp []datatypes.Network_Storage, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getNetworkStorage\", nil, &r.Options, &resp)\n\treturn\n}", "func (client StorageGatewayClient) listStorageGateways(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/storageGateways\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListStorageGatewaysResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func NetConnections(kind string) ([]NetConnectionStat, error) {\n\tvar ret []NetConnectionStat\n\n\treturn ret, NotImplementedError\n}", "func getNetwork(net string, zoneID *egoscale.UUID) (*egoscale.Network, error) {\n\tvar found *egoscale.Network\n\n\treq := &egoscale.Network{\n\t\tZoneID: zoneID,\n\t\tType: \"Isolated\",\n\t\tCanUseForDeploy: true,\n\t}\n\n\tid, errUUID := egoscale.ParseUUID(net)\n\tif errUUID != nil {\n\t\treq.Name = net\n\t} else {\n\t\treq.ID = id\n\t}\n\n\tresp, err := cs.ListWithContext(gContext, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, item := range resp {\n\t\tnetwork := item.(*egoscale.Network)\n\n\t\t// If search criterion is an unique ID, return the first (i.e. only) match\n\t\tif id != nil && network.ID.Equal(*id) {\n\t\t\treturn network, nil\n\t\t}\n\n\t\t// If search criterion is a name, check that there isn't multiple networks named\n\t\t// identically before returning a match\n\t\tif network.Name == net {\n\t\t\t// We already found a match before -> multiple results\n\t\t\tif found != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"found multiple networks named %q, please specify a unique ID instead\", net)\n\t\t\t}\n\t\t\tfound = network\n\t\t}\n\t}\n\n\tif found != nil {\n\t\treturn found, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"network %q not found\", net)\n}", "func listInfo() ([]*RegionInfo, error) {\n // ex-1)\n // /cloud-info-spaces/regions/aws_region01/AWS/region [ap-northeast-2]\n // ex-2)\n // /cloud-info-spaces/regions/gcp_region02/GCP/region [us-east1]\n // /cloud-info-spaces/regions/gcp_region02/GCP/zone [us-east1-c]\n\n\n key := \"/cloud-info-spaces/regions\"\n keyValueList, err := store.GetList(key, true)\n if err != nil {\n return nil, err\n }\n\n var regionInfoList []*RegionInfo\n\tvar inKeyValueList []icbs.KeyValue\n\tprevRegionName := \"\"\n\tprevProviderName := \"\"\n for _, kv := range keyValueList {\n\n\t\tregionName := utils.GetNodeValue(kv.Key, 3)\n\t\tproviderName := utils.GetNodeValue(kv.Key, 4)\n\n\t\tif prevRegionName==\"\" || regionName == prevRegionName {\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t} else {\n\t\t\t// insert prev RegionInfo\n\t\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tinKeyValueList = nil\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t}\n\n }\n\n\tif len(keyValueList) > 0 {\n\t\t// insert last RegionInfo\n\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\t}\n\n return regionInfoList, nil\n}", "func NewPcloudVpnconnectionsNetworksGetOK() *PcloudVpnconnectionsNetworksGetOK {\n\treturn &PcloudVpnconnectionsNetworksGetOK{}\n}", "func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager {\n\tq, err := gophercloud.BuildQueryString(&opts)\n\tif err != nil {\n\t\treturn pagination.Pager{Err: err}\n\t}\n\tu := rootURL(c) + q.String()\n\treturn pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {\n\t\treturn PoolPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func (m *Setup) DelNetworks(ctx context.Context) error {\n\treturn m.command(ctx, \"DEL\")\n}", "func (a *AmazonConnectionsApiService) BrowseEncryptionKeysExecute(r ApiBrowseEncryptionKeysRequest) (CloudEncryptionKeysPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudEncryptionKeysPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseEncryptionKeys\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudEncryptionKeys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (d *Driver) createNetworks() error {\n\tif err := d.createNetwork(\"default\", defaultNetworkTmpl); err != nil {\n\t\treturn errors.Wrap(err, \"creating default network\")\n\t}\n\tif err := d.createNetwork(d.NetworkName, privateNetworkTmpl); err != nil {\n\t\treturn errors.Wrap(err, \"creating private network\")\n\t}\n\n\treturn nil\n}" ]
[ "0.68448156", "0.6555897", "0.62431705", "0.6154171", "0.5575327", "0.549623", "0.54702884", "0.53919774", "0.53837615", "0.53559184", "0.52491796", "0.5146743", "0.51275605", "0.51164585", "0.50539297", "0.504731", "0.5046735", "0.4994143", "0.4978576", "0.4968765", "0.49622697", "0.4938829", "0.49346635", "0.49181938", "0.4865668", "0.48505077", "0.48484915", "0.4800186", "0.47832075", "0.47831827", "0.47797376", "0.47791296", "0.4778016", "0.4770097", "0.47642016", "0.4758574", "0.4751861", "0.4751634", "0.47345248", "0.47309834", "0.4716424", "0.47155198", "0.4711324", "0.46885324", "0.46639463", "0.4648788", "0.46422192", "0.46400014", "0.46370068", "0.46214247", "0.46062472", "0.46056682", "0.45972207", "0.45863444", "0.4570064", "0.45588374", "0.45472008", "0.45449612", "0.4537008", "0.451597", "0.4514309", "0.4496991", "0.44880685", "0.44828764", "0.44721854", "0.44706815", "0.44616255", "0.44540143", "0.4449559", "0.44400203", "0.4435527", "0.4433792", "0.44293556", "0.44127938", "0.44119385", "0.44107652", "0.44089925", "0.43926144", "0.43883404", "0.43803927", "0.43745434", "0.43647158", "0.436331", "0.43627894", "0.43542588", "0.43530762", "0.43509567", "0.4346963", "0.4341724", "0.43393534", "0.43391758", "0.43381706", "0.43216088", "0.4319104", "0.43148798", "0.43094853", "0.43085098", "0.4299231", "0.42978346", "0.42969337" ]
0.75171417
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseCloudNetworksExecute(r ApiBrowseCloudNetworksRequest) (CloudNetworksPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue CloudNetworksPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseCloudNetworks") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/cloudNetworks" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.offset != nil { localVarQueryParams.Add("Offset", parameterToString(*r.offset, "")) } if r.limit != nil { localVarQueryParams.Add("Limit", parameterToString(*r.limit, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
/ BrowseCloudSecurityGroups Method for BrowseCloudSecurityGroups
func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroups(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSecurityGroupsRequest { return ApiBrowseCloudSecurityGroupsRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroupsExecute(r ApiBrowseCloudSecurityGroupsRequest) (CloudSecurityGroupsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSecurityGroupsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSecurityGroups\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSecurityGroups\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func ExampleDeviceSecurityGroupsClient_NewListPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewDeviceSecurityGroupsClient().NewListPager(\"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\", nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.DeviceSecurityGroupList = armsecurity.DeviceSecurityGroupList{\n\t\t// \tValue: []*armsecurity.DeviceSecurityGroup{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"samplesecuritygroup\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.Security/deviceSecurityGroups\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub/providers/Microsoft.Security/deviceSecurityGroups/samplesecuritygroup\"),\n\t\t// \t\t\tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t\t// \t\t\t\tAllowlistRules: []armsecurity.AllowlistCustomAlertRuleClassification{\n\t\t// \t\t\t\t\t&armsecurity.ConnectionToIPNotAllowed{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when an outbound connection is created between your device and an ip that isn't allowed\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Outbound connection to an ip that isn't allowed\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"ConnectionToIpNotAllowed\"),\n\t\t// \t\t\t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeIPCidr),\n\t\t// \t\t\t\t\t\tAllowlistValues: []*string{\n\t\t// \t\t\t\t\t\t},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.LocalUserNotAllowed{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when a local user that isn't allowed logins to the device\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Login by a local user that isn't allowed\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"LocalUserNotAllowed\"),\n\t\t// \t\t\t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t\t// \t\t\t\t\t\tAllowlistValues: []*string{\n\t\t// \t\t\t\t\t\t},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.ProcessNotAllowed{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when a process that isn't allowed is executed\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Execution of a process that isn't allowed\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"ProcessNotAllowed\"),\n\t\t// \t\t\t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t\t// \t\t\t\t\t\tAllowlistValues: []*string{\n\t\t// \t\t\t\t\t\t},\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tDenylistRules: []*armsecurity.DenylistCustomAlertRule{\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tThresholdRules: []armsecurity.ThresholdCustomAlertRuleClassification{\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t\t// \t\t\t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of active connections of a device in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of active connections is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.AmqpC2DMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"AmqpC2DMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.MqttC2DMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"MqttC2DMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.HTTPC2DMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"HttpC2DMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.AmqpC2DRejectedMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"AmqpC2DRejectedMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.MqttC2DRejectedMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"MqttC2DRejectedMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.HTTPC2DRejectedMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"HttpC2DRejectedMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.AmqpD2CMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (AMQP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"AmqpD2CMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.MqttD2CMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (MQTT protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"MqttD2CMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.HTTPD2CMessagesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (HTTP protocol) is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"HttpD2CMessagesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.DirectMethodInvokesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of direct method invokes in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of direct method invokes is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"DirectMethodInvokesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.FailedLocalLoginsNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of failed local logins on the device in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of failed local logins is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"FailedLocalLoginsNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.FileUploadsNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of file uploads from the device to the cloud in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of file uploads is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"FileUploadsNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.QueuePurgesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device queue purges in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of device queue purges is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"QueuePurgesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.TwinUpdatesNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number of twin updates (by the device or the service) in the time window is not in the allowed range\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of twin updates is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"TwinUpdatesNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\t&armsecurity.UnauthorizedOperationsNotInAllowedRange{\n\t\t// \t\t\t\t\t\tDescription: to.Ptr(\"Get an alert when the number unauthorized operations in the time window is not in the allowed range. Unauthorized operations are operations that affect the device (or done by it) that fail because of an unauthorized error\"),\n\t\t// \t\t\t\t\t\tDisplayName: to.Ptr(\"Number of unauthorized operations is not in allowed range\"),\n\t\t// \t\t\t\t\t\tIsEnabled: to.Ptr(false),\n\t\t// \t\t\t\t\t\tRuleType: to.Ptr(\"UnauthorizedOperationsNotInAllowedRange\"),\n\t\t// \t\t\t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t// \t\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func GetSecurityGroupInfo(sess *session.Session) (*ec2.DescribeSecurityGroupsOutput, error) {\n // snippet-start:[ec2.go.describe_security_groups.call]\n svc := ec2.New(sess)\n\n result, err := svc.DescribeSecurityGroups(nil)\n // snippet-end:[ec2.go.describe_security_groups.call]\n if err != nil {\n return nil, err\n }\n\n return result, nil\n}", "func (a *Client) ListOpenstackSecurityGroups(params *ListOpenstackSecurityGroupsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackSecurityGroupsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackSecurityGroupsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackSecurityGroups\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/providers/openstack/securitygroups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackSecurityGroupsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackSecurityGroupsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackSecurityGroupsDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (instance *Host) ListSecurityGroups(ctx context.Context, state securitygroupstate.Enum) (list []*propertiesv1.SecurityGroupBond, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\txerr := instance.Inspect(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tlist = FilterBondsByKind(hsgV1.ByID, state)\n\t\t\treturn nil\n\t\t})\n\t})\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\treturn list, nil\n}", "func (service *Service) GetAll() (*[]CloudSecurityGroupResponse, *http.Response, error) {\n\tv := new([]CloudSecurityGroupResponse)\n\tresp, err := service.Client.NewRequestDo(\"GET\", awsSgResourcePath, nil, nil, v)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn v, resp, nil\n}", "func Find(ec2Client aws.EC2API, nameTags []*string) ([]*SecurityGroup, error) {\n\tfilters := []*ec2.Filter{\n\t\t&ec2.Filter{\n\t\t\tName: to.Strp(\"tag-key\"),\n\t\t\tValues: []*string{to.Strp(\"Name\")},\n\t\t},\n\t\t&ec2.Filter{\n\t\t\tName: to.Strp(\"tag-value\"),\n\t\t\tValues: nameTags,\n\t\t},\n\t}\n\n\toutput, err := ec2Client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\tFilters: filters,\n\t\tMaxResults: to.Int64p(5), // Smallest allowed value returns\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsgs := newSGs(output.SecurityGroups)\n\tswitch len(sgs) {\n\tcase len(nameTags):\n\t\treturn sgs, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Number of Security Groups %v/%v\", len(sgs), len(nameTags))\n\t}\n}", "func dataSourceSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {\n config := meta.(*PConfig)\n\n platform := d.Get(\"platform\").(string)\n siteID := d.Get(\"vcs\").(string)\n\n resourcePath := fmt.Sprintf(\"api/v3/%s/sites/%s/\", platform, siteID)\n response, err := config.doNormalRequest(platform, resourcePath, \"GET\", nil)\n if err != nil {\n return fmt.Errorf(\"Unable to get VCS %s: %v\", siteID, err)\n }\n var site map[string]interface{}\n if err = json.Unmarshal([]byte(response), &site); err != nil {\n return err\n }\n projectID := int(site[\"project\"].(float64))\n var serverID int\n for _, server := range site[\"servers\"].([]interface{}) {\n serverInfo := server.(map[string]interface{})\n serverID = int(serverInfo[\"id\"].(float64))\n break\n }\n\n resourcePath = fmt.Sprintf(\"api/v3/%s/security_groups/?project=%d&server=%d\", platform, projectID, serverID)\n response, err = config.doNormalRequest(platform, resourcePath, \"GET\", nil)\n\n if err != nil {\n return fmt.Errorf(\"Unable to list security_groups: %v\", err)\n }\n\n var security_groups []map[string]interface{}\n if err = json.Unmarshal([]byte(response), &security_groups); err != nil {\n return err\n }\n\n for _, security_group := range security_groups {\n return dataSourceSecurityGroupAttributes(d, security_group)\n }\n\n return fmt.Errorf(\"Unable to retrieve security group by VCS %s: %v\", siteID, err)\n}", "func (*ListSecurityGroupsRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{1}\n}", "func (client *AwsClientWrapper) GetSecurityGroups(machine *clusterv1alpha1.Machine) ([]string, error) {\n\tinstance, err := getRunningInstance(machine, client.client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar groups []string\n\tfor _, groupIdentifier := range instance.SecurityGroups {\n\t\tif *groupIdentifier.GroupName != \"\" {\n\t\t\tgroups = append(groups, *groupIdentifier.GroupName)\n\t\t}\n\t}\n\treturn groups, nil\n}", "func (c *MockNetworkSecurityGroupsClient) List(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, error) {\n\tvar l []network.SecurityGroup\n\tfor _, nsg := range c.NSGs {\n\t\tl = append(l, nsg)\n\t}\n\treturn l, nil\n}", "func (*ListSecurityGroupsResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{2}\n}", "func (stg *securityTestGroup) getSecurityGroups(agent string) ([]security.NetworkSecurityPolicy, error) {\n\tvar sgplist []security.NetworkSecurityPolicy\n\tstatus, err := stg.authAgentClient.Req(\"GET\", \"https://\"+agent+\":\"+globals.AgentProxyPort+\"/api/sgs/\", nil, &sgplist)\n\tif err != nil || status != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Error getting SG Policies list: %v\", err)\n\t}\n\treturn sgplist, nil\n}", "func ExampleDeviceSecurityGroupsClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewDeviceSecurityGroupsClient().Get(ctx, \"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\", \"samplesecuritygroup\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DeviceSecurityGroup = armsecurity.DeviceSecurityGroup{\n\t// \tName: to.Ptr(\"samplesecuritygroup\"),\n\t// \tType: to.Ptr(\"Microsoft.Security/deviceSecurityGroups\"),\n\t// \tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub/providers/Microsoft.Security/deviceSecurityGroups/samplesecuritygroup\"),\n\t// \tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t// \t\tAllowlistRules: []armsecurity.AllowlistCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ConnectionToIPNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when an outbound connection is created between your device and an ip that isn't allowed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Outbound connection to an ip that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ConnectionToIpNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeIPCidr),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.LocalUserNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a local user that isn't allowed logins to the device\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Login by a local user that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"LocalUserNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.ProcessNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a process that isn't allowed is executed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Execution of a process that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ProcessNotAllowed\"),\n\t// \t\t\t\tValueType: to.Ptr(armsecurity.ValueTypeString),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t}},\n\t// \t\tDenylistRules: []*armsecurity.DenylistCustomAlertRule{\n\t// \t\t},\n\t// \t\tThresholdRules: []armsecurity.ThresholdCustomAlertRuleClassification{\n\t// \t\t},\n\t// \t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of active connections of a device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of active connections is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.DirectMethodInvokesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of direct method invokes in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of direct method invokes is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"DirectMethodInvokesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FailedLocalLoginsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of failed local logins on the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of failed local logins is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FailedLocalLoginsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FileUploadsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of file uploads from the device to the cloud in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of file uploads is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FileUploadsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.QueuePurgesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device queue purges in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device queue purges is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"QueuePurgesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.TwinUpdatesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of twin updates (by the device or the service) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of twin updates is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"TwinUpdatesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.UnauthorizedOperationsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number unauthorized operations in the time window is not in the allowed range. Unauthorized operations are operations that affect the device (or done by it) that fail because of an unauthorized error\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of unauthorized operations is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"UnauthorizedOperationsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t}},\n\t// \t},\n\t// }\n}", "func (a *Client) ListOpenstackSecurityGroupsNoCredentials(params *ListOpenstackSecurityGroupsNoCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackSecurityGroupsNoCredentialsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackSecurityGroupsNoCredentialsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackSecurityGroupsNoCredentials\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/projects/{project_id}/dc/{dc}/clusters/{cluster_id}/providers/openstack/securitygroups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackSecurityGroupsNoCredentialsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackSecurityGroupsNoCredentialsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackSecurityGroupsNoCredentialsDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (a *Client) ListOpenstackSecurityGroupsNoCredentialsV2(params *ListOpenstackSecurityGroupsNoCredentialsV2Params, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOpenstackSecurityGroupsNoCredentialsV2OK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListOpenstackSecurityGroupsNoCredentialsV2Params()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listOpenstackSecurityGroupsNoCredentialsV2\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v2/projects/{project_id}/clusters/{cluster_id}/providers/openstack/securitygroups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListOpenstackSecurityGroupsNoCredentialsV2Reader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListOpenstackSecurityGroupsNoCredentialsV2OK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListOpenstackSecurityGroupsNoCredentialsV2Default)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func NewListSecurityGroupsRequest(server string) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/security-group\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (*ListNetworkSecurityGroupsRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{11}\n}", "func ExampleDeviceSecurityGroupsClient_NewListPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armsecurity.NewDeviceSecurityGroupsClient(cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := client.NewListPager(\"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\",\n\t\tnil)\n\tfor pager.More() {\n\t\tnextResult, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range nextResult.Value {\n\t\t\t// TODO: use page item\n\t\t\t_ = v\n\t\t}\n\t}\n}", "func (c *Client) ListSecurityGroups(ctx context.Context, zone string) ([]*SecurityGroup, error) {\n\tlist := make([]*SecurityGroup, 0)\n\n\tresp, err := c.ListSecurityGroupsWithResponse(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.JSON200.SecurityGroups != nil {\n\t\tfor i := range *resp.JSON200.SecurityGroups {\n\t\t\tsecurityGroup := securityGroupFromAPI(&(*resp.JSON200.SecurityGroups)[i])\n\t\t\tsecurityGroup.c = c\n\t\t\tsecurityGroup.zone = zone\n\n\t\t\tlist = append(list, securityGroup)\n\t\t}\n\t}\n\n\treturn list, nil\n}", "func (c *MockApplicationSecurityGroupsClient) List(ctx context.Context, resourceGroupName string) ([]network.ApplicationSecurityGroup, error) {\n\tvar l []network.ApplicationSecurityGroup\n\tfor _, nsg := range c.ASGs {\n\t\tl = append(l, nsg)\n\t}\n\treturn l, nil\n}", "func (s *HostListener) ListSecurityGroups(ctx context.Context, in *protocol.SecurityGroupHostBindRequest) (_ *protocol.SecurityGroupBondsResponse, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(&err)\n\tdefer fail.OnExitWrapError(&err, \"cannot disable security group on host\")\n\tdefer fail.OnPanic(&err)\n\n\tif s == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn nil, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif ctx == nil {\n\t\treturn nil, fail.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\n\tif ok, err := govalidator.ValidateStruct(in); err == nil && !ok {\n\t\tlogrus.Warnf(\"Structure validation failure: %v\", in) // FIXME: Generate json tags in protobuf\n\t}\n\n\thostRef, hostRefLabel := srvutils.GetReference(in.GetHost())\n\tif hostRef == \"\" {\n\t\treturn nil, fail.InvalidRequestError(\"neither name nor id given as reference of Host\")\n\t}\n\n\tjob, xerr := PrepareJob(ctx, in.GetHost().GetTenantId(), fmt.Sprintf(\"/host/%s/securitygroups/list\", hostRef))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\ttracer := debug.NewTracer(job.Task(), tracing.ShouldTrace(\"listeners.host\"), \"(%s)\", hostRefLabel).WithStopwatch().Entering()\n\tdefer tracer.Exiting()\n\tdefer fail.OnExitLogError(&err, tracer.TraceMessage())\n\n\thostInstance, xerr := hostfactory.Load(job.Service(), hostRef)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tdefer hostInstance.Released()\n\n\tbonds, xerr := hostInstance.ListSecurityGroups(securitygroupstate.All)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tresp := converters.SecurityGroupBondsFromPropertyToProtocol(bonds, \"hosts\")\n\treturn resp, nil\n}", "func (provider *ResourceProvider) SecurityGroup(id string) (*reachAWS.SecurityGroup, error) {\n\tinput := &ec2.DescribeSecurityGroupsInput{\n\t\tGroupIds: []*string{\n\t\t\taws.String(id),\n\t\t},\n\t}\n\tresult, err := provider.ec2.DescribeSecurityGroups(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = ensureSingleResult(len(result.SecurityGroups), \"security group\", id); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecurityGroup := newSecurityGroupFromAPI(result.SecurityGroups[0])\n\treturn &securityGroup, nil\n}", "func (*ListNetworkSecurityGroupsResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{12}\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSubnetworksExecute(r ApiBrowseCloudSubnetworksRequest) (CloudSubnetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSubnetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSubnetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSubnetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.availabilityZone != nil {\n\t\tlocalVarQueryParams.Add(\"availabilityZone\", parameterToString(*r.availabilityZone, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *Client) ListProvidersByRegionShort(params *ListProvidersByRegionParams, authInfo runtime.ClientAuthInfoWriter) (*ListProvidersByRegionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListProvidersByRegionParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListProvidersByRegion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/dsmcontroller/public/providers/regions/{region}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListProvidersByRegionReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *ListProvidersByRegionOK:\n\t\treturn v, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func (o *CreateLoadBalancerRequest) GetSecurityGroups() []string {\n\tif o == nil || o.SecurityGroups == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SecurityGroups\n}", "func (a *Client) GetPlatformSecurityGroups(params *GetPlatformSecurityGroupsParams) (*GetPlatformSecurityGroupsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetPlatformSecurityGroupsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getPlatformSecurityGroups\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/security_groups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetPlatformSecurityGroupsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetPlatformSecurityGroupsOK), nil\n\n}", "func Listv2SGs(se Session) (PolicyList []interface{}) {\n\t// Create an EC2 service client.\n\tsvc := ec2.New(se.Sess)\n\n\t// Retrieve the security sg descriptions\n\tresult, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\tDryRun: aws.Bool(false),\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase \"InvalidGroupId.Malformed\":\n\t\t\t\tfallthrough\n\t\t\tcase \"InvalidGroup.NotFound\":\n\t\t\t\texitErrorf(\"%s.\", aerr.Message())\n\t\t\t}\n\t\t}\n\t\texitErrorf(\"Unable to get descriptions for security sgs, %v\", err)\n\t}\n\t//\n\tpolicy := new(PolicyDetail)\n\tfor _, sg := range result.SecurityGroups {\n\t\tfor _, ippermission := range sg.IpPermissions {\n\t\t\tif *ippermission.IpProtocol == \"-1\" {\n\t\t\t\tif len(ippermission.IpRanges) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.IpRanges {\n\t\t\t\t\t\t// fmt.Println(\" ALL IpRanges information:\", *sg.GroupName, *sg.VpcId, *sg.GroupId, \"ALL PROTOCOL\", \"from port ALL\", \"end port ALL\", *permission.CidrIp)\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.CidrIp\n\t\t\t\t\t\tpolicy.Protocol = \"ALL\"\n\t\t\t\t\t\tpolicy.FromPort = 0\n\t\t\t\t\t\tpolicy.ToPort = 65535\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(ippermission.UserIdGroupPairs) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.UserIdGroupPairs {\n\t\t\t\t\t\t// fmt.Println(\" ALL GroupPairs information:\", *sg.GroupName, *sg.VpcId, *sg.GroupId, \"ALLPROTOCOL\", \"fromportALL\", \"endportALL\", *permission.GroupId)\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.GroupId\n\t\t\t\t\t\tpolicy.Protocol = \"ALL\"\n\t\t\t\t\t\tpolicy.FromPort = 0\n\t\t\t\t\t\tpolicy.ToPort = 65535\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(ippermission.PrefixListIds) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.PrefixListIds {\n\t\t\t\t\t\t//fmt.Println(\" ===all===Prefix information:\", permission)\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.PrefixListId\n\t\t\t\t\t\tpolicy.Protocol = \"Unknow\"\n\t\t\t\t\t\tpolicy.FromPort = 0\n\t\t\t\t\t\tpolicy.ToPort = 65535\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif len(ippermission.IpRanges) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.IpRanges {\n\t\t\t\t\t\t//fmt.Println(\" IpRanges information:\", *sg.GroupName, *sg.VpcId, *sg.GroupId, *ippermission.IpProtocol, *ippermission.FromPort, *ippermission.ToPort, *permission.CidrIp)\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.CidrIp\n\t\t\t\t\t\tpolicy.Protocol = *ippermission.IpProtocol\n\t\t\t\t\t\tpolicy.FromPort = *ippermission.FromPort\n\t\t\t\t\t\tpolicy.ToPort = *ippermission.ToPort\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(ippermission.UserIdGroupPairs) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.UserIdGroupPairs {\n\t\t\t\t\t\t//fmt.Println(\" GroupPairs information:\", *sg.GroupName, *sg.VpcId, *sg.GroupId, *ippermission.IpProtocol, *ippermission.FromPort, *ippermission.ToPort, *permission.GroupId )\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.GroupId\n\t\t\t\t\t\tpolicy.Protocol = *ippermission.IpProtocol\n\t\t\t\t\t\tpolicy.FromPort = *ippermission.FromPort\n\t\t\t\t\t\tpolicy.ToPort = *ippermission.ToPort\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(ippermission.PrefixListIds) != 0 {\n\t\t\t\t\tfor _, permission := range ippermission.PrefixListIds {\n\t\t\t\t\t\t//fmt.Println(\" ======Prefix information:\", permission)\n\t\t\t\t\t\tpolicy.GroupName = *sg.GroupName\n\t\t\t\t\t\tpolicy.VpcId = *sg.VpcId\n\t\t\t\t\t\tpolicy.GroupId = *sg.GroupId\n\t\t\t\t\t\tpolicy.Source = *permission.PrefixListId\n\t\t\t\t\t\tpolicy.Protocol = \"Unknow\"\n\t\t\t\t\t\tpolicy.FromPort = -1\n\t\t\t\t\t\tpolicy.ToPort = -1\n\t\t\t\t\t\tPolicyList = append(PolicyList, *policy)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn PolicyList\n}", "func ExampleDeviceSecurityGroupsClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armsecurity.NewDeviceSecurityGroupsClient(cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.Get(ctx,\n\t\t\"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\",\n\t\t\"samplesecuritygroup\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (s *SubnetListener) ListSecurityGroups(inctx context.Context, in *protocol.SecurityGroupSubnetBindRequest) (_ *protocol.SecurityGroupBondsResponse, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitLogError(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot list Security Groups bound to Subnet\")\n\n\tif s == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn nil, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif inctx == nil {\n\t\treturn nil, fail.InvalidParameterError(\"inctx\", \"cannot be nil\")\n\t}\n\n\tnetworkRef, _ := srvutils.GetReference(in.GetNetwork())\n\tsubnetRef, _ := srvutils.GetReference(in.GetSubnet())\n\tif subnetRef == \"\" {\n\t\treturn nil, fail.InvalidRequestError(\"neither name nor id given as reference for Subnet\")\n\t}\n\n\tjob, xerr := PrepareJob(inctx, in.GetNetwork().GetTenantId(), fmt.Sprintf(\"network/%s/subnet/%s/securitygroups/list\", networkRef, subnetRef))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\tstate := securitygroupstate.Enum(in.GetState())\n\n\thandler := handlers.NewSubnetHandler(job)\n\tbonds, xerr := handler.ListSecurityGroups(networkRef, subnetRef, state)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\tresp := converters.SecurityGroupBondsFromPropertyToProtocol(bonds, \"subnets\")\n\treturn resp, nil\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSubnetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSubnetworksRequest {\n\treturn ApiBrowseCloudSubnetworksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (c *Client) ListKubernetesSecurityGroups(ctx context.Context, vpcID, clusterName string) ([]string, error) {\n\tgroups, err := c.EC2.DescribeSecurityGroupsWithContext(ctx, &ec2.DescribeSecurityGroupsInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"vpc-id\"),\n\t\t\t\tValues: []*string{aws.String(vpcID)},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"tag-key\"),\n\t\t\t\tValues: []*string{aws.String(fmt.Sprintf(\"kubernetes.io/cluster/%s\", clusterName))},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"tag-value\"),\n\t\t\t\tValues: []*string{aws.String(\"owned\")},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []string\n\tfor _, group := range groups.SecurityGroups {\n\t\tresults = append(results, *group.GroupId)\n\t}\n\n\treturn results, nil\n}", "func (*ListSecurityGroupOperationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{13}\n}", "func (c *Client) ListKubernetesSecurityGroups(vpcID, clusterName string) ([]string, error) {\n\tgroups, err := c.EC2.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"vpc-id\"),\n\t\t\t\tValues: []*string{aws.String(vpcID)},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"tag-key\"),\n\t\t\t\tValues: []*string{aws.String(fmt.Sprintf(\"kubernetes.io/cluster/%s\", clusterName))},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"tag-value\"),\n\t\t\t\tValues: []*string{aws.String(\"owned\")},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := []string{}\n\tfor _, group := range groups.SecurityGroups {\n\t\tresults = append(results, *group.GroupId)\n\t}\n\n\treturn results, nil\n}", "func (s *applicationSecurityGroupLister) List(selector labels.Selector) (ret []*v1alpha1.ApplicationSecurityGroup, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ApplicationSecurityGroup))\n\t})\n\treturn ret, err\n}", "func createSecurityGroup(client ec2iface.EC2API, vpcID, clusterName string) (string, error) {\n\tvar securityGroupID string\n\n\tnewSecurityGroupName := resourceNamePrefix + clusterName\n\tcsgOut, err := client.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{\n\t\tVpcId: &vpcID,\n\t\tGroupName: aws.String(newSecurityGroupName),\n\t\tDescription: aws.String(fmt.Sprintf(\"Security group for the Kubernetes cluster %s\", clusterName)),\n\t})\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != \"InvalidGroup.Duplicate\" {\n\t\t\treturn \"\", fmt.Errorf(\"failed to create security group %s: %v\", newSecurityGroupName, err)\n\t\t}\n\t\tdescribeOut, err := client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\t\tFilters: []*ec2.Filter{{\n\t\t\t\tName: aws.String(\"group-name\"),\n\t\t\t\tValues: []*string{aws.String(newSecurityGroupName)}}},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to get security group after creation failed because the group already existed: %v\", err)\n\t\t}\n\t\tif n := len(describeOut.SecurityGroups); n != 1 {\n\t\t\treturn \"\", fmt.Errorf(\"expected to get exactly one security group after create failed because the group already existed, got %d\", n)\n\t\t}\n\n\t\tsecurityGroupID = aws.StringValue(describeOut.SecurityGroups[0].GroupId)\n\t}\n\tif csgOut != nil && csgOut.GroupId != nil {\n\t\tsecurityGroupID = *csgOut.GroupId\n\t}\n\tklog.V(2).Infof(\"Security group %s for cluster %s created with id %s.\", newSecurityGroupName, clusterName, securityGroupID)\n\n\t// Add permissions.\n\t_, err = client.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{\n\t\tGroupId: aws.String(securityGroupID),\n\t\tIpPermissions: []*ec2.IpPermission{\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// all protocols from within the sg\n\t\t\t\tSetIpProtocol(\"-1\").\n\t\t\t\tSetUserIdGroupPairs([]*ec2.UserIdGroupPair{\n\t\t\t\t\t(&ec2.UserIdGroupPair{}).\n\t\t\t\t\t\tSetGroupId(securityGroupID),\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// tcp:22 from everywhere\n\t\t\t\tSetIpProtocol(\"tcp\").\n\t\t\t\tSetFromPort(provider.DefaultSSHPort).\n\t\t\t\tSetToPort(provider.DefaultSSHPort).\n\t\t\t\tSetIpRanges([]*ec2.IpRange{\n\t\t\t\t\t{CidrIp: aws.String(\"0.0.0.0/0\")},\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// ICMP from/to everywhere\n\t\t\t\tSetIpProtocol(\"icmp\").\n\t\t\t\tSetFromPort(-1). // any port\n\t\t\t\tSetToPort(-1). // any port\n\t\t\t\tSetIpRanges([]*ec2.IpRange{\n\t\t\t\t\t{CidrIp: aws.String(\"0.0.0.0/0\")},\n\t\t\t\t}),\n\t\t\t(&ec2.IpPermission{}).\n\t\t\t\t// ICMPv6 from/to everywhere\n\t\t\t\tSetIpProtocol(\"icmpv6\").\n\t\t\t\tSetFromPort(-1). // any port\n\t\t\t\tSetToPort(-1). // any port\n\t\t\t\tSetIpv6Ranges([]*ec2.Ipv6Range{\n\t\t\t\t\t{CidrIpv6: aws.String(\"::/0\")},\n\t\t\t\t}),\n\t\t},\n\t})\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != \"InvalidPermission.Duplicate\" {\n\t\t\treturn \"\", fmt.Errorf(\"failed to authorize security group %s with id %s: %v\", newSecurityGroupName, securityGroupID, err)\n\t\t}\n\t}\n\n\treturn securityGroupID, nil\n}", "func (service *Service) GetAllInRegion(d9CloudAccountID, awsRegionName string) (*[]CloudSecurityGroupResponse, *http.Response, error) {\n\tif d9CloudAccountID == \"\" && awsRegionName == \"\" {\n\t\treturn nil, nil, fmt.Errorf(\"d9 cloud account id and aws region name must be passed\")\n\t}\n\n\toptions := GetSecurityGroupQueryParameters{\n\t\tCloudAccountID: d9CloudAccountID,\n\t\tRegionID: awsRegionName,\n\t}\n\n\tv := new([]CloudSecurityGroupResponse)\n\tresp, err := service.Client.NewRequestDo(\"GET\", awsSgResourcePath, options, nil, v)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn v, resp, nil\n}", "func requestCredList(ctx aws.Context, client *ec2metadata.EC2Metadata) ([]string, error) {\n\tresp, err := client.GetMetadataWithContext(ctx, iamSecurityCredsPath)\n\tif err != nil {\n\t\treturn nil, awserr.New(\"EC2RoleRequestError\", \"no EC2 instance role found\", err)\n\t}\n\n\tcredsList := []string{}\n\ts := bufio.NewScanner(strings.NewReader(resp))\n\tfor s.Scan() {\n\t\tcredsList = append(credsList, s.Text())\n\t}\n\n\tif err := s.Err(); err != nil {\n\t\treturn nil, awserr.New(request.ErrCodeSerialization,\n\t\t\t\"failed to read EC2 instance role from metadata service\", err)\n\t}\n\n\treturn credsList, nil\n}", "func ExampleRegulatoryComplianceStandardsClient_NewListPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewRegulatoryComplianceStandardsClient().NewListPager(&armsecurity.RegulatoryComplianceStandardsClientListOptions{Filter: nil})\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.RegulatoryComplianceStandardList = armsecurity.RegulatoryComplianceStandardList{\n\t\t// \tValue: []*armsecurity.RegulatoryComplianceStandard{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"PCI-DSS-3.2\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.Security/regulatoryComplianceStandard\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/regulatoryComplianceStandards/PCI-DSS-3.2\"),\n\t\t// \t\t\tProperties: &armsecurity.RegulatoryComplianceStandardProperties{\n\t\t// \t\t\t\tFailedControls: to.Ptr[int32](4),\n\t\t// \t\t\t\tPassedControls: to.Ptr[int32](7),\n\t\t// \t\t\t\tSkippedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tState: to.Ptr(armsecurity.StateFailed),\n\t\t// \t\t\t\tUnsupportedControls: to.Ptr[int32](0),\n\t\t// \t\t\t},\n\t\t// \t\t},\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"ISO-27001\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.Security/regulatoryComplianceStandard\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/regulatoryComplianceStandards/ISO-27001\"),\n\t\t// \t\t\tProperties: &armsecurity.RegulatoryComplianceStandardProperties{\n\t\t// \t\t\t\tFailedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tPassedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tSkippedControls: to.Ptr[int32](10),\n\t\t// \t\t\t\tState: to.Ptr(armsecurity.StateSkipped),\n\t\t// \t\t\t\tUnsupportedControls: to.Ptr[int32](0),\n\t\t// \t\t\t},\n\t\t// \t\t},\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"AZURE-CIS\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.Security/regulatoryComplianceStandard\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/regulatoryComplianceStandards/AZURE-CIS\"),\n\t\t// \t\t\tProperties: &armsecurity.RegulatoryComplianceStandardProperties{\n\t\t// \t\t\t\tFailedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tPassedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tSkippedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tState: to.Ptr(armsecurity.StateUnsupported),\n\t\t// \t\t\t\tUnsupportedControls: to.Ptr[int32](0),\n\t\t// \t\t\t},\n\t\t// \t\t},\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"SOC-TSP\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.Security/regulatoryComplianceStandard\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/regulatoryComplianceStandards/SOC-TSP\"),\n\t\t// \t\t\tProperties: &armsecurity.RegulatoryComplianceStandardProperties{\n\t\t// \t\t\t\tFailedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tPassedControls: to.Ptr[int32](15),\n\t\t// \t\t\t\tSkippedControls: to.Ptr[int32](0),\n\t\t// \t\t\t\tState: to.Ptr(armsecurity.StatePassed),\n\t\t// \t\t\t\tUnsupportedControls: to.Ptr[int32](0),\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func ListVPC(connectionName string, rsType string) ([]*cres.VPCInfo, error) {\n\tcblog.Info(\"call ListVPC()\")\n\n\t// check empty and trim user inputs\n connectionName, err := EmptyCheckAndTrim(\"connectionName\", connectionName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n\tcldConn, err := ccm.GetCloudConnection(connectionName)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\thandler, err := cldConn.CreateVPCHandler()\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (1) get IID:list\n\tiidInfoList, err := iidRWLock.ListIID(iidm.IIDSGROUP, connectionName, rsType)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tvar infoList []*cres.VPCInfo\n\tif iidInfoList == nil || len(iidInfoList) <= 0 {\n\t\tinfoList = []*cres.VPCInfo{}\n\t\treturn infoList, nil\n\t}\n\n\t// (2) Get VPCInfo-list with IID-list\n\twg := new(sync.WaitGroup)\n\tresultInfoList := []*cres.VPCInfo{}\n var retChanInfos []chan ResultVPCInfo\n for i:=0 ; i<len(iidInfoList); i++ {\n retChanInfos = append(retChanInfos, make(chan ResultVPCInfo))\n }\n\n for idx, iidInfo := range iidInfoList {\n\n wg.Add(1)\n\n go getVPCInfo(connectionName, handler, iidInfo.IId, retChanInfos[idx])\n\n wg.Done()\n\n }\n wg.Wait()\n\n var errList []string\n for idx, retChanInfo := range retChanInfos {\n chanInfo := <-retChanInfo\n\n if chanInfo.err != nil {\n if checkNotFoundError(chanInfo.err) {\n cblog.Info(chanInfo.err) } else {\n errList = append(errList, connectionName + \":VPC:\" + iidInfoList[idx].IId.NameId + \" # \" + chanInfo.err.Error())\n }\n } else {\n resultInfoList = append(resultInfoList, &chanInfo.vpcInfo)\n }\n\n close(retChanInfo)\n }\n\n if len(errList) > 0 {\n cblog.Error(strings.Join(errList, \"\\n\"))\n return nil, errors.New(strings.Join(errList, \"\\n\"))\n }\n\n return resultInfoList, nil\n}", "func (p *GroupsProvider) RetrieveGroups() ([]string, error) {\n\n\tauthAuthenticatorURL := p.Config.OIDC.TokenSVC.String()\n\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"POST\", authAuthenticatorURL, nil)\n\treq.Header.Add(\"Authorization\", p.Config.OIDC.Token)\n\treq.Header.Add(\"Stage\", p.Config.Stage)\n\treq.Header.Add(\"Environment\", p.Config.Environment)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Caller\", \"groups\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to build post request: (%s)\", err)\n\t}\n\n\tvar postErr error\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpostErr = err\n\t}\n\n\tif resp != nil {\n\n\t\tdefer resp.Body.Close()\n\n\t\tvar result map[string]interface{}\n\n\t\tjson.NewDecoder(resp.Body).Decode(&result)\n\n\t\tlog.Infof(\"Requesting roles - Client-RequestId: [%s]\", resp.Header.Get(\"x-amzn-RequestId\"))\n\n\t\tif resp.StatusCode >= 400 || postErr != nil {\n\t\t\treturn nil, fmt.Errorf(result[\"message\"].(string))\n\t\t}\n\n\t\tb, err := json.Marshal(result[\"Groups\"])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tjsonErr := json.Unmarshal(b, &groups)\n\t\tif jsonErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to marshal/unmarshal data: (%s)\", jsonErr)\n\t\t}\n\t\treturn groups, nil\n\t}\n\treturn nil, postErr\n}", "func (r Virtual_Guest) GetSecurityScanRequests() (resp []datatypes.Network_Security_Scanner_Request, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getSecurityScanRequests\", nil, &r.Options, &resp)\n\treturn\n}", "func (a *CloudProviderCredentialsApiService) ListAWSCredentialsExecute(r ApiListAWSCredentialsRequest) (ClusterCredentialsResponseList, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ClusterCredentialsResponseList\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"CloudProviderCredentialsApiService.ListAWSCredentials\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/organization/{organizationId}/aws/credentials\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"organizationId\"+\"}\", _neturl.PathEscape(parameterToString(r.organizationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *CloudProviderCredentialsApiService) ListScalewayRegionsExecute(r ApiListScalewayRegionsRequest) (ClusterRegionResponseList, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ClusterRegionResponseList\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"CloudProviderCredentialsApiService.ListScalewayRegions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/scaleway/region\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (*ListSecurityGroupOperationsResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{14}\n}", "func ExamplePrivateCloudsClient_NewListPager_privateCloudsListStretched() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewPrivateCloudsClient().NewListPager(\"group1\", nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.PrivateCloudList = armavs.PrivateCloudList{\n\t\t// \tValue: []*armavs.PrivateCloud{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"cloud1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.AVS/privateClouds\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AVS/privateClouds/cloud1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"eastus2\"),\n\t\t// \t\t\tTags: map[string]*string{\n\t\t// \t\t\t},\n\t\t// \t\t\tProperties: &armavs.PrivateCloudProperties{\n\t\t// \t\t\t\tAvailability: &armavs.AvailabilityProperties{\n\t\t// \t\t\t\t\tSecondaryZone: to.Ptr[int32](2),\n\t\t// \t\t\t\t\tStrategy: to.Ptr(armavs.AvailabilityStrategyDualZone),\n\t\t// \t\t\t\t\tZone: to.Ptr[int32](1),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tIdentitySources: []*armavs.IdentitySource{\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"group1\"),\n\t\t// \t\t\t\t\t\tAlias: to.Ptr(\"groupAlias\"),\n\t\t// \t\t\t\t\t\tBaseGroupDN: to.Ptr(\"ou=baseGroup\"),\n\t\t// \t\t\t\t\t\tBaseUserDN: to.Ptr(\"ou=baseUser\"),\n\t\t// \t\t\t\t\t\tDomain: to.Ptr(\"domain1\"),\n\t\t// \t\t\t\t\t\tPrimaryServer: to.Ptr(\"ldaps://1.1.1.1:636/\"),\n\t\t// \t\t\t\t\t\tSecondaryServer: to.Ptr(\"ldaps://1.1.1.2:636/\"),\n\t\t// \t\t\t\t\t\tSSL: to.Ptr(armavs.SSLEnumEnabled),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tInternet: to.Ptr(armavs.InternetEnumDisabled),\n\t\t// \t\t\t\tManagementCluster: &armavs.ManagementCluster{\n\t\t// \t\t\t\t\tClusterID: to.Ptr[int32](1),\n\t\t// \t\t\t\t\tClusterSize: to.Ptr[int32](4),\n\t\t// \t\t\t\t\tHosts: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost18.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost19.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost20.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost21.nyc1.kubernetes.center\")},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect\"),\n\t\t// \t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tEndpoints: &armavs.Endpoints{\n\t\t// \t\t\t\t\t\tHcxCloudManager: to.Ptr(\"https://192.168.50.4/\"),\n\t\t// \t\t\t\t\t\tNsxtManager: to.Ptr(\"https://192.168.50.3/\"),\n\t\t// \t\t\t\t\t\tVcsa: to.Ptr(\"https://192.168.50.2/\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tExternalCloudLinks: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"/subscriptions/12341234-1234-1234-1234-123412341234/resourceGroups/mygroup/providers/Microsoft.AVS/privateClouds/cloud2\")},\n\t\t// \t\t\t\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armavs.PrivateCloudProvisioningStateSucceeded),\n\t\t// \t\t\t\t\t\tSecondaryCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect2\"),\n\t\t// \t\t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er2/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t\t},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tSKU: &armavs.SKU{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"AV36\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t}},\n\t\t// \t\t}\n\t}\n}", "func dataSourceSecurityGroupAttributes(d *schema.ResourceData, data map[string]interface{}) error {\n security_group_id := data[\"id\"].(string)\n log.Printf(\"[DEBUG] Retrieved twcc_security_group: %s\", security_group_id)\n\n d.SetId(security_group_id)\n d.Set(\"name\", data[\"name\"])\n security_group_rules := flattenSecurityGroupRulesInfo(data[\"security_group_rules\"].([]interface{}))\n d.Set(\"security_group_rules\", security_group_rules)\n\n return nil\n}", "func (s *applicationSecurityGroupLister) ApplicationSecurityGroups(namespace string) ApplicationSecurityGroupNamespaceLister {\n\treturn applicationSecurityGroupNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func ExampleRDS_DescribeDBSecurityGroups_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DescribeDBSecurityGroupsInput{\n\t\tDBSecurityGroupName: aws.String(\"mydbsecuritygroup\"),\n\t}\n\n\tresult, err := svc.DescribeDBSecurityGroups(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase rds.ErrCodeDBSecurityGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupNotFoundFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (a *AmazonConnectionsApiService) BrowseCloudNetworksExecute(r ApiBrowseCloudNetworksRequest) (CloudNetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudNetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudNetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudNetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (v *Vps) PopulateSecurityGroups(os *OpenStack) error {\n\tvar err error\n\n\t// Security Groups\n\tresult := servers.GetResult{}\n\turl := os.Compute.ServiceURL(\"servers\", v.ID, \"os-security-groups\")\n\t_, err = os.Compute.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar resp struct {\n\t\tSecurityGroups []secgroups.SecurityGroup `mapstructure:\"security_groups\"`\n\t}\n\n\tif err = mapstructure.Decode(result.Body, &resp); err != nil {\n\t\treturn err\n\t}\n\tv.SecurityGroups = resp.SecurityGroups\n\n\treturn nil\n}", "func (a *CloudProviderCredentialsApiService) ListScalewayCredentialsExecute(r ApiListScalewayCredentialsRequest) (ClusterCredentialsResponseList, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ClusterCredentialsResponseList\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"CloudProviderCredentialsApiService.ListScalewayCredentials\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/organization/{organizationId}/scaleway/credentials\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"organizationId\"+\"}\", _neturl.PathEscape(parameterToString(r.organizationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *Client) ListProvidersByRegion(params *ListProvidersByRegionParams, authInfo runtime.ClientAuthInfoWriter) (*ListProvidersByRegionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListProvidersByRegionParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListProvidersByRegion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/dsmcontroller/public/providers/regions/{region}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListProvidersByRegionReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *ListProvidersByRegionOK:\n\t\treturn v, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func (a *CloudProviderCredentialsApiService) ListAWSRegionsExecute(r ApiListAWSRegionsRequest) (ClusterRegionResponseList, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ClusterRegionResponseList\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"CloudProviderCredentialsApiService.ListAWSRegions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/aws/region\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *Client) ListProvidersShort(params *ListProvidersParams, authInfo runtime.ClientAuthInfoWriter) (*ListProvidersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListProvidersParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListProviders\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/dsmcontroller/public/providers\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListProvidersReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *ListProvidersOK:\n\t\treturn v, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func ExampleDeviceSecurityGroupsClient_CreateOrUpdate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewDeviceSecurityGroupsClient().CreateOrUpdate(ctx, \"subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub\", \"samplesecuritygroup\", armsecurity.DeviceSecurityGroup{\n\t\tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t\t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t\t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t\t\t\t\tIsEnabled: to.Ptr(true),\n\t\t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t\t\t\t\tMaxThreshold: to.Ptr[int32](30),\n\t\t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t\t\t\t\tTimeWindowSize: to.Ptr(\"PT05M\"),\n\t\t\t\t}},\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DeviceSecurityGroup = armsecurity.DeviceSecurityGroup{\n\t// \tName: to.Ptr(\"samplesecuritygroup\"),\n\t// \tType: to.Ptr(\"Microsoft.Security/deviceSecurityGroups\"),\n\t// \tID: to.Ptr(\"/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/resourceGroups/SampleRG/providers/Microsoft.Devices/iotHubs/sampleiothub/providers/Microsoft.Security/deviceSecurityGroups/samplesecuritygroup\"),\n\t// \tProperties: &armsecurity.DeviceSecurityGroupProperties{\n\t// \t\tAllowlistRules: []armsecurity.AllowlistCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ConnectionToIPNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when an outbound connection is created between your device and an ip that isn't allowed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Outbound connection to an ip that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ConnectionToIpNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.LocalUserNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a local user that isn't allowed logins to the device\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Login by a local user that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"LocalUserNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.ProcessNotAllowed{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when a process that isn't allowed is executed\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Execution of a process that isn't allowed\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"ProcessNotAllowed\"),\n\t// \t\t\t\tAllowlistValues: []*string{\n\t// \t\t\t\t},\n\t// \t\t}},\n\t// \t\tDenylistRules: []*armsecurity.DenylistCustomAlertRule{\n\t// \t\t},\n\t// \t\tThresholdRules: []armsecurity.ThresholdCustomAlertRuleClassification{\n\t// \t\t},\n\t// \t\tTimeWindowRules: []armsecurity.TimeWindowCustomAlertRuleClassification{\n\t// \t\t\t&armsecurity.ActiveConnectionsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of active connections of a device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of active connections is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(true),\n\t// \t\t\t\tRuleType: to.Ptr(\"ActiveConnectionsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](30),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT05M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (AMQP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (MQTT protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPC2DRejectedMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of cloud to device messages (HTTP protocol) that were rejected by the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of rejected cloud to device messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpC2DRejectedMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.AmqpD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (AMQP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (AMQP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"AmqpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.MqttD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (MQTT protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (MQTT protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"MqttD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.HTTPD2CMessagesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device to cloud messages (HTTP protocol) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device to cloud messages (HTTP protocol) is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"HttpD2CMessagesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.DirectMethodInvokesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of direct method invokes in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of direct method invokes is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"DirectMethodInvokesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FailedLocalLoginsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of failed local logins on the device in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of failed local logins is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FailedLocalLoginsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.FileUploadsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of file uploads from the device to the cloud in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of file uploads is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"FileUploadsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.QueuePurgesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of device queue purges in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of device queue purges is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"QueuePurgesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.TwinUpdatesNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number of twin updates (by the device or the service) in the time window is not in the allowed range\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of twin updates is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"TwinUpdatesNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t\t},\n\t// \t\t\t&armsecurity.UnauthorizedOperationsNotInAllowedRange{\n\t// \t\t\t\tDescription: to.Ptr(\"Get an alert when the number unauthorized operations in the time window is not in the allowed range. Unauthorized operations are operations that affect the device (or done by it) that fail because of an unauthorized error\"),\n\t// \t\t\t\tDisplayName: to.Ptr(\"Number of unauthorized operations is not in allowed range\"),\n\t// \t\t\t\tIsEnabled: to.Ptr(false),\n\t// \t\t\t\tRuleType: to.Ptr(\"UnauthorizedOperationsNotInAllowedRange\"),\n\t// \t\t\t\tMaxThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tMinThreshold: to.Ptr[int32](0),\n\t// \t\t\t\tTimeWindowSize: to.Ptr(\"PT15M\"),\n\t// \t\t}},\n\t// \t},\n\t// }\n}", "func (a *CloudProviderCredentialsApiService) ListScalewayRegions(ctx _context.Context) ApiListScalewayRegionsRequest {\n\treturn ApiListScalewayRegionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *ClientWithResponses) ListSecurityGroupsWithResponse(ctx context.Context) (*ListSecurityGroupsResponse, error) {\n\trsp, err := c.ListSecurityGroups(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseListSecurityGroupsResponse(rsp)\n}", "func ExamplePrivateCloudsClient_NewListPager_privateCloudsList() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewPrivateCloudsClient().NewListPager(\"group1\", nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.PrivateCloudList = armavs.PrivateCloudList{\n\t\t// \tValue: []*armavs.PrivateCloud{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"cloud1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.AVS/privateClouds\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AVS/privateClouds/cloud1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"eastus2\"),\n\t\t// \t\t\tTags: map[string]*string{\n\t\t// \t\t\t},\n\t\t// \t\t\tProperties: &armavs.PrivateCloudProperties{\n\t\t// \t\t\t\tAvailability: &armavs.AvailabilityProperties{\n\t\t// \t\t\t\t\tStrategy: to.Ptr(armavs.AvailabilityStrategySingleZone),\n\t\t// \t\t\t\t\tZone: to.Ptr[int32](1),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tIdentitySources: []*armavs.IdentitySource{\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"group1\"),\n\t\t// \t\t\t\t\t\tAlias: to.Ptr(\"groupAlias\"),\n\t\t// \t\t\t\t\t\tBaseGroupDN: to.Ptr(\"ou=baseGroup\"),\n\t\t// \t\t\t\t\t\tBaseUserDN: to.Ptr(\"ou=baseUser\"),\n\t\t// \t\t\t\t\t\tDomain: to.Ptr(\"domain1\"),\n\t\t// \t\t\t\t\t\tPrimaryServer: to.Ptr(\"ldaps://1.1.1.1:636/\"),\n\t\t// \t\t\t\t\t\tSecondaryServer: to.Ptr(\"ldaps://1.1.1.2:636/\"),\n\t\t// \t\t\t\t\t\tSSL: to.Ptr(armavs.SSLEnumEnabled),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tInternet: to.Ptr(armavs.InternetEnumDisabled),\n\t\t// \t\t\t\tManagementCluster: &armavs.ManagementCluster{\n\t\t// \t\t\t\t\tClusterID: to.Ptr[int32](1),\n\t\t// \t\t\t\t\tClusterSize: to.Ptr[int32](4),\n\t\t// \t\t\t\t\tHosts: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost18.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost19.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost20.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost21.nyc1.kubernetes.center\")},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect\"),\n\t\t// \t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tEndpoints: &armavs.Endpoints{\n\t\t// \t\t\t\t\t\tHcxCloudManager: to.Ptr(\"https://192.168.50.4/\"),\n\t\t// \t\t\t\t\t\tNsxtManager: to.Ptr(\"https://192.168.50.3/\"),\n\t\t// \t\t\t\t\t\tVcsa: to.Ptr(\"https://192.168.50.2/\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tExternalCloudLinks: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"/subscriptions/12341234-1234-1234-1234-123412341234/resourceGroups/mygroup/providers/Microsoft.AVS/privateClouds/cloud2\")},\n\t\t// \t\t\t\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armavs.PrivateCloudProvisioningStateSucceeded),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tSKU: &armavs.SKU{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"AV36\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t}},\n\t\t// \t\t}\n\t}\n}", "func ListEndpoint(projectProvider provider.ProjectProvider, privilegedProjectProvider provider.PrivilegedProjectProvider, serviceAccountProvider provider.ServiceAccountProvider, privilegedServiceAccount provider.PrivilegedServiceAccountProvider, memberMapper provider.ProjectMemberMapper, userInfoGetter provider.UserInfoGetter) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treq, ok := request.(common.GetProjectRq)\n\t\tif !ok {\n\t\t\treturn nil, errors.NewBadRequest(\"invalid request\")\n\t\t}\n\n\t\tif len(req.ProjectID) == 0 {\n\t\t\treturn nil, errors.NewBadRequest(\"the name of the project cannot be empty\")\n\t\t}\n\n\t\tproject, err := common.GetProject(ctx, userInfoGetter, projectProvider, privilegedProjectProvider, req.ProjectID)\n\t\tif err != nil {\n\t\t\treturn nil, common.KubernetesErrorToHTTPError(err)\n\t\t}\n\t\tsaList, err := listSA(ctx, serviceAccountProvider, privilegedServiceAccount, userInfoGetter, project, nil)\n\t\tif err != nil {\n\t\t\treturn nil, common.KubernetesErrorToHTTPError(err)\n\t\t}\n\n\t\tvar errorList []string\n\t\tresponse := make([]*apiv1.ServiceAccount, 0)\n\t\tfor _, sa := range saList {\n\t\t\texternalSA := convertInternalServiceAccountToExternal(sa)\n\t\t\tif apiv1.ServiceAccountInactive == externalSA.Status {\n\t\t\t\tresponse = append(response, externalSA)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tgroup, err := memberMapper.MapUserToGroup(sa.Spec.Email, project.Name)\n\t\t\tif err != nil {\n\t\t\t\terrorList = append(errorList, err.Error())\n\t\t\t} else {\n\t\t\t\texternalSA.Group = group\n\t\t\t\tresponse = append(response, externalSA)\n\t\t\t}\n\t\t}\n\t\tif len(errorList) > 0 {\n\t\t\treturn response, errors.NewWithDetails(http.StatusInternalServerError, \"failed to get some service accounts, please examine details field for more info\", errorList)\n\t\t}\n\n\t\treturn response, nil\n\t}\n}", "func (a *CloudProviderCredentialsApiService) ListScalewayCredentials(ctx _context.Context, organizationId string) ApiListScalewayCredentialsRequest {\n\treturn ApiListScalewayCredentialsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\torganizationId: organizationId,\n\t}\n}", "func (m *GraphBaseServiceClient) Security()(*i35d7bbcc8f7e8b8e9525ea0ee5b3c51c3a1a58f9ed512b727d181bfcd08eb032.SecurityRequestBuilder) {\n return i35d7bbcc8f7e8b8e9525ea0ee5b3c51c3a1a58f9ed512b727d181bfcd08eb032.NewSecurityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Security()(*i35d7bbcc8f7e8b8e9525ea0ee5b3c51c3a1a58f9ed512b727d181bfcd08eb032.SecurityRequestBuilder) {\n return i35d7bbcc8f7e8b8e9525ea0ee5b3c51c3a1a58f9ed512b727d181bfcd08eb032.NewSecurityRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (o InstanceOutput) SecurityGroups() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.SecurityGroups }).(pulumi.StringArrayOutput)\n}", "func (a *CloudProviderCredentialsApiService) ListAWSCredentials(ctx _context.Context, organizationId string) ApiListAWSCredentialsRequest {\n\treturn ApiListAWSCredentialsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\torganizationId: organizationId,\n\t}\n}", "func listInfo() ([]*RegionInfo, error) {\n // ex-1)\n // /cloud-info-spaces/regions/aws_region01/AWS/region [ap-northeast-2]\n // ex-2)\n // /cloud-info-spaces/regions/gcp_region02/GCP/region [us-east1]\n // /cloud-info-spaces/regions/gcp_region02/GCP/zone [us-east1-c]\n\n\n key := \"/cloud-info-spaces/regions\"\n keyValueList, err := store.GetList(key, true)\n if err != nil {\n return nil, err\n }\n\n var regionInfoList []*RegionInfo\n\tvar inKeyValueList []icbs.KeyValue\n\tprevRegionName := \"\"\n\tprevProviderName := \"\"\n for _, kv := range keyValueList {\n\n\t\tregionName := utils.GetNodeValue(kv.Key, 3)\n\t\tproviderName := utils.GetNodeValue(kv.Key, 4)\n\n\t\tif prevRegionName==\"\" || regionName == prevRegionName {\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t} else {\n\t\t\t// insert prev RegionInfo\n\t\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\n\t\t\tprevRegionName = regionName\n\t\t\tprevProviderName = providerName\n\t\t\tinKeyValueList = nil\n\t\t\tkeyValue := icbs.KeyValue{utils.GetNodeValue(kv.Key, 5), kv.Value}\n\t\t\tinKeyValueList = append(inKeyValueList, keyValue)\n\t\t}\n\n }\n\n\tif len(keyValueList) > 0 {\n\t\t// insert last RegionInfo\n\t\trgnInfo := &RegionInfo{prevRegionName, prevProviderName, inKeyValueList}\n\t\tregionInfoList = append(regionInfoList, rgnInfo)\n\t}\n\n return regionInfoList, nil\n}", "func (instance *Host) setSecurityGroups(ctx context.Context, req abstract.HostRequest, defaultSubnet resources.Subnet) fail.Error {\n\tsvc := instance.Service()\n\tif req.Single {\n\t\thostID, err := instance.GetID()\n\t\tif err != nil {\n\t\t\treturn fail.ConvertError(err)\n\t\t}\n\t\tfor k := range req.SecurityGroupIDs {\n\t\t\tif k != \"\" {\n\t\t\t\tlogrus.WithContext(ctx).Infof(\"Binding security group with id %s to host %s\", k, hostID)\n\t\t\t\txerr := svc.BindSecurityGroupToHost(ctx, k, hostID)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\treturn xerr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\txerr := instance.Alter(ctx, func(clonable data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Alter(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) (finnerXErr fail.Error) {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\t// get default Subnet core data\n\t\t\tvar (\n\t\t\t\tdefaultAbstractSubnet *abstract.Subnet\n\t\t\t\tdefaultSubnetID string\n\t\t\t)\n\t\t\tinnerXErr := defaultSubnet.Inspect(ctx,\n\t\t\t\tfunc(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {\n\t\t\t\t\tvar ok bool\n\t\t\t\t\tdefaultAbstractSubnet, ok = clonable.(*abstract.Subnet)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.Subnet' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t\t}\n\n\t\t\t\t\tdefaultSubnetID = defaultAbstractSubnet.ID\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t)\n\t\t\tif innerXErr != nil {\n\t\t\t\treturn innerXErr\n\t\t\t}\n\n\t\t\tvar gwsg, pubipsg, lansg resources.SecurityGroup\n\n\t\t\t// Apply Security Group for gateways in default Subnet\n\t\t\tif req.IsGateway && defaultAbstractSubnet.GWSecurityGroupID != \"\" {\n\t\t\t\tgwsg, innerXErr = LoadSecurityGroup(ctx, svc, defaultAbstractSubnet.GWSecurityGroupID)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to query Subnet '%s' Security Group '%s'\", defaultSubnet.GetName(), defaultAbstractSubnet.GWSecurityGroupID)\n\t\t\t\t}\n\n\t\t\t\tinnerXErr = gwsg.BindToHost(ctx, instance, resources.SecurityGroupEnable, resources.MarkSecurityGroupAsSupplemental)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to apply Subnet's GW Security Group for gateway '%s' on Host '%s'\", gwsg.GetName(), req.ResourceName)\n\t\t\t\t}\n\n\t\t\t\tdefer func() {\n\t\t\t\t\tif finnerXErr != nil && !req.KeepOnFailure {\n\t\t\t\t\t\tderr := gwsg.UnbindFromHost(cleanupContextFrom(ctx), instance)\n\t\t\t\t\t\tif derr != nil {\n\t\t\t\t\t\t\t_ = finnerXErr.AddConsequence(fail.Wrap(derr, \"cleaning up on %s, failed to unbind Security Group '%s' from Host '%s'\", ActionFromError(finnerXErr), gwsg.GetName(), req.ResourceName))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tgwid, err := gwsg.GetID()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fail.ConvertError(err)\n\t\t\t\t}\n\n\t\t\t\titem := &propertiesv1.SecurityGroupBond{\n\t\t\t\t\tID: gwid,\n\t\t\t\t\tName: gwsg.GetName(),\n\t\t\t\t\tDisabled: false,\n\t\t\t\t\tFromSubnet: true,\n\t\t\t\t}\n\t\t\t\thsgV1.ByID[item.ID] = item\n\t\t\t\thsgV1.ByName[item.Name] = item.ID\n\t\t\t}\n\n\t\t\t// Apply Security Group for hosts with public IP in default Subnet\n\t\t\tif (req.IsGateway || req.PublicIP) && defaultAbstractSubnet.PublicIPSecurityGroupID != \"\" {\n\t\t\t\tpubipsg, innerXErr = LoadSecurityGroup(ctx, svc, defaultAbstractSubnet.PublicIPSecurityGroupID)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to query Subnet '%s' Security Group with ID %s\", defaultSubnet.GetName(), defaultAbstractSubnet.PublicIPSecurityGroupID)\n\t\t\t\t}\n\n\t\t\t\tinnerXErr = pubipsg.BindToHost(ctx, instance, resources.SecurityGroupEnable, resources.MarkSecurityGroupAsSupplemental)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to apply Subnet's Public Security Group for gateway '%s' on Host '%s'\", pubipsg.GetName(), req.ResourceName)\n\t\t\t\t}\n\n\t\t\t\tdefer func() {\n\t\t\t\t\tif finnerXErr != nil && !req.KeepOnFailure {\n\t\t\t\t\t\tderr := pubipsg.UnbindFromHost(cleanupContextFrom(ctx), instance)\n\t\t\t\t\t\tif derr != nil {\n\t\t\t\t\t\t\t_ = finnerXErr.AddConsequence(fail.Wrap(derr, \"cleaning up on %s, failed to unbind Security Group '%s' from Host '%s'\", ActionFromError(finnerXErr), pubipsg.GetName(), req.ResourceName))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\t\tpubID, err := pubipsg.GetID()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fail.ConvertError(err)\n\t\t\t\t}\n\n\t\t\t\titem := &propertiesv1.SecurityGroupBond{\n\t\t\t\t\tID: pubID,\n\t\t\t\t\tName: pubipsg.GetName(),\n\t\t\t\t\tDisabled: false,\n\t\t\t\t\tFromSubnet: true,\n\t\t\t\t}\n\t\t\t\thsgV1.ByID[item.ID] = item\n\t\t\t\thsgV1.ByName[item.Name] = item.ID\n\t\t\t}\n\n\t\t\t// Apply internal Security Group of each other subnets\n\t\t\tdefer func() {\n\t\t\t\tif finnerXErr != nil && !req.KeepOnFailure {\n\t\t\t\t\tvar (\n\t\t\t\t\t\tsg resources.SecurityGroup\n\t\t\t\t\t\tderr error\n\t\t\t\t\t\terrs []error\n\t\t\t\t\t)\n\t\t\t\t\tfor _, v := range req.Subnets {\n\t\t\t\t\t\tif v.ID == defaultSubnetID {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsubnetInstance, deeperXErr := LoadSubnet(cleanupContextFrom(ctx), svc, \"\", v.ID)\n\t\t\t\t\t\tif deeperXErr != nil {\n\t\t\t\t\t\t\t_ = innerXErr.AddConsequence(deeperXErr)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsgName := sg.GetName()\n\t\t\t\t\t\tdeeperXErr = subnetInstance.Inspect(cleanupContextFrom(ctx), func(\n\t\t\t\t\t\t\tclonable data.Clonable, _ *serialize.JSONProperties,\n\t\t\t\t\t\t) fail.Error {\n\t\t\t\t\t\t\tabstractSubnet, ok := clonable.(*abstract.Subnet)\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.Subnet' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif abstractSubnet.InternalSecurityGroupID != \"\" {\n\t\t\t\t\t\t\t\tsg, derr = LoadSecurityGroup(cleanupContextFrom(ctx), svc, abstractSubnet.InternalSecurityGroupID)\n\t\t\t\t\t\t\t\tif derr != nil {\n\t\t\t\t\t\t\t\t\terrs = append(errs, derr)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tderr = sg.UnbindFromHost(cleanupContextFrom(ctx), instance)\n\t\t\t\t\t\t\t\t\tif derr != nil {\n\t\t\t\t\t\t\t\t\t\terrs = append(errs, derr)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t})\n\t\t\t\t\t\tif deeperXErr != nil {\n\t\t\t\t\t\t\t_ = finnerXErr.AddConsequence(fail.Wrap(deeperXErr, \"cleaning up on failure, failed to unbind Security Group '%s' from Host\", sgName))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif len(errs) > 0 {\n\t\t\t\t\t\t_ = finnerXErr.AddConsequence(fail.Wrap(fail.NewErrorList(errs), \"failed to unbind Subnets Security Group from Host '%s'\", sg.GetName(), req.ResourceName))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor _, v := range req.Subnets {\n\t\t\t\t// Do not try to bind defaultSubnet on gateway, because this code is running under a lock on defaultSubnet in this case, and this will lead to deadlock\n\t\t\t\t// (binding of gateway on defaultSubnet is done inside Subnet.Create() call)\n\t\t\t\tif req.IsGateway && v.ID == defaultSubnetID {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\totherSubnetInstance, innerXErr := LoadSubnet(ctx, svc, \"\", v.ID)\n\t\t\t\tinnerXErr = debug.InjectPlannedFail(innerXErr)\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn innerXErr\n\t\t\t\t}\n\n\t\t\t\tvar otherAbstractSubnet *abstract.Subnet\n\t\t\t\tinnerXErr = otherSubnetInstance.Inspect(ctx, func(\n\t\t\t\t\tclonable data.Clonable, _ *serialize.JSONProperties,\n\t\t\t\t) fail.Error {\n\t\t\t\t\tvar ok bool\n\t\t\t\t\totherAbstractSubnet, ok = clonable.(*abstract.Subnet)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.Subnet' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t\t}\n\t\t\t\t\t_ = otherAbstractSubnet\n\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif innerXErr != nil {\n\t\t\t\t\treturn innerXErr\n\t\t\t\t}\n\n\t\t\t\tsafe := false\n\n\t\t\t\t// Fix for Stein\n\t\t\t\t{\n\t\t\t\t\tst, xerr := svc.GetProviderName()\n\t\t\t\t\tif xerr != nil {\n\t\t\t\t\t\treturn xerr\n\t\t\t\t\t}\n\t\t\t\t\tif st != \"ovh\" {\n\t\t\t\t\t\tsafe = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif cfg, xerr := svc.GetConfigurationOptions(ctx); xerr == nil {\n\t\t\t\t\tif aval, ok := cfg.Get(\"Safe\"); ok {\n\t\t\t\t\t\tif val, ok := aval.(bool); ok {\n\t\t\t\t\t\t\tsafe = val\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif otherAbstractSubnet.InternalSecurityGroupID != \"\" {\n\t\t\t\t\tlansg, innerXErr = LoadSecurityGroup(ctx, svc, otherAbstractSubnet.InternalSecurityGroupID)\n\t\t\t\t\tif innerXErr != nil {\n\t\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to load Subnet '%s' internal Security Group %s\", otherAbstractSubnet.Name, otherAbstractSubnet.InternalSecurityGroupID)\n\t\t\t\t\t}\n\n\t\t\t\t\tif !safe {\n\t\t\t\t\t\tinnerXErr = svc.ChangeSecurityGroupSecurity(ctx, false, true, otherAbstractSubnet.Network, \"\")\n\t\t\t\t\t\tif innerXErr != nil {\n\t\t\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to change security group\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tinnerXErr = lansg.BindToHost(ctx, instance, resources.SecurityGroupEnable, resources.MarkSecurityGroupAsSupplemental)\n\t\t\t\t\tif innerXErr != nil {\n\t\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to apply Subnet '%s' internal Security Group '%s' to Host '%s'\", otherAbstractSubnet.Name, lansg.GetName(), req.ResourceName)\n\t\t\t\t\t}\n\n\t\t\t\t\tif !safe {\n\t\t\t\t\t\tinnerXErr = svc.ChangeSecurityGroupSecurity(ctx, true, false, otherAbstractSubnet.Network, \"\")\n\t\t\t\t\t\tif innerXErr != nil {\n\t\t\t\t\t\t\treturn fail.Wrap(innerXErr, \"failed to change security group\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tlangID, err := lansg.GetID()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fail.ConvertError(err)\n\t\t\t\t\t}\n\n\t\t\t\t\t// register security group in properties\n\t\t\t\t\titem := &propertiesv1.SecurityGroupBond{\n\t\t\t\t\t\tID: langID,\n\t\t\t\t\t\tName: lansg.GetName(),\n\t\t\t\t\t\tDisabled: false,\n\t\t\t\t\t\tFromSubnet: true,\n\t\t\t\t\t}\n\t\t\t\t\thsgV1.ByID[item.ID] = item\n\t\t\t\t\thsgV1.ByName[item.Name] = item.ID\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\treturn nil\n}", "func main() {\n opts := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: \"http://10.169.41.188/identity\",\n\t\tUsername: \"admin\",\n\t\tPassword: \"password\",\n\t\tTenantID: \"01821bd38f2f474489491adb0da7efaf\",\n\t\tDomainID: \"default\",\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tfmt.Println(err)\n\tif err != nil {\n\t\tfmt.Errorf(\"Sending get container group request failed: %v\", err)\n\t\treturn\n\t}\n client, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{\n\t\tRegion: \"RegionOne\",\n\t})\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to create a network client: %v\", err)\n\t}\n\tallPages, err := subnets.List(client, nil).AllPages()\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to list subnets: %v\", err)\n\t}\n\n\tallSubnets, err := subnets.ExtractSubnets(allPages)\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to extract subnets: %v\", err)\n\t}\n\n\tfor _, subnet := range allSubnets {\n\t b, _ := json.MarshalIndent(subnet, \"\", \" \")\n fmt.Printf(\"%s\", string(b))\n }\n\n}", "func (o *ClusterUninstaller) listVPCs() (cloudResources, error) {\n\to.Logger.Debugf(\"Listing VPCs\")\n\n\tctx, cancel := o.contextWithTimeout()\n\tdefer cancel()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\to.Logger.Debugf(\"listVPCs: case <-ctx.Done()\")\n\t\treturn nil, o.Context.Err() // we're cancelled, abort\n\tdefault:\n\t}\n\n\toptions := o.vpcSvc.NewListVpcsOptions()\n\tvpcs, _, err := o.vpcSvc.ListVpcs(options)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to list vps\")\n\t}\n\n\tvar foundOne = false\n\n\tresult := []cloudResource{}\n\tfor _, vpc := range vpcs.Vpcs {\n\t\tif strings.Contains(*vpc.Name, o.InfraID) {\n\t\t\tfoundOne = true\n\t\t\to.Logger.Debugf(\"listVPCs: FOUND: %s, %s\", *vpc.ID, *vpc.Name)\n\t\t\tresult = append(result, cloudResource{\n\t\t\t\tkey: *vpc.ID,\n\t\t\t\tname: *vpc.Name,\n\t\t\t\tstatus: \"\",\n\t\t\t\ttypeName: vpcTypeName,\n\t\t\t\tid: *vpc.ID,\n\t\t\t})\n\t\t}\n\t}\n\tif !foundOne {\n\t\to.Logger.Debugf(\"listVPCs: NO matching vpc against: %s\", o.InfraID)\n\t\tfor _, vpc := range vpcs.Vpcs {\n\t\t\to.Logger.Debugf(\"listVPCs: vpc: %s\", *vpc.Name)\n\t\t}\n\t}\n\n\treturn cloudResources{}.insert(result...), nil\n}", "func (o *CreateLoadBalancerRequest) GetSecurityGroupsOk() (*[]string, bool) {\n\tif o == nil || o.SecurityGroups == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SecurityGroups, true\n}", "func (stg *securityTestGroup) testSecurityGroupCreateDelete() {\n\t// sg params\n\tsg := security.SecurityGroup{\n\t\tTypeMeta: api.TypeMeta{Kind: \"SecurityGroup\"},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tTenant: \"default\",\n\t\t\tNamespace: \"default\",\n\t\t\tName: \"group1\",\n\t\t},\n\t\tSpec: security.SecurityGroupSpec{\n\t\t\tWorkloadSelector: labels.SelectorFromSet(labels.Set{\"env\": \"production\", \"app\": \"procurement\"}),\n\t\t},\n\t}\n\tvar securityGroupRestIf security.SecurityV1SecurityGroupInterface\n\tapiGwAddr := ts.tu.ClusterVIP + \":\" + globals.APIGwRESTPort\n\trestSvc, err := apiclient.NewRestAPIClient(apiGwAddr)\n\tif err == nil {\n\t\tBy(\"Creating SecurityGroup Client ------\")\n\t\tsecurityGroupRestIf = restSvc.SecurityV1().SecurityGroup()\n\t}\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(stg.securityRestIf).ShouldNot(Equal(nil))\n\n\tctx := ts.tu.MustGetLoggedInContext(context.Background())\n\t// create sg policy\n\tresp, err := securityGroupRestIf.Create(ctx, &sg)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\t// verify we can read the policy back\n\trsg, err := securityGroupRestIf.Get(ctx, &sg.ObjectMeta)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(rsg).Should(Equal(resp))\n\n\t// verify agents have the policy\n\tEventually(func() bool {\n\t\tfor _, naplesIP := range ts.tu.NaplesNodeIPs {\n\t\t\tsglist, err := stg.getSecurityGroups(naplesIP)\n\t\t\tif err != nil {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list failed, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (len(sglist) != 1) || (sglist[0].Name != sg.Name) {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list has invalid items, security groups: %+v\", time.Now().String(), sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tBy(fmt.Sprintf(\"ts:%s security group list success, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t}\n\t\treturn true\n\t}, 30, 1).Should(BeTrue(), \"Failed to get security groups on netagent\")\n\n\t// delete the sg policy\n\tEventually(func() error {\n\t\t_, err = securityGroupRestIf.Delete(ctx, &sg.ObjectMeta)\n\t\treturn err\n\t}, 30, 1).ShouldNot(HaveOccurred())\n\n\t// verify policy is gone from the agents\n\tEventually(func() bool {\n\t\tfor _, naplesIP := range ts.tu.NaplesNodeIPs {\n\t\t\tsglist, err := stg.getSecurityGroups(naplesIP)\n\t\t\tif err != nil {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list failed, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif len(sglist) != 0 {\n\t\t\t\tBy(fmt.Sprintf(\"ts:%s security group list has invalid items, sg groups: %+v\", time.Now().String(), sglist))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tBy(fmt.Sprintf(\"ts:%s security group list success, err: %+v sgs: %+v\", time.Now().String(), err, sglist))\n\t\t}\n\t\treturn true\n\t}, 30, 1).Should(BeTrue(), \"Failed to get security groups on netagent\")\n}", "func setSecurityGroups(c *cli.Context) error {\n\terr := checkArgCount(c, 2)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid := c.Args().First()\n\titems := []string{}\n\tif c.Args()[1] != \"\" {\n\t\titems = regexp.MustCompile(`\\s*,\\s*`).Split(c.Args()[1], -1)\n\t}\n\tsecurityGroups := &photon.SecurityGroupsSpec{\n\t\tItems: items,\n\t}\n\n\tclient.Photonclient, err = client.GetClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttask, err := client.Photonclient.Tenants.SetSecurityGroups(id, securityGroups)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = waitOnTaskOperation(task.ID, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ExamplePrivateCloudsClient_NewListInSubscriptionPager_privateCloudsListInSubscriptionStretched() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewPrivateCloudsClient().NewListInSubscriptionPager(nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.PrivateCloudList = armavs.PrivateCloudList{\n\t\t// \tValue: []*armavs.PrivateCloud{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"cloud1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.AVS/privateClouds\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AVS/privateClouds/cloud1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"eastus2\"),\n\t\t// \t\t\tTags: map[string]*string{\n\t\t// \t\t\t},\n\t\t// \t\t\tProperties: &armavs.PrivateCloudProperties{\n\t\t// \t\t\t\tAvailability: &armavs.AvailabilityProperties{\n\t\t// \t\t\t\t\tSecondaryZone: to.Ptr[int32](2),\n\t\t// \t\t\t\t\tStrategy: to.Ptr(armavs.AvailabilityStrategyDualZone),\n\t\t// \t\t\t\t\tZone: to.Ptr[int32](1),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tIdentitySources: []*armavs.IdentitySource{\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"group1\"),\n\t\t// \t\t\t\t\t\tAlias: to.Ptr(\"groupAlias\"),\n\t\t// \t\t\t\t\t\tBaseGroupDN: to.Ptr(\"ou=baseGroup\"),\n\t\t// \t\t\t\t\t\tBaseUserDN: to.Ptr(\"ou=baseUser\"),\n\t\t// \t\t\t\t\t\tDomain: to.Ptr(\"domain1\"),\n\t\t// \t\t\t\t\t\tPrimaryServer: to.Ptr(\"ldaps://1.1.1.1:636/\"),\n\t\t// \t\t\t\t\t\tSecondaryServer: to.Ptr(\"ldaps://1.1.1.2:636/\"),\n\t\t// \t\t\t\t\t\tSSL: to.Ptr(armavs.SSLEnumEnabled),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tInternet: to.Ptr(armavs.InternetEnumDisabled),\n\t\t// \t\t\t\tManagementCluster: &armavs.ManagementCluster{\n\t\t// \t\t\t\t\tClusterID: to.Ptr[int32](1),\n\t\t// \t\t\t\t\tClusterSize: to.Ptr[int32](4),\n\t\t// \t\t\t\t\tHosts: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost18.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost19.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost20.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost21.nyc1.kubernetes.center\")},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect\"),\n\t\t// \t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tEndpoints: &armavs.Endpoints{\n\t\t// \t\t\t\t\t\tHcxCloudManager: to.Ptr(\"https://192.168.50.4/\"),\n\t\t// \t\t\t\t\t\tNsxtManager: to.Ptr(\"https://192.168.50.3/\"),\n\t\t// \t\t\t\t\t\tVcsa: to.Ptr(\"https://192.168.50.2/\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t\t// \t\t\t\t\tProvisioningState: to.Ptr(armavs.PrivateCloudProvisioningStateSucceeded),\n\t\t// \t\t\t\t\tSecondaryCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect2\"),\n\t\t// \t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er2/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tSKU: &armavs.SKU{\n\t\t// \t\t\t\t\tName: to.Ptr(\"AV36\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t}},\n\t\t// \t}\n\t}\n}", "func (c *Client) EvalEC2SG(accounts []*policy.Account, p policy.Policy, regions []string, f func(policy.Violation)) error {\n\tvar errs error\n\tctx := context.Background()\n\terr := c.WalkAccountsAndRegions(accounts, regions, func(client *cziAws.Client, account *policy.Account, region string) {\n\t\tvar nextToken *string\n\t\t// Limiting to 1000 iteration guarantees that we don't get an infinite loop, even if we have\n\t\t// a mistake below. Small tradeoff is that if there are greater than 1000*pagesize security\n\t\t// groups we won't scan them all.\n\t\tfor i := 1; i <= 1000; i++ {\n\t\t\tlog.Debugf(\"nextToken: %#v\", nextToken)\n\t\t\tinput := &ec2.DescribeSecurityGroupsInput{NextToken: nextToken}\n\n\t\t\toutput, err := client.EC2.Svc.DescribeSecurityGroupsWithContext(ctx, input)\n\n\t\t\tif err != nil {\n\t\t\t\terrs = multierror.Append(errs, err)\n\t\t\t} else {\n\t\t\t\tfor _, sg := range output.SecurityGroups {\n\t\t\t\t\ts := NewEC2SG(sg, region)\n\t\t\t\t\tif p.Match(s) {\n\t\t\t\t\t\tviolation := policy.NewViolation(p, s, false, account)\n\t\t\t\t\t\tf(violation)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif output.NextToken == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnextToken = output.NextToken\n\t\t}\n\t})\n\terrs = multierror.Append(errs, err)\n\n\treturn errs\n}", "func (o *CloudAwsVirtualMachineAllOf) GetSecurityGroups() []CloudAwsSecurityGroupRelationship {\n\tif o == nil {\n\t\tvar ret []CloudAwsSecurityGroupRelationship\n\t\treturn ret\n\t}\n\treturn o.SecurityGroups\n}", "func (c *Client) BindSecurityGroups(args *BindSecurityGroupsArgs) error {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn BindSecurityGroups(c, body)\n}", "func SecurityGroups(groups ...string) RequestOptionFunc {\n\treturn func(body *RequestBody) error {\n\t\tbody.SecurityGroup = groups\n\t\treturn nil\n\t}\n}", "func QueryMySqlInstanceSecurityGroups(providerParams string, instanceId string) ([]string, error) {\n\tsecurityGroups := []string{}\n\tparamsMap, err := GetMapFromProviderParams(providerParams)\n\tclient, err := CreateMysqlVmClient(paramsMap[\"Region\"], paramsMap[\"SecretID\"], paramsMap[\"SecretKey\"])\n\tif err != nil {\n\t\treturn securityGroups, err\n\t}\n\n\trequest := cdb.NewDescribeDBSecurityGroupsRequest()\n\trequest.InstanceId = &instanceId\n\n\tresponse, err := client.DescribeDBSecurityGroups(request)\n\tif err != nil {\n\t\tlogrus.Errorf(\"cdb DescribeDBSecurityGroups meet err=%v\", err)\n\t\treturn securityGroups, err\n\t}\n\n\tfor _, group := range response.Response.Groups {\n\t\tsecurityGroups = append(securityGroups, *group.SecurityGroupId)\n\t}\n\treturn securityGroups, nil\n}", "func (o *QtreeCollectionGetParams) SetSecurityStyle(securityStyle *string) {\n\to.SecurityStyle = securityStyle\n}", "func (s applicationSecurityGroupNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ApplicationSecurityGroup, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ApplicationSecurityGroup))\n\t})\n\treturn ret, err\n}", "func (a *AmazonConnectionsApiService) BrowseCloudNetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudNetworksRequest {\n\treturn ApiBrowseCloudNetworksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (m *MockSecurityGroupServiceIface) ListSecurityGroups(p *ListSecurityGroupsParams) (*ListSecurityGroupsResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListSecurityGroups\", p)\n\tret0, _ := ret[0].(*ListSecurityGroupsResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) List() goa.Endpoint {\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\tinv := goagrpc.NewInvoker(\n\t\t\tBuildListFunc(c.grpccli, c.opts...),\n\t\t\tEncodeListRequest,\n\t\t\tDecodeListResponse)\n\t\tres, err := inv.Invoke(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, goa.Fault(err.Error())\n\t\t}\n\t\treturn res, nil\n\t}\n}", "func ExamplePrivateCloudsClient_NewListInSubscriptionPager_privateCloudsListInSubscription() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewPrivateCloudsClient().NewListInSubscriptionPager(nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.PrivateCloudList = armavs.PrivateCloudList{\n\t\t// \tValue: []*armavs.PrivateCloud{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"cloud1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.AVS/privateClouds\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AVS/privateClouds/cloud1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"eastus2\"),\n\t\t// \t\t\tTags: map[string]*string{\n\t\t// \t\t\t},\n\t\t// \t\t\tProperties: &armavs.PrivateCloudProperties{\n\t\t// \t\t\t\tAvailability: &armavs.AvailabilityProperties{\n\t\t// \t\t\t\t\tStrategy: to.Ptr(armavs.AvailabilityStrategySingleZone),\n\t\t// \t\t\t\t\tZone: to.Ptr[int32](1),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tIdentitySources: []*armavs.IdentitySource{\n\t\t// \t\t\t\t\t{\n\t\t// \t\t\t\t\t\tName: to.Ptr(\"group1\"),\n\t\t// \t\t\t\t\t\tAlias: to.Ptr(\"groupAlias\"),\n\t\t// \t\t\t\t\t\tBaseGroupDN: to.Ptr(\"ou=baseGroup\"),\n\t\t// \t\t\t\t\t\tBaseUserDN: to.Ptr(\"ou=baseUser\"),\n\t\t// \t\t\t\t\t\tDomain: to.Ptr(\"domain1\"),\n\t\t// \t\t\t\t\t\tPrimaryServer: to.Ptr(\"ldaps://1.1.1.1:636/\"),\n\t\t// \t\t\t\t\t\tSecondaryServer: to.Ptr(\"ldaps://1.1.1.2:636/\"),\n\t\t// \t\t\t\t\t\tSSL: to.Ptr(armavs.SSLEnumEnabled),\n\t\t// \t\t\t\t}},\n\t\t// \t\t\t\tInternet: to.Ptr(armavs.InternetEnumDisabled),\n\t\t// \t\t\t\tManagementCluster: &armavs.ManagementCluster{\n\t\t// \t\t\t\t\tClusterID: to.Ptr[int32](1),\n\t\t// \t\t\t\t\tClusterSize: to.Ptr[int32](4),\n\t\t// \t\t\t\t\tHosts: []*string{\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost18.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost19.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost20.nyc1.kubernetes.center\"),\n\t\t// \t\t\t\t\t\tto.Ptr(\"fakehost21.nyc1.kubernetes.center\")},\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tCircuit: &armavs.Circuit{\n\t\t// \t\t\t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect\"),\n\t\t// \t\t\t\t\t\tExpressRoutePrivatePeeringID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt42-cust-p01-dmo01/providers/Microsoft.Network/expressroutecircuits/tnt42-cust-p01-dmo01-er/peerings/AzurePrivatePeering\"),\n\t\t// \t\t\t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t\t// \t\t\t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tEndpoints: &armavs.Endpoints{\n\t\t// \t\t\t\t\t\tHcxCloudManager: to.Ptr(\"https://192.168.50.4/\"),\n\t\t// \t\t\t\t\t\tNsxtManager: to.Ptr(\"https://192.168.50.3/\"),\n\t\t// \t\t\t\t\t\tVcsa: to.Ptr(\"https://192.168.50.2/\"),\n\t\t// \t\t\t\t\t},\n\t\t// \t\t\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t\t// \t\t\t\t\tProvisioningState: to.Ptr(armavs.PrivateCloudProvisioningStateSucceeded),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tSKU: &armavs.SKU{\n\t\t// \t\t\t\t\tName: to.Ptr(\"AV36\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t}},\n\t\t// \t}\n\t}\n}", "func (client AccessGovernanceCPClient) listGovernanceInstances(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/governanceInstances\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListGovernanceInstancesResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/access-governance-cp/20220518/GovernanceInstanceCollection/ListGovernanceInstances\"\n\t\terr = common.PostProcessServiceError(err, \"AccessGovernanceCP\", \"ListGovernanceInstances\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func ListProviders() {\n\n\theaders := make(map[string]string)\n\theaders[\"Content-Type\"] = \"application/json\"\n\n\tauthenticator := &core.IamAuthenticator{\n\t\tApiKey: apiKey,\n\t\tURL: url, //use for dev/preprod env\n\t}\n\tservice, _ := findingsapiv1.NewFindingsApiV1(&findingsapiv1.FindingsApiV1Options{\n\t\tAuthenticator: authenticator,\n\t\tURL: \"https://us-south.secadvisor.cloud.ibm.com/findings\", //Specify url or use default\n\t})\n\n\tvar listProvidersOptions = service.NewListProvidersOptions(accountID)\n\tlistProvidersOptions.SetLimit(5)\n\tlistProvidersOptions.SetStartProviderID(\"a\")\n\tlistProvidersOptions.SetEndProviderID(\"p\")\n\n\tres, _, err := service.ListProviders(listProvidersOptions)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to get list of providers: \", err)\n\t} else {\n\t\tfmt.Printf(`Found %d Providers between \"a\" and \"p\". Limit is set to 5 per page.`, len(res.Providers))\n\t\tfmt.Println()\n\t\tif len(res.Providers) > 0 {\n\t\t\tfmt.Println(\"Providers 1 id: \", *res.Providers[0].ID)\n\t\t\tfmt.Println(\"Providers 1 name: \", *res.Providers[0].Name)\n\n\t\t}\n\t}\n\n}", "func (client GroupClient) ListCredentials(accountName string, databaseName string, filter string, top *int32, skip *int32, expand string, selectParameter string, orderby string, count *bool) (result USQLCredentialList, err error) {\n\treq, err := client.ListCredentialsPreparer(accountName, databaseName, filter, top, skip, expand, selectParameter, orderby, count)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"ListCredentials\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListCredentialsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"ListCredentials\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListCredentialsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"catalog.GroupClient\", \"ListCredentials\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client *IotSecuritySolutionClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *IotSecuritySolutionClientListByResourceGroupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-08-01\")\n\tif options != nil && options.Filter != nil {\n\t\treqQP.Set(\"$filter\", *options.Filter)\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *LaunchConfiguration) VpcClassicLinkSecurityGroups() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"vpcClassicLinkSecurityGroups\"])\n}", "func GetSecurityGroupConfig(s *ec2.SecurityGroup) []AWSResourceConfig {\n\tcf := SecurityGroupConfig{\n\t\tConfig: Config{\n\t\t\tName: s.GroupName,\n\t\t\tTags: s.Tags,\n\t\t},\n\t\tGroupName: s.GroupName,\n\t\tGroupDescription: s.GroupDescription,\n\t}\n\n\tingresses := make([]IngressEgress, 0)\n\tfor _, i := range s.SecurityGroupIngress {\n\t\tingress := IngressEgress{\n\t\t\tIPProtocol: i.IpProtocol,\n\t\t\tDescription: i.Description,\n\t\t\tCidrIP: []string{i.CidrIp},\n\t\t\tCidrIpv6: []string{i.CidrIpv6},\n\t\t\tFromPort: i.FromPort,\n\t\t\tToPort: i.ToPort,\n\t\t}\n\t\tingresses = append(ingresses, ingress)\n\t}\n\tcf.SecurityGroupIngress = ingresses\n\n\tegresses := make([]IngressEgress, 0)\n\tfor _, e := range s.SecurityGroupEgress {\n\t\tegress := IngressEgress{\n\t\t\tIPProtocol: e.IpProtocol,\n\t\t\tDescription: e.Description,\n\t\t\tCidrIP: []string{e.CidrIp},\n\t\t\tCidrIpv6: []string{e.CidrIpv6},\n\t\t\tFromPort: e.FromPort,\n\t\t\tToPort: e.ToPort,\n\t\t}\n\t\tegresses = append(egresses, egress)\n\t}\n\tcf.SecurityGroupEgress = egresses\n\n\treturn []AWSResourceConfig{{\n\t\tResource: cf,\n\t\tMetadata: s.AWSCloudFormationMetadata,\n\t}}\n}", "func (instance *Host) EnableSecurityGroup(ctx context.Context, sg resources.SecurityGroup) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\tif sg == nil {\n\t\treturn fail.InvalidParameterError(\"sg\", \"cannot be null value of 'SecurityGroup'\")\n\t}\n\n\thid, err := instance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\tsgName := sg.GetName()\n\n\t// instance.Lock()\n\t// defer instance.Unlock()\n\n\tsvc := instance.Service()\n\txerr := instance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tvar asg *abstract.SecurityGroup\n\t\t\txerr := sg.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {\n\t\t\t\tvar ok bool\n\t\t\t\tif asg, ok = clonable.(*abstract.SecurityGroup); !ok {\n\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.SecurityGroup' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn xerr\n\t\t\t}\n\n\t\t\t// First check if the security group is not already registered for the Host with the exact same state\n\t\t\tvar found bool\n\t\t\tfor k := range hsgV1.ByID {\n\t\t\t\tif k == asg.ID {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn fail.NotFoundError(\"security group '%s' is not bound to Host '%s'\", sgName, hid)\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t// Bind the security group on provider side; if already bound (*fail.ErrDuplicate), considered as a success\n\t\t\t\txerr = svc.BindSecurityGroupToHost(ctx, asg, hid)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\tswitch xerr.(type) {\n\t\t\t\t\tcase *fail.ErrDuplicate:\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, xerr)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn xerr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// found and updated, update metadata\n\t\t\thsgV1.ByID[asg.ID].Disabled = false\n\t\t\treturn nil\n\t\t})\n\t})\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\treturn nil\n}", "func NewScmProvidersGetCollectionRequest(server string, params *ScmProvidersGetCollectionParams) (*http.Request, error) {\n\tvar err error\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/v1/scmProviders\")\n\tif operationPath[0] == '/' {\n\t\toperationPath = \".\" + operationPath\n\t}\n\n\tqueryURL, err := serverURL.Parse(operationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryValues := queryURL.Query()\n\n\tif params.FieldsScmProviders != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", false, \"fields[scmProviders]\", runtime.ParamLocationQuery, *params.FieldsScmProviders); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.Limit != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", true, \"limit\", runtime.ParamLocationQuery, *params.Limit); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif params.FieldsScmRepositories != nil {\n\n\t\tif queryFrag, err := runtime.StyleParamWithLocation(\"form\", false, \"fields[scmRepositories]\", runtime.ParamLocationQuery, *params.FieldsScmRepositories); err != nil {\n\t\t\treturn nil, err\n\t\t} else if parsed, err := url.ParseQuery(queryFrag); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfor k, v := range parsed {\n\t\t\t\tfor _, v2 := range v {\n\t\t\t\t\tqueryValues.Add(k, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tqueryURL.RawQuery = queryValues.Encode()\n\n\treq, err := http.NewRequest(\"GET\", queryURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (client *ClustersClient) listCreateRequest(ctx context.Context, options *ClustersClientListOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.DBforPostgreSQL/serverGroupsv2\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-11-08\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (handler *handler) extractCreds(req *http.Request, creds *Credentials) (int, error) {\n\tif credID := req.URL.Query().Get(\"cloudCredentialId\"); credID != \"\" {\n\t\tns, name := ref.Parse(credID)\n\t\tif ns == \"\" || name == \"\" {\n\t\t\tlogrus.Debugf(\"[oci-handler] invalid cloud credential ID %s\", credID)\n\t\t\treturn httperror.InvalidBodyContent.Status, fmt.Errorf(\"invalid cloud credential ID %s\", credID)\n\t\t}\n\n\t\tapiContext := handler.generateAPIContext(req)\n\t\tif err := access.ByID(apiContext, &schema.Version, client.CloudCredentialType, credID, &client.CloudCredential{}); err != nil {\n\t\t\tif apiError, ok := err.(*httperror.APIError); ok {\n\t\t\t\tif apiError.Code.Status == httperror.PermissionDenied.Status || apiError.Code.Status == httperror.NotFound.Status {\n\t\t\t\t\t// If the user doesn't have direct access to the cloud credential, then we check if the user\n\t\t\t\t\t// has access to a cluster that uses the cloud credential.\n\t\t\t\t\tvar clusters []*prov.Cluster\n\t\t\t\t\tclusters, err = handler.provClusterCache.GetByIndex(provcluster.ByCloudCred, credID)\n\t\t\t\t\tif err != nil || len(clusters) == 0 {\n\t\t\t\t\t\treturn httperror.NotFound.Status, fmt.Errorf(\"cloud credential not found\")\n\t\t\t\t\t}\n\t\t\t\t\tfor _, cluster := range clusters {\n\t\t\t\t\t\tif err = access.ByID(apiContext, &schema.Version, client.ClusterType, cluster.Status.ClusterName, &client.Cluster{}); err == nil {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn httperror.NotFound.Status, err\n\t\t\t}\n\t\t}\n\n\t\tcc, err := handler.secretsLister.Get(namespace.GlobalNamespace, name)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"[oci-handler] error accessing cloud credential %s\", credID)\n\t\t\treturn httperror.InvalidBodyContent.Status, fmt.Errorf(\"error accessing cloud credential %s\", credID)\n\t\t}\n\n\t\tcreds.Tenancy = string(cc.Data[requiredDataFields[\"tenancyId\"]])\n\t\tcreds.User = string(cc.Data[requiredDataFields[\"userId\"]])\n\t\tcreds.FingerPrint = string(cc.Data[requiredDataFields[\"fingerprint\"]])\n\t\tcreds.PrivateKey = string(cc.Data[requiredDataFields[\"privateKeyContents\"]])\n\t\tcreds.PrivateKeyPassphrase = string(cc.Data[requiredDataFields[\"privateKeyPassphrase\"]])\n\t\tregion := req.URL.Query().Get(\"region\")\n\t\tif region != \"\" {\n\t\t\tcreds.Region = region\n\t\t}\n\t\tcompartment := req.URL.Query().Get(\"compartment\")\n\t\tif compartment != \"\" {\n\t\t\tcreds.Compartment = compartment\n\t\t}\n\t} else if req.Method == http.MethodPost {\n\t\t// Get credentials from body\n\t\traw, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"[oci-handler] cannot read request body: \" + err.Error())\n\t\t\treturn httperror.InvalidBodyContent.Status, fmt.Errorf(\"cannot read request body: \" + err.Error())\n\t\t}\n\n\t\terr = json.Unmarshal(raw, &creds)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"[oci-handler] cannot parse request body: \" + err.Error())\n\t\t\treturn httperror.InvalidBodyContent.Status, fmt.Errorf(\"cannot parse request body: \" + err.Error())\n\t\t}\n\t} else {\n\t\treturn httperror.Unauthorized.Status, fmt.Errorf(\"cannot access OCI API without credentials to authenticate\")\n\t}\n\n\treturn http.StatusOK, nil\n}", "func (instance *Host) DisableSecurityGroup(ctx context.Context, sgInstance resources.SecurityGroup) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\tif sgInstance == nil {\n\t\treturn fail.InvalidParameterError(\"sgInstance\", \"cannot be nil\")\n\t}\n\n\tsgName := sgInstance.GetName()\n\tsgID, err := sgInstance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\thid, err := instance.GetID()\n\tif err != nil {\n\t\treturn fail.ConvertError(err)\n\t}\n\n\tsvc := instance.Service()\n\txerr := instance.Alter(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Alter(hostproperty.SecurityGroupsV1, func(clonable data.Clonable) fail.Error {\n\t\t\thsgV1, ok := clonable.(*propertiesv1.HostSecurityGroups)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv1.HostSecurityGroups' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\n\t\t\tvar asg *abstract.SecurityGroup\n\t\t\txerr := sgInstance.Inspect(ctx, func(clonable data.Clonable, _ *serialize.JSONProperties) fail.Error {\n\t\t\t\tvar ok bool\n\t\t\t\tif asg, ok = clonable.(*abstract.SecurityGroup); !ok {\n\t\t\t\t\treturn fail.InconsistentError(\"'*abstract.SecurityGroup' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn xerr\n\t\t\t}\n\n\t\t\t// First check if the security group is not already registered for the Host with the exact same state\n\t\t\tvar found bool\n\t\t\tfor k := range hsgV1.ByID {\n\t\t\t\tif k == asg.ID {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn fail.NotFoundError(\"security group '%s' is not bound to Host '%s'\", sgName, sgID)\n\t\t\t}\n\n\t\t\t{\n\t\t\t\t// Bind the security group on provider side; if security group not binded, considered as a success\n\t\t\t\txerr = svc.UnbindSecurityGroupFromHost(ctx, asg, hid)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\tswitch xerr.(type) {\n\t\t\t\t\tcase *fail.ErrNotFound:\n\t\t\t\t\t\tdebug.IgnoreError2(ctx, xerr)\n\t\t\t\t\t\t// continue\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn xerr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// found, update properties\n\t\t\thsgV1.ByID[asg.ID].Disabled = true\n\t\t\treturn nil\n\t\t})\n\t})\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\treturn nil\n}", "func (o *CloudAwsVirtualMachineAllOf) GetSecurityGroupsOk() ([]CloudAwsSecurityGroupRelationship, bool) {\n\tif o == nil || o.SecurityGroups == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SecurityGroups, true\n}", "func (s *Service) CreateOrUpdateNetworkSecurityGroup(resourceGroupName string, networkSecurityGroupName string, location string) (*armada.SecurityGroupsCreateOrUpdateFuture, error) {\n\t//JEB if networkSecurityGroupName == \"\" {\n\t//JEB networkSecurityGroupName = SecurityGroupDefaultName\n\t//JEB }\n\t//JEB sshInbound := armada.SecurityRule{\n\t//JEB Name: to.StringPtr(\"ClusterAPISSH\"),\n\t//JEB SecurityRulePropertiesFormat: &armada.SecurityRulePropertiesFormat{\n\t//JEB Protocol: armada.SecurityRuleProtocolTCP,\n\t//JEB SourcePortRange: to.StringPtr(\"*\"),\n\t//JEB DestinationPortRange: to.StringPtr(\"22\"),\n\t//JEB SourceAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB DestinationAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB Priority: to.Int32Ptr(1000),\n\t//JEB Direction: armada.SecurityRuleDirectionInbound,\n\t//JEB Access: armada.SecurityRuleAccessAllow,\n\t//JEB },\n\t//JEB }\n\t//JEB\n\t//JEB kubernetesInbound := armada.SecurityRule{\n\t//JEB Name: to.StringPtr(\"KubernetesAPI\"),\n\t//JEB SecurityRulePropertiesFormat: &armada.SecurityRulePropertiesFormat{\n\t//JEB Protocol: armada.SecurityRuleProtocolTCP,\n\t//JEB SourcePortRange: to.StringPtr(\"*\"),\n\t//JEB DestinationPortRange: to.StringPtr(\"6443\"),\n\t//JEB SourceAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB DestinationAddressPrefix: to.StringPtr(\"*\"),\n\t//JEB Priority: to.Int32Ptr(1001),\n\t//JEB Direction: armada.SecurityRuleDirectionInbound,\n\t//JEB Access: armada.SecurityRuleAccessAllow,\n\t//JEB },\n\t//JEB }\n\t//JEB\n\t//JEB securityGroupProperties := armada.SecurityGroupPropertiesFormat{\n\t//JEB SecurityRules: &[]armada.SecurityRule{sshInbound, kubernetesInbound},\n\t//JEB }\n\t//JEB securityGroup := armada.SecurityGroup{\n\t//JEB Location: to.StringPtr(location),\n\t//JEB SecurityGroupPropertiesFormat: &securityGroupProperties,\n\t//JEB }\n\t//JEB sgFuture, err := s.scope.AirshipClients.SecurityGroups.CreateOrUpdate(s.scope.Context, resourceGroupName, networkSecurityGroupName, securityGroup)\n\t//JEB if err != nil {\n\t//JEB return nil, err\n\t//JEB }\n\t//JEB return &sgFuture, nil\n\treturn &armada.SecurityGroupsCreateOrUpdateFuture{}, nil\n}", "func ExampleSensitivitySettingsClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewSensitivitySettingsClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.GetSensitivitySettingsListResponse = armsecurity.GetSensitivitySettingsListResponse{\n\t// \tValue: []*armsecurity.GetSensitivitySettingsResponse{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"current\"),\n\t// \t\t\tType: to.Ptr(\"Microsoft.Security/sensitivitySettings\"),\n\t// \t\t\tID: to.Ptr(\"/providers/Microsoft.Security/sensitivitySettings\"),\n\t// \t\t\tProperties: &armsecurity.GetSensitivitySettingsResponseProperties{\n\t// \t\t\t\tMipInformation: &armsecurity.GetSensitivitySettingsResponsePropertiesMipInformation{\n\t// \t\t\t\t\tBuiltInInfoTypes: []*armsecurity.BuiltInInfoType{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"Http Authorization Header\"),\n\t// \t\t\t\t\t\t\tType: to.Ptr(\"Credentials\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"4d0d3eb6-619f-4c8c-810c-c16150c95278\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"User Login Credentials\"),\n\t// \t\t\t\t\t\t\tType: to.Ptr(\"Credentials\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"a98fde82-45b6-4b2c-afd0-ad579cd9f826\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"Credit card number\"),\n\t// \t\t\t\t\t\t\tType: to.Ptr(\"Finance\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"50842eb7-edc8-4019-85dd-5a5c1f2bb085\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"EU debit card number\"),\n\t// \t\t\t\t\t\t\tType: to.Ptr(\"Finance\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"0e9b3178-9678-47dd-a509-37222ca96b42\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tCustomInfoTypes: []*armsecurity.InfoType{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"User created custom info type 1\"),\n\t// \t\t\t\t\t\t\tDescription: to.Ptr(\"Custom info type description\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"c5f9b9a1-2b9a-4a3a-8c5b-1f3d1d9d9c9b\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"User created custom info type 2\"),\n\t// \t\t\t\t\t\t\tDescription: to.Ptr(\"Custom info type description\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"a4fee2b6-5618-404b-a5e7-aa377cd67543\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"User created custom info type 3\"),\n\t// \t\t\t\t\t\t\tDescription: to.Ptr(\"Custom info type description\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"a355f11e-f87d-4f48-8490-ecf0873325b5\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tLabels: []*armsecurity.Label{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"Public\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"fdfb5435-124d-4651-a889-a4210fec6a77\"),\n\t// \t\t\t\t\t\t\tOrder: to.Ptr[float32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"Confidential\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"4c5447ec-f7f3-4345-a160-6a5850f2bf0c\"),\n\t// \t\t\t\t\t\t\tOrder: to.Ptr[float32](1),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"Highly Confidential\"),\n\t// \t\t\t\t\t\t\tID: to.Ptr(\"f38ac75c-f42a-4c89-aa37-9c4e74101414\"),\n\t// \t\t\t\t\t\t\tOrder: to.Ptr[float32](2),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tMipIntegrationStatus: to.Ptr(armsecurity.MipIntegrationStatusOk),\n\t// \t\t\t\t},\n\t// \t\t\t\tSensitiveInfoTypesIDs: []*string{\n\t// \t\t\t\t\tto.Ptr(\"a98fde82-45b6-4b2c-afd0-ad579cd9f826\"),\n\t// \t\t\t\t\tto.Ptr(\"4d0d3eb6-619f-4c8c-810c-c16150c95278\"),\n\t// \t\t\t\t\tto.Ptr(\"0e9b3178-9678-47dd-a509-37222ca96b42\"),\n\t// \t\t\t\t\tto.Ptr(\"c5f9b9a1-2b9a-4a3a-8c5b-1f3d1d9d9c9b\")},\n\t// \t\t\t\t\tSensitivityThresholdLabelOrder: to.Ptr[float32](1),\n\t// \t\t\t\t},\n\t// \t\t}},\n\t// \t}\n}", "func (mr *MockClientMockRecorder) DescribeSecurityGroups(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DescribeSecurityGroups\", reflect.TypeOf((*MockClient)(nil).DescribeSecurityGroups), arg0)\n}" ]
[ "0.7117278", "0.6193971", "0.61442214", "0.60747856", "0.58706504", "0.58697045", "0.58517337", "0.5848987", "0.5775005", "0.57562935", "0.57172966", "0.56506014", "0.56425047", "0.56378657", "0.5628495", "0.56277186", "0.55987495", "0.5580184", "0.5566828", "0.5520823", "0.5489748", "0.5434384", "0.5357789", "0.53478986", "0.5343413", "0.53279966", "0.53181356", "0.5310584", "0.5273148", "0.5270049", "0.52532405", "0.5244692", "0.5236611", "0.52330935", "0.52068764", "0.51865155", "0.517141", "0.5113581", "0.51132804", "0.5082162", "0.503439", "0.50300616", "0.50007224", "0.4980493", "0.49717692", "0.49602878", "0.49550223", "0.49500436", "0.49466714", "0.4943906", "0.4931598", "0.49262965", "0.4919622", "0.49039978", "0.48990053", "0.48952803", "0.4888438", "0.4883247", "0.48804924", "0.48784631", "0.484861", "0.48471284", "0.48443428", "0.48443428", "0.48393613", "0.483936", "0.4831051", "0.48203322", "0.48185897", "0.48141536", "0.47884166", "0.47861287", "0.4770389", "0.47684717", "0.47637683", "0.47628474", "0.47624597", "0.47568986", "0.47362295", "0.4735351", "0.47353378", "0.47340748", "0.47284725", "0.4719292", "0.47107977", "0.4709185", "0.4706859", "0.4702592", "0.46771613", "0.46761107", "0.4661816", "0.46519127", "0.46514252", "0.4638257", "0.46327242", "0.4629175", "0.46150762", "0.46146026", "0.4613482", "0.45971465" ]
0.78652805
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroupsExecute(r ApiBrowseCloudSecurityGroupsRequest) (CloudSecurityGroupsPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue CloudSecurityGroupsPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseCloudSecurityGroups") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/cloudSecurityGroups" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.cloudNetworkId != nil { localVarQueryParams.Add("cloudNetworkId", parameterToString(*r.cloudNetworkId, "")) } if r.offset != nil { localVarQueryParams.Add("Offset", parameterToString(*r.offset, "")) } if r.limit != nil { localVarQueryParams.Add("Limit", parameterToString(*r.limit, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.7777472", "0.7582237", "0.741292", "0.7358592", "0.7292706", "0.72179556", "0.72150666", "0.7154164", "0.7144244", "0.70236844", "0.6968861", "0.69574517", "0.6857601", "0.68203115", "0.6786843", "0.67499226", "0.6732799", "0.6726702", "0.664588", "0.66373837", "0.66341907", "0.66192603", "0.6618354", "0.65951604", "0.6592189", "0.6544029", "0.65052474", "0.6500035", "0.6499713", "0.6493198", "0.6459492", "0.64537424", "0.64339274", "0.64231", "0.6411837", "0.6354237", "0.6342012", "0.6331562", "0.63293886", "0.63235724", "0.63210624", "0.63129383", "0.63012326", "0.62950426", "0.62711006", "0.6269801", "0.62694305", "0.62559414", "0.62376016", "0.61896044", "0.61866677", "0.6157971", "0.61576515", "0.6157038", "0.61556566", "0.6138981", "0.61365765", "0.61309266", "0.61302364", "0.61298376", "0.6119938", "0.61105776", "0.6102657", "0.6093387", "0.609142", "0.6079346", "0.6078881", "0.6075695", "0.6045966", "0.6045463", "0.60427797", "0.6032737", "0.603158", "0.6027389", "0.60167104", "0.60026646", "0.5987349", "0.5974702", "0.5971437", "0.59703684", "0.5965762", "0.59478134", "0.5939073", "0.59338975", "0.59321105", "0.5925759", "0.5913415", "0.59012485", "0.58960927", "0.5890233", "0.5883923", "0.58764994", "0.5875759", "0.58713603", "0.58534265", "0.5852063", "0.5849181", "0.58465594", "0.5846279", "0.58363706", "0.58326805" ]
0.0
-1
/ BrowseCloudSubnetworks Method for BrowseCloudSubnetworks
func (a *AmazonConnectionsApiService) BrowseCloudSubnetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSubnetworksRequest { return ApiBrowseCloudSubnetworksRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseCloudSubnetworksExecute(r ApiBrowseCloudSubnetworksRequest) (CloudSubnetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSubnetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSubnetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSubnetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.availabilityZone != nil {\n\t\tlocalVarQueryParams.Add(\"availabilityZone\", parameterToString(*r.availabilityZone, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c *TestClient) ListSubnetworks(project, region string, opts ...ListCallOption) ([]*compute.Subnetwork, error) {\n\tif c.ListSubnetworksFn != nil {\n\t\treturn c.ListSubnetworksFn(project, region, opts...)\n\t}\n\treturn c.client.ListSubnetworks(project, region, opts...)\n}", "func (o ServiceConnectionPolicyPscConfigOutput) Subnetworks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceConnectionPolicyPscConfig) []string { return v.Subnetworks }).(pulumi.StringArrayOutput)\n}", "func (a *AmazonConnectionsApiService) BrowseCloudNetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudNetworksRequest {\n\treturn ApiBrowseCloudNetworksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (o ServiceConnectionPolicyPscConfigPtrOutput) Subnetworks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ServiceConnectionPolicyPscConfig) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Subnetworks\n\t}).(pulumi.StringArrayOutput)\n}", "func (o NetworkAttachmentOutput) Subnetworks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *NetworkAttachment) pulumi.StringArrayOutput { return v.Subnetworks }).(pulumi.StringArrayOutput)\n}", "func (a *AmazonConnectionsApiService) BrowseCloudNetworksExecute(r ApiBrowseCloudNetworksRequest) (CloudNetworksPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudNetworksPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudNetworks\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudNetworks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (s *Stack) ListNetworks() ([]*abstract.Network, fail.Error) {\n\tvar networks []*abstract.Network\n\n\tcompuService := s.ComputeService\n\n\ttoken := \"\"\n\tfor paginate := true; paginate; {\n\t\tresp, err := compuService.Networks.List(s.GcpConfig.ProjectID).PageToken(token).Do()\n\t\tif err != nil {\n\t\t\treturn networks, fail.Errorf(fmt.Sprintf(\"cannot list networks ...: %s\", err), err)\n\t\t}\n\n\t\tfor _, nett := range resp.Items {\n\t\t\tnewNet := abstract.NewNetwork()\n\t\t\tnewNet.Name = nett.Name\n\t\t\tnewNet.ID = strconv.FormatUint(nett.Id, 10)\n\t\t\tnewNet.CIDR = nett.IPv4Range\n\n\t\t\tnetworks = append(networks, newNet)\n\t\t}\n\t\ttoken := resp.NextPageToken\n\t\tpaginate = token != \"\"\n\t}\n\n\ttoken = \"\"\n\tfor paginate := true; paginate; {\n\t\tresp, err := compuService.Subnetworks.List(s.GcpConfig.ProjectID, s.GcpConfig.Region).PageToken(token).Do()\n\t\tif err != nil {\n\t\t\treturn networks, fail.Errorf(fmt.Sprintf(\"cannot list subnetworks ...: %s\", err), err)\n\t\t}\n\n\t\tfor _, nett := range resp.Items {\n\t\t\tnewNet := abstract.NewNetwork()\n\t\t\tnewNet.Name = nett.Name\n\t\t\tnewNet.ID = strconv.FormatUint(nett.Id, 10)\n\t\t\tnewNet.CIDR = nett.IpCidrRange\n\n\t\t\tnetworks = append(networks, newNet)\n\t\t}\n\t\ttoken := resp.NextPageToken\n\t\tpaginate = token != \"\"\n\t}\n\n\treturn networks, nil\n}", "func (de *DockerEngine) getSubNet() (string, error) {\n\tde.subNetMu.Lock()\n\tdefer de.subNetMu.Unlock()\n\n\taddrs, err := net.InterfaceAddrs()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Error getting network addresses\")\n\t}\n\n\tvar nets []*net.IPNet\n\n\tfor _, addr := range addrs {\n\t\tdockerLog.Debugf(\"Inspecting interface %s\", addr.String())\n\n\t\t_, n, err := net.ParseCIDR(addr.String())\n\n\t\tif err != nil {\n\t\t\tdockerLog.Warningf(\"Error parsing address: %s\", addr.String())\n\n\t\t\tcontinue\n\t\t}\n\n\t\tnets = append(nets, n)\n\t}\n\n\tnetaddr := func() string {\n\t\ttpl := \"10.%d.%d.0/24\"\n\n\t\treturn fmt.Sprintf(tpl, de.subNetOct1, de.subNetOct2)\n\t}\n\n\t_, pnet, _ := net.ParseCIDR(netaddr())\n\n\tfor {\n\t\t// Find non-overlapping network\n\t\toverlap := false\n\n\t\tfor _, n := range nets {\n\t\t\tif lib.NetsOverlap(pnet, n) {\n\t\t\t\toverlap = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif overlap {\n\t\t\tde.subNetOct2 += 1\n\n\t\t\tif de.subNetOct2 > 255 {\n\t\t\t\tde.subNetOct1 += 1\n\t\t\t\tde.subNetOct2 = 0\n\t\t\t}\n\n\t\t\t_, pnet, _ = net.ParseCIDR(netaddr())\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn netaddr(), nil\n}", "func (o PacketMirroringMirroredResourceInfoResponsePtrOutput) Subnetworks() PacketMirroringMirroredResourceInfoSubnetInfoResponseArrayOutput {\n\treturn o.ApplyT(func(v *PacketMirroringMirroredResourceInfoResponse) []PacketMirroringMirroredResourceInfoSubnetInfoResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Subnetworks\n\t}).(PacketMirroringMirroredResourceInfoSubnetInfoResponseArrayOutput)\n}", "func (c *TestClient) AggregatedListSubnetworks(project string, opts ...ListCallOption) ([]*compute.Subnetwork, error) {\n\tif c.AggregatedListSubnetworksFn != nil {\n\t\treturn c.AggregatedListSubnetworksFn(project, opts...)\n\t}\n\treturn c.client.AggregatedListSubnetworks(project, opts...)\n}", "func (o AccessLevelsAccessLevelBasicConditionOutput) IpSubnetworks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelsAccessLevelBasicCondition) []string { return v.IpSubnetworks }).(pulumi.StringArrayOutput)\n}", "func (o PacketMirroringMirroredResourceInfoPtrOutput) Subnetworks() PacketMirroringMirroredResourceInfoSubnetInfoArrayOutput {\n\treturn o.ApplyT(func(v *PacketMirroringMirroredResourceInfo) []PacketMirroringMirroredResourceInfoSubnetInfo {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Subnetworks\n\t}).(PacketMirroringMirroredResourceInfoSubnetInfoArrayOutput)\n}", "func (o AccessLevelBasicConditionOutput) IpSubnetworks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AccessLevelBasicCondition) []string { return v.IpSubnetworks }).(pulumi.StringArrayOutput)\n}", "func (o RegionNetworkEndpointGroupOutput) Subnetwork() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RegionNetworkEndpointGroup) pulumi.StringPtrOutput { return v.Subnetwork }).(pulumi.StringPtrOutput)\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Subnetwork() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) string { return v.Subnetwork }).(pulumi.StringOutput)\n}", "func (o PacketMirroringMirroredResourceInfoResponseOutput) Subnetworks() PacketMirroringMirroredResourceInfoSubnetInfoResponseArrayOutput {\n\treturn o.ApplyT(func(v PacketMirroringMirroredResourceInfoResponse) []PacketMirroringMirroredResourceInfoSubnetInfoResponse {\n\t\treturn v.Subnetworks\n\t}).(PacketMirroringMirroredResourceInfoSubnetInfoResponseArrayOutput)\n}", "func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroups(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudSecurityGroupsRequest {\n\treturn ApiBrowseCloudSecurityGroupsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (o RouterNatOutput) Subnetworks() RouterNatSubnetworkToNatArrayOutput {\n\treturn o.ApplyT(func(v RouterNat) []RouterNatSubnetworkToNat { return v.Subnetworks }).(RouterNatSubnetworkToNatArrayOutput)\n}", "func main() {\n opts := gophercloud.AuthOptions{\n\t\tIdentityEndpoint: \"http://10.169.41.188/identity\",\n\t\tUsername: \"admin\",\n\t\tPassword: \"password\",\n\t\tTenantID: \"01821bd38f2f474489491adb0da7efaf\",\n\t\tDomainID: \"default\",\n\t}\n\tprovider, err := openstack.AuthenticatedClient(opts)\n\tfmt.Println(err)\n\tif err != nil {\n\t\tfmt.Errorf(\"Sending get container group request failed: %v\", err)\n\t\treturn\n\t}\n client, err := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{\n\t\tRegion: \"RegionOne\",\n\t})\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to create a network client: %v\", err)\n\t}\n\tallPages, err := subnets.List(client, nil).AllPages()\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to list subnets: %v\", err)\n\t}\n\n\tallSubnets, err := subnets.ExtractSubnets(allPages)\n\tif err != nil {\n\t\tfmt.Errorf(\"Unable to extract subnets: %v\", err)\n\t}\n\n\tfor _, subnet := range allSubnets {\n\t b, _ := json.MarshalIndent(subnet, \"\", \" \")\n fmt.Printf(\"%s\", string(b))\n }\n\n}", "func (o RouterNatResponseOutput) Subnetworks() RouterNatSubnetworkToNatResponseArrayOutput {\n\treturn o.ApplyT(func(v RouterNatResponse) []RouterNatSubnetworkToNatResponse { return v.Subnetworks }).(RouterNatSubnetworkToNatResponseArrayOutput)\n}", "func (o NetworkInterfaceOutput) Subnetwork() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NetworkInterface) *string { return v.Subnetwork }).(pulumi.StringPtrOutput)\n}", "func (o PacketMirroringMirroredResourceInfoOutput) Subnetworks() PacketMirroringMirroredResourceInfoSubnetInfoArrayOutput {\n\treturn o.ApplyT(func(v PacketMirroringMirroredResourceInfo) []PacketMirroringMirroredResourceInfoSubnetInfo {\n\t\treturn v.Subnetworks\n\t}).(PacketMirroringMirroredResourceInfoSubnetInfoArrayOutput)\n}", "func (s *ClusterScope) Subnets() infrav1.Subnets {\n\treturn s.AzureCluster.Spec.NetworkSpec.Subnets\n}", "func Subnets(prefix cty.Value, newbits ...cty.Value) (cty.Value, error) {\n\targs := make([]cty.Value, len(newbits)+1)\n\targs[0] = prefix\n\tcopy(args[1:], newbits)\n\treturn SubnetsFunc.Call(args)\n}", "func (o RouterInterfaceOutput) Subnetwork() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterInterface) *string { return v.Subnetwork }).(pulumi.StringPtrOutput)\n}", "func (o NetworkInterfaceResponseOutput) Subnetwork() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NetworkInterfaceResponse) string { return v.Subnetwork }).(pulumi.StringOutput)\n}", "func (o RouterInterfaceResponseOutput) Subnetwork() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterInterfaceResponse) string { return v.Subnetwork }).(pulumi.StringOutput)\n}", "func (o LookupVirtualNetworkResultOutput) Subnets() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupVirtualNetworkResult) []string { return v.Subnets }).(pulumi.StringArrayOutput)\n}", "func (client Client) Subnets() network.SubnetsClient {\n\tif client.subnets == nil {\n\t\tclnt := network.NewSubnetsClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.subnets = &clnt\t\t\n\t}\t\n\treturn *client.subnets\n}", "func (o LookupWorkstationClusterResultOutput) Subnetwork() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupWorkstationClusterResult) string { return v.Subnetwork }).(pulumi.StringOutput)\n}", "func (c *TestClient) GetSubnetwork(project, region, name string) (*compute.Subnetwork, error) {\n\tif c.GetSubnetworkFn != nil {\n\t\treturn c.GetSubnetworkFn(project, region, name)\n\t}\n\treturn c.client.GetSubnetwork(project, region, name)\n}", "func (instance *Network) Browse(ctx context.Context, callback func(*abstract.Network) fail.Error) (xerr fail.Error) {\n\tdefer fail.OnPanic(&xerr)\n\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\ttask, xerr := concurrency.TaskFromContext(ctx)\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn xerr\n\t}\n\n\tif task.Aborted() {\n\t\treturn fail.AbortedError(nil, \"aborted\")\n\t}\n\n\tinstance.lock.RLock()\n\tdefer instance.lock.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(func(buf []byte) fail.Error {\n\t\tif task.Aborted() {\n\t\t\treturn fail.AbortedError(nil, \"aborted\")\n\t\t}\n\n\t\tan := abstract.NewNetwork()\n\t\txerr := an.Deserialize(buf)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn xerr\n\t\t}\n\n\t\treturn callback(an)\n\t})\n}", "func (o *AggregatedDomain) Subnets(info *bambou.FetchingInfo) (SubnetsList, *bambou.Error) {\n\n\tvar list SubnetsList\n\terr := bambou.CurrentSession().FetchChildren(o, SubnetIdentity, &list, info)\n\treturn list, err\n}", "func (c *Client) PrivateNetworks() (string, error) {\n\treturn c.get(\"/private-networks\")\n}", "func (s *SubnetworkServer) ListComputeSubnetwork(ctx context.Context, request *computepb.ListComputeSubnetworkRequest) (*computepb.ListComputeSubnetworkResponse, error) {\n\tcl, err := createConfigSubnetwork(ctx, request.GetServiceAccountFile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := cl.ListSubnetwork(ctx, request.GetProject(), request.GetRegion())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar protos []*computepb.ComputeSubnetwork\n\tfor _, r := range resources.Items {\n\t\trp := SubnetworkToProto(r)\n\t\tprotos = append(protos, rp)\n\t}\n\tp := &computepb.ListComputeSubnetworkResponse{}\n\tp.SetItems(protos)\n\treturn p, nil\n}", "func (r Virtual_Guest_Network_Component) GetSubnets() (resp []datatypes.Network_Subnet, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Network_Component\", \"getSubnets\", nil, &r.Options, &resp)\n\treturn\n}", "func (o ClusterOutput) Subnetwork() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.Subnetwork }).(pulumi.StringOutput)\n}", "func List(ctx context.Context, svc iaas.Service, networkID string, all bool, terraform bool) ([]*abstract.Subnet, fail.Error) {\n\tif !terraform {\n\t\treturn operations.ListSubnets(ctx, svc, networkID, all)\n\t}\n\n\tvar neptune []*abstract.Subnet\n\traw, err := operations.ListTerraformSubnets(ctx, svc, networkID, \"\", terraform)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, val := range raw { // FIXME: Another mapping problem\n\t\tns := abstract.NewSubnet()\n\t\tns.ID = val.Identity\n\t\tns.Name = val.Name\n\t\tneptune = append(neptune, ns)\n\t}\n\n\treturn neptune, nil\n}", "func (esr *etcdSubnetRegistry) getNetworks(ctx context.Context) ([]string, uint64, error) {\n\tresp, err := esr.client().Get(ctx, esr.etcdCfg.Prefix, &etcd.GetOptions{Recursive: true})\n\n\tnetworks := []string{}\n\n\tif err == nil {\n\t\tfor _, node := range resp.Node.Nodes {\n\t\t\t// Look for '/config' on the child nodes\n\t\t\tfor _, child := range node.Nodes {\n\t\t\t\tnetname, isConfig := esr.parseNetworkKey(child.Key)\n\t\t\t\tif isConfig {\n\t\t\t\t\tnetworks = append(networks, netname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn networks, resp.Index, nil\n\t}\n\n\tif etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeKeyNotFound {\n\t\t// key not found: treat it as empty set\n\t\treturn networks, etcdErr.Index, nil\n\t}\n\n\treturn nil, 0, err\n}", "func DeleteVirtualNetworkSubnet() {}", "func DeleteVirtualNetworkSubnet() {}", "func (a *AmazonConnectionsApiService) BrowseCloudSecurityGroupsExecute(r ApiBrowseCloudSecurityGroupsRequest) (CloudSecurityGroupsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSecurityGroupsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseCloudSecurityGroups\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudSecurityGroups\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.cloudNetworkId != nil {\n\t\tlocalVarQueryParams.Add(\"cloudNetworkId\", parameterToString(*r.cloudNetworkId, \"\"))\n\t}\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Subnets(supernet *net.IPNet, prefix int) []*net.IPNet {\n\tones, bits := supernet.Mask.Size()\n\tif ones > prefix || bits < prefix {\n\t\treturn nil\n\t}\n\n\tip := supernet.IP\n\tmask := net.CIDRMask(prefix, bits)\n\tsize, _ := uint128.Pow2(uint(bits - prefix))\n\n\tsubnets := make([]*net.IPNet, 1<<uint(prefix-ones))\n\tfor i := 0; i < len(subnets); i++ {\n\t\tif i > 0 {\n\t\t\tlast, _ := uint128.NewFromBytes(subnets[i-1].IP)\n\t\t\tbuf := last.Add(size).Bytes()\n\n\t\t\t// Uint128 always returns a 16-byte slice. We only need the last\n\t\t\t// 4 bytes for IPv4 addresses.\n\t\t\tip = buf[16-len(ip):]\n\t\t}\n\n\t\tsubnets[i] = &net.IPNet{\n\t\t\tIP: ip,\n\t\t\tMask: mask,\n\t\t}\n\t}\n\n\treturn subnets\n}", "func (a SubAccountClient) GetSubAccounts(req *rest3.RequestForSubAccounts) (rest3.ResponseForSubAccounts, error) {\n\tpanic(\"implement me\")\n}", "func (subnet *VirtualNetworksSubnet) Hub() {}", "func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {\n\tvar v4Subnets []net.IPNet\n\tvar v6Subnets []net.IPNet\n\n\tfor _, managedNetwork := range daemon.netController.Networks() {\n\t\tv4infos, v6infos := managedNetwork.IpamInfo()\n\t\tfor _, info := range v4infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv4Subnets = append(v4Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t\tfor _, info := range v6infos {\n\t\t\tif info.IPAMData.Pool != nil {\n\t\t\t\tv6Subnets = append(v6Subnets, *info.IPAMData.Pool)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn v4Subnets, v6Subnets\n}", "func (s *ClusterScope) Subnet(name string) infrav1.SubnetSpec {\n\tfor _, sn := range s.AzureCluster.Spec.NetworkSpec.Subnets {\n\t\tif sn.Name == name {\n\t\t\treturn sn\n\t\t}\n\t}\n\n\treturn infrav1.SubnetSpec{}\n}", "func (s *SubnetworkServer) applySubnetwork(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeSubnetworkRequest) (*computepb.ComputeSubnetwork, error) {\n\tp := ProtoToSubnetwork(request.GetResource())\n\tres, err := c.ApplySubnetwork(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := SubnetworkToProto(res)\n\treturn r, nil\n}", "func GetMultiNetworks(nad []string, ns string, podName string) *corev1.Pod {\n\tpod := GetPodDefinition(ns, podName)\n\tpod.Annotations = map[string]string{\"k8s.v1.cni.cncf.io/networks\": strings.Join(nad, \",\")}\n\treturn pod\n}", "func getNetworkNames(\n\tinfraStatus *apisgcp.InfrastructureStatus,\n\tcp *extensionsv1alpha1.ControlPlane,\n) (string, string) {\n\tnetworkName := infraStatus.Networks.VPC.Name\n\tif networkName == \"\" {\n\t\tnetworkName = cp.Namespace\n\t}\n\n\tsubNetworkName := \"\"\n\tsubnet, _ := apihelper.FindSubnetForPurpose(infraStatus.Networks.Subnets, apisgcp.PurposeInternal)\n\tif subnet != nil {\n\t\tsubNetworkName = subnet.Name\n\t}\n\n\treturn networkName, subNetworkName\n}", "func (c *MockAzureCloud) Subnet() azure.SubnetsClient {\n\treturn c.SubnetsClient\n}", "func GetSubkind(n *scpb.Node) string {\n\tif k := n.GetGenericSubkind(); k != \"\" {\n\t\treturn k\n\t}\n\treturn SubkindString(n.GetKytheSubkind())\n}", "func ProtoToSubnetwork(p *computepb.ComputeSubnetwork) *compute.Subnetwork {\n\tobj := &compute.Subnetwork{\n\t\tCreationTimestamp: dcl.StringOrNil(p.GetCreationTimestamp()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tGatewayAddress: dcl.StringOrNil(p.GetGatewayAddress()),\n\t\tIPCidrRange: dcl.StringOrNil(p.GetIpCidrRange()),\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tNetwork: dcl.StringOrNil(p.GetNetwork()),\n\t\tFingerprint: dcl.StringOrNil(p.GetFingerprint()),\n\t\tPurpose: ProtoToComputeSubnetworkPurposeEnum(p.GetPurpose()),\n\t\tRole: ProtoToComputeSubnetworkRoleEnum(p.GetRole()),\n\t\tPrivateIPGoogleAccess: dcl.Bool(p.GetPrivateIpGoogleAccess()),\n\t\tRegion: dcl.StringOrNil(p.GetRegion()),\n\t\tLogConfig: ProtoToComputeSubnetworkLogConfig(p.GetLogConfig()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tSelfLink: dcl.StringOrNil(p.GetSelfLink()),\n\t\tEnableFlowLogs: dcl.Bool(p.GetEnableFlowLogs()),\n\t}\n\tfor _, r := range p.GetSecondaryIpRanges() {\n\t\tobj.SecondaryIPRanges = append(obj.SecondaryIPRanges, *ProtoToComputeSubnetworkSecondaryIPRanges(r))\n\t}\n\treturn obj\n}", "func (s *Stack) DeleteNetwork(ref string) (err error) {\n\ttheNetwork, err := s.GetNetwork(ref)\n\tif err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tif gerr.Code != 404 {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif theNetwork == nil {\n\t\treturn fail.Errorf(\n\t\t\tfmt.Sprintf(\"delete network failed: unexpected nil network when looking for [%s]\", ref), err,\n\t\t)\n\t}\n\n\tif !theNetwork.OK() {\n\t\tlogrus.Warnf(\"Missing data in network: %s\", spew.Sdump(theNetwork))\n\t}\n\n\tcompuService := s.ComputeService\n\tsubnetwork, err := compuService.Subnetworks.Get(s.GcpConfig.ProjectID, s.GcpConfig.Region, theNetwork.Name).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topp, err := compuService.Subnetworks.Delete(s.GcpConfig.ProjectID, s.GcpConfig.Region, subnetwork.Name).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toco := OpContext{\n\t\tOperation: opp,\n\t\tProjectID: s.GcpConfig.ProjectID,\n\t\tService: compuService,\n\t\tDesiredState: \"DONE\",\n\t}\n\n\terr = waitUntilOperationIsSuccessfulOrTimeout(oco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout())\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase fail.ErrTimeout:\n\t\t\tlogrus.Warnf(\"Timeout waiting for subnetwork deletion\")\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Delete routes and firewall\n\tfirewallRuleName := fmt.Sprintf(\"%s-%s-all-in\", s.GcpConfig.NetworkName, subnetwork.Name)\n\tfws, err := compuService.Firewalls.Get(s.GcpConfig.ProjectID, firewallRuleName).Do()\n\tif fws != nil && err == nil {\n\t\topp, operr := compuService.Firewalls.Delete(s.GcpConfig.ProjectID, firewallRuleName).Do()\n\t\tif operr == nil {\n\t\t\toco := OpContext{\n\t\t\t\tOperation: opp,\n\t\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\t\tService: compuService,\n\t\t\t\tDesiredState: \"DONE\",\n\t\t\t}\n\n\t\t\toperr = waitUntilOperationIsSuccessfulOrTimeout(\n\t\t\t\toco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout(),\n\t\t\t)\n\t\t\tif operr != nil {\n\t\t\t\tlogrus.Warn(operr)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tlogrus.Warn(err)\n\t}\n\n\tnatRuleName := fmt.Sprintf(\"%s-%s-nat-allowed\", s.GcpConfig.NetworkName, subnetwork.Name)\n\tnws, err := compuService.Routes.Get(s.GcpConfig.ProjectID, natRuleName).Do()\n\tif nws != nil && err == nil {\n\t\topp, operr := compuService.Routes.Delete(s.GcpConfig.ProjectID, natRuleName).Do()\n\t\tif operr == nil {\n\t\t\toco := OpContext{\n\t\t\t\tOperation: opp,\n\t\t\t\tProjectID: s.GcpConfig.ProjectID,\n\t\t\t\tService: compuService,\n\t\t\t\tDesiredState: \"DONE\",\n\t\t\t}\n\n\t\t\toperr = waitUntilOperationIsSuccessfulOrTimeout(\n\t\t\t\toco, temporal.GetMinDelay(), temporal.GetHostCleanupTimeout(),\n\t\t\t)\n\t\t\tif operr != nil {\n\t\t\t\tlogrus.Warn(operr)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tlogrus.Warn(err)\n\t}\n\n\treturn nil\n}", "func TestGetServerNetworks(t *testing.T) {\n\trecord(t, \"getservernetworks\", func(t *testing.T, svc *Service) {\n\t\tserverDetails, err := createServer(svc, \"TestGetServerNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworking, err := svc.GetServerNetworks(&request.GetServerNetworksRequest{\n\t\t\tServerUUID: serverDetails.UUID,\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tsdNetworking := upcloud.Networking(serverDetails.Networking)\n\t\tassert.Equal(t, &sdNetworking, networking)\n\t})\n}", "func (c *Client) GetAllNetworks() ([]byte, error) {\n\treturn c.doGet(master.GetNetworksRESTEndpoint)\n}", "func (mavenlinkService *MavenlinkService) RetrieveSubTasksInWorkspace(keyOrId int32, taskKeyOrId int32,\n\ttasks chan []communicator.Task) {\n\n\tvar subTasksResponse *communicator.Response\n\tvar taskListRequest communicator.Request\n\tvar subTasks []communicator.Task\n\ttaskListRequest.Workspace = fmt.Sprint(keyOrId)\n\ttaskListRequest.Task = fmt.Sprint(taskKeyOrId)\n\tsubTasksResponse, err := utility.GetUtilitiesSingleton().MavenlinkClient.GetSubTasksByParentTaskAndProjectId(\n\t\tutility.GetUtilitiesSingleton().CommsContext, &taskListRequest)\n\tif err == nil && subTasksResponse.Error == nil &&\n\t\tsubTasksResponse != nil &&\n\t\tsubTasksResponse.Tasks != nil {\n\t\tfor _, subTask := range subTasksResponse.Tasks {\n\t\t\tsubTasks = append(subTasks, *subTask)\n\t\t}\n\t}\n\ttasks <- subTasks\n}", "func SubnetworkToProto(resource *compute.Subnetwork) *computepb.ComputeSubnetwork {\n\tp := &computepb.ComputeSubnetwork{}\n\tp.SetCreationTimestamp(dcl.ValueOrEmptyString(resource.CreationTimestamp))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetGatewayAddress(dcl.ValueOrEmptyString(resource.GatewayAddress))\n\tp.SetIpCidrRange(dcl.ValueOrEmptyString(resource.IPCidrRange))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetNetwork(dcl.ValueOrEmptyString(resource.Network))\n\tp.SetFingerprint(dcl.ValueOrEmptyString(resource.Fingerprint))\n\tp.SetPurpose(ComputeSubnetworkPurposeEnumToProto(resource.Purpose))\n\tp.SetRole(ComputeSubnetworkRoleEnumToProto(resource.Role))\n\tp.SetPrivateIpGoogleAccess(dcl.ValueOrEmptyBool(resource.PrivateIPGoogleAccess))\n\tp.SetRegion(dcl.ValueOrEmptyString(resource.Region))\n\tp.SetLogConfig(ComputeSubnetworkLogConfigToProto(resource.LogConfig))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink))\n\tp.SetEnableFlowLogs(dcl.ValueOrEmptyBool(resource.EnableFlowLogs))\n\tsSecondaryIPRanges := make([]*computepb.ComputeSubnetworkSecondaryIPRanges, len(resource.SecondaryIPRanges))\n\tfor i, r := range resource.SecondaryIPRanges {\n\t\tsSecondaryIPRanges[i] = ComputeSubnetworkSecondaryIPRangesToProto(&r)\n\t}\n\tp.SetSecondaryIpRanges(sSecondaryIPRanges)\n\n\treturn p\n}", "func (client Client) VirtualNetworks() network.VirtualNetworksClient {\n\tif client.networks == nil {\n\t\tclnt := network.NewVirtualNetworksClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.networks = &clnt\t\t\n\t}\t\n\treturn *client.networks\n}", "func (c *Client) CloudInfoNetworkPrivate(projectID string) ([]types.CloudNetwork, error) {\n\tnetwork := []types.CloudNetwork{}\n\terr := c.Get(queryEscape(\"/cloud/project/%s/network/private\", projectID), &network)\n\treturn network, err\n}", "func (m *MachineScope) Subnet() infrav1.SubnetSpec {\n\tfor _, subnet := range m.Subnets() {\n\t\tif subnet.Name == m.AzureMachine.Spec.NetworkInterfaces[0].SubnetName {\n\t\t\treturn subnet\n\t\t}\n\t}\n\n\treturn infrav1.SubnetSpec{}\n}", "func (*ListNetworkSubnetsResponse) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{10}\n}", "func (s *ClusterScope) SubnetSpecs() []azure.ResourceSpecGetter {\n\tnumberOfSubnets := len(s.AzureCluster.Spec.NetworkSpec.Subnets)\n\tif s.IsAzureBastionEnabled() {\n\t\tnumberOfSubnets++\n\t}\n\n\tsubnetSpecs := make([]azure.ResourceSpecGetter, 0, numberOfSubnets)\n\n\tfor _, subnet := range s.AzureCluster.Spec.NetworkSpec.Subnets {\n\t\tsubnetSpec := &subnets.SubnetSpec{\n\t\t\tName: subnet.Name,\n\t\t\tResourceGroup: s.ResourceGroup(),\n\t\t\tSubscriptionID: s.SubscriptionID(),\n\t\t\tCIDRs: subnet.CIDRBlocks,\n\t\t\tVNetName: s.Vnet().Name,\n\t\t\tVNetResourceGroup: s.Vnet().ResourceGroup,\n\t\t\tIsVNetManaged: s.IsVnetManaged(),\n\t\t\tRouteTableName: subnet.RouteTable.Name,\n\t\t\tSecurityGroupName: subnet.SecurityGroup.Name,\n\t\t\tRole: subnet.Role,\n\t\t\tNatGatewayName: subnet.NatGateway.Name,\n\t\t\tServiceEndpoints: subnet.ServiceEndpoints,\n\t\t}\n\t\tsubnetSpecs = append(subnetSpecs, subnetSpec)\n\t}\n\n\tif s.IsAzureBastionEnabled() {\n\t\tazureBastionSubnet := s.AzureCluster.Spec.BastionSpec.AzureBastion.Subnet\n\t\tsubnetSpecs = append(subnetSpecs, &subnets.SubnetSpec{\n\t\t\tName: azureBastionSubnet.Name,\n\t\t\tResourceGroup: s.ResourceGroup(),\n\t\t\tSubscriptionID: s.SubscriptionID(),\n\t\t\tCIDRs: azureBastionSubnet.CIDRBlocks,\n\t\t\tVNetName: s.Vnet().Name,\n\t\t\tVNetResourceGroup: s.Vnet().ResourceGroup,\n\t\t\tIsVNetManaged: s.IsVnetManaged(),\n\t\t\tSecurityGroupName: azureBastionSubnet.SecurityGroup.Name,\n\t\t\tRouteTableName: azureBastionSubnet.RouteTable.Name,\n\t\t\tRole: azureBastionSubnet.Role,\n\t\t\tServiceEndpoints: azureBastionSubnet.ServiceEndpoints,\n\t\t})\n\t}\n\n\treturn subnetSpecs\n}", "func networkListExample() string {\n\treturn `$ pouch network ls\nNETWORK ID NAME DRIVER SCOPE\n6f7aba8a58 net2 bridge\n55f134176c net3 bridge\ne495f50913 net1 bridge\n`\n}", "func (instance *Host) Browse(ctx context.Context, callback func(*abstract.HostCore) fail.Error) (ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif instance == nil {\n\t\treturn fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\tif callback == nil {\n\t\treturn fail.InvalidParameterCannotBeNilError(\"callback\")\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\treturn instance.MetadataCore.BrowseFolder(ctx, func(buf []byte) (innerXErr fail.Error) {\n\t\tahc := abstract.NewHostCore()\n\t\tvar inErr fail.Error\n\t\tif inErr = ahc.Deserialize(buf); inErr != nil {\n\t\t\treturn inErr\n\t\t}\n\n\t\treturn callback(ahc)\n\t})\n}", "func (a *AmazonConnectionsApiService) BrowseAvailabilityZones(ctx _context.Context, amazonConnectionId string) ApiBrowseAvailabilityZonesRequest {\n\treturn ApiBrowseAvailabilityZonesRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func TestAccComputeSubnetworkIamPolicy(t *testing.T) {\n\tt.Parallel()\n\n\tproject := envvar.GetTestProjectFromEnv()\n\taccount := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt(t))\n\trole := \"roles/compute.networkUser\"\n\tregion := envvar.GetTestRegionFromEnv()\n\tsubnetwork := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(t, 10))\n\n\tacctest.VcrTest(t, resource.TestCase{\n\t\tPreCheck: func() { acctest.AccTestPreCheck(t) },\n\t\tProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccComputeSubnetworkIamPolicy_basic(account, region, subnetwork, role),\n\t\t\t},\n\t\t\t// Test a few import formats\n\t\t\t{\n\t\t\t\tResourceName: \"google_compute_subnetwork_iam_policy.foo\",\n\t\t\t\tImportStateId: fmt.Sprintf(\"projects/%s/regions/%s/subnetworks/%s\", project, region, subnetwork),\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: \"google_compute_subnetwork_iam_policy.foo\",\n\t\t\t\tImportStateId: fmt.Sprintf(\"%s/%s/%s\", project, region, subnetwork),\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: \"google_compute_subnetwork_iam_policy.foo\",\n\t\t\t\tImportStateId: fmt.Sprintf(\"%s/%s\", region, subnetwork),\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName: \"google_compute_subnetwork_iam_policy.foo\",\n\t\t\t\tImportStateId: subnetwork,\n\t\t\t\tImportState: true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}", "func SubServices(c *fiber.Ctx) {\n\tServiceID := c.Params(\"service_id\")\n\n\tvar SubServiceFromSQL SubServiceSQL\n\tvar SubServicePointer []SubServiceSQL\n\tvar Pointer SubServiceSQLPointer\n\tPointers := []SubServiceSQLPointer{}\n\n\tSubServicesSQL, ErrorSubservices := sq.Select(\n\t\t\"sub_service_type_id\",\n\t\t\"sub_service_name\",\n\t).\n\t\tFrom(\"sub_service_type\").\n\t\tWhere(\"service_type_id = ?\", ServiceID).\n\t\tRunWith(database).\n\t\tQuery()\n\n\tif ErrorSubservices != nil {\n\t\tfmt.Println(ErrorSubservices, \"Error get sub services\")\n\t\tc.JSON(ErrorResponse{MESSAGE: \"Problem with get sub services\"})\n\t\tc.SendStatus(400)\n\t\treturn\n\t}\n\n\tfor SubServicesSQL.Next() {\n\t\t_ = SubServicesSQL.Scan(\n\t\t\t&SubServiceFromSQL.SubServiceTypeID,\n\t\t\t&SubServiceFromSQL.SubServiceName,\n\t\t)\n\n\t\tSubServicePointer = append(SubServicePointer, SubServiceFromSQL)\n\t}\n\n\tfor i := 0; i < len(SubServicePointer); i++ {\n\t\tPointer.SubServiceTypeID = &SubServicePointer[i].SubServiceTypeID.String\n\t\tPointer.SubServiceName = &SubServicePointer[i].SubServiceName.String\n\n\t\tPointers = append(Pointers, Pointer)\n\t}\n\n\tresponse := SubServiceResponse{SubService: Pointers}\n\n\tc.JSON(response)\n}", "func ListSubnets(subnetsToQuery []string, site []string) (subnets []*ToScan) {\n\treturn LoadSubnets(viper.GetString(\"scanner.subnet_source\"), subnetsToQuery, site)\n}", "func (u *User) GetSubnets(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET USER SUBNETS ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"subnets\"])\n\n\treturn u.do(\"GET\", url, \"\", queryParams)\n}", "func (client *CraneDockerClient) filterStackNetwork(namespace string) ([]docker.Network, error) {\n\tfilter := docker.NetworkFilterOpts{\"label\": map[string]bool{LabelNamespace: true}}\n\tnetworks, err := client.ListNetworks(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stackNetwork []docker.Network\n\tfor _, network := range networks {\n\t\tif network.Labels == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name, ok := network.Labels[LabelNamespace]; !ok || name != namespace {\n\t\t\tcontinue\n\t\t}\n\n\t\tstackNetwork = append(stackNetwork, network)\n\t}\n\n\treturn stackNetwork, nil\n}", "func (g *SCCGraph) Subnodes(cid int) []int {\n\treturn g.subnodes[g.subnodeIndexes[cid]:g.subnodeIndexes[cid+1]]\n}", "func (c Container) connectNetworks(conf dkrtypes.ContainerJSON) error {\n\tfor _, endPtConfig := range conf.NetworkSettings.Networks {\n\t\t_, err := c.dkrClient.NetworkInspect(context.TODO(), endPtConfig.NetworkID, dkrtypes.NetworkInspectOptions{})\n\t\tif err != nil {\n\t\t\tif dkrclient.IsErrNotFound(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Bridge networks cannot be inspected\n\t\t\t// todo should be fixed in swarm api?\n\t\t\treturn bosherr.Errorf(\"Did not find network '%s'\", endPtConfig.NetworkID)\n\t\t}\n\n\t\terr = c.dkrClient.NetworkConnect(\n\t\t\tcontext.TODO(), endPtConfig.NetworkID, c.id.AsString(), endPtConfig)\n\t\tif err != nil {\n\t\t\treturn bosherr.WrapError(err, \"Connecting container to network\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func ExampleDelegatedSubnetServiceClient_NewListBySubscriptionPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdelegatednetwork.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewDelegatedSubnetServiceClient().NewListBySubscriptionPager(nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.DelegatedSubnets = armdelegatednetwork.DelegatedSubnets{\n\t\t// \tValue: []*armdelegatednetwork.DelegatedSubnet{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"delegated1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.DelegatedNetwork/delegatedSubnets\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testvnet/subnets/testsubnet/providers/Microsoft.DelegatedNetwork/delegatedSubnets/delegated1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"West US\"),\n\t\t// \t\t\tProperties: &armdelegatednetwork.DelegatedSubnetProperties{\n\t\t// \t\t\t\tControllerDetails: &armdelegatednetwork.ControllerDetails{\n\t\t// \t\t\t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.DelegatedNetwork/controller/dnctestcontroller\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tProvisioningState: to.Ptr(armdelegatednetwork.DelegatedSubnetStateSucceeded),\n\t\t// \t\t\t\tResourceGUID: to.Ptr(\"5a82cbcf-e8ea-4175-ac2b-ad36a73f9801\"),\n\t\t// \t\t\t\tSubnetDetails: &armdelegatednetwork.SubnetDetails{\n\t\t// \t\t\t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testvnet/subnets/testsubnet\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func (ggSession *GreengrassSession) ListSub() error {\n\tif ggSession.config.SubscriptionDefinition.ID == \"\" {\n\t\tfmt.Printf(\"No initial subscription defined\\n\")\n\t\treturn nil\n\t}\n\tsubscription, err := ggSession.greengrass.GetSubscriptionDefinition(&greengrass.GetSubscriptionDefinitionInput{\n\t\tSubscriptionDefinitionId: &ggSession.config.SubscriptionDefinition.ID,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"subscription: %v\\n\", subscription)\n\tsubscriptionVersion, err := ggSession.greengrass.GetSubscriptionDefinitionVersion(&greengrass.GetSubscriptionDefinitionVersionInput{\n\t\tSubscriptionDefinitionId: subscription.Id,\n\t\tSubscriptionDefinitionVersionId: subscription.LatestVersion,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"subscription version: %v\\n\", subscriptionVersion)\n\n\treturn nil\n}", "func (o *orcaLB) UpdateSubConnState(sc balancer.SubConn, scs balancer.SubConnState) {}", "func TestGetNetworks(t *testing.T) {\n\trecord(t, \"getnetworks\", func(t *testing.T, svc *Service) {\n\t\t_, err := createServer(svc, \"TestGetNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworks, err := svc.GetNetworks()\n\t\trequire.NoError(t, err)\n\n\t\tassert.NotEmpty(t, networks.Networks)\n\n\t\tassert.NotEmpty(t, networks.Networks[0].IPNetworks)\n\t\tassert.NotEmpty(t, networks.Networks[0].Name)\n\t\tassert.NotEmpty(t, networks.Networks[0].Type)\n\t\tassert.NotEmpty(t, networks.Networks[0].UUID)\n\t\tassert.NotEmpty(t, networks.Networks[0].Zone)\n\n\t\t// Find a network with a server\n\t\tvar found bool\n\t\tfor _, n := range networks.Networks {\n\t\t\tif len(n.Servers) > 0 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(t, found)\n\t})\n}", "func (*ListNetworkSubnetsRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_network_service_proto_rawDescGZIP(), []int{9}\n}", "func NetworkGet(w http.ResponseWriter, r *http.Request) {\n\tresp, err := goreq.Request{\n\t\tMethod: \"GET\",\n\t\tUri: remoteURL + \"/networks/current\",\n\t}.Do()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(resp.StatusCode)\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tw.Write(body)\n}", "func (m *MockClusterScoper) Subnets() v1beta1.Subnets {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Subnets\")\n\tret0, _ := ret[0].(v1beta1.Subnets)\n\treturn ret0\n}", "func (s *StackEbrc) ListVolumes() ([]abstract.Volume, fail.Error) {\n\tlogrus.Debug(\"ebrc.Client.ListVolumes() called\")\n\tdefer logrus.Debug(\"ebrc.Client.ListVolumes() done\")\n\n\tvar volumes []abstract.Volume\n\n\torg, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn volumes, fail.Wrap(err, fmt.Sprintf(\"Error listing volumes\"))\n\t}\n\n\t// Check if network is already there\n\trefs, err := getLinks(org, \"vnd.vmware.vcloud.disk+xml\")\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error recovering network information\"))\n\t}\n\tfor _, ref := range refs {\n\t\t// FIXME: Add data\n\t\tdr, err := vdc.QueryDisk(ref.Name)\n\t\tif err == nil {\n\t\t\tthed, err := vdc.FindDiskByHREF(dr.Disk.HREF)\n\t\t\tif err == nil {\n\t\t\t\tvolumes = append(volumes, abstract.Volume{Name: ref.Name, ID: ref.ID, Size: thed.Disk.Size})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn volumes, nil\n}", "func (mavenlinkService *MavenlinkService) RetrieveTasksFromSubTasksInWorkspace(keyOrId int32, subTaskKeyOrId int32,\n\ttasks chan []communicator.Task) {\n\tvar tasksInSubTasksResponse *communicator.Response\n\tvar tasksInSubTaskListRequest communicator.Request\n\tvar tasksInSubTask []communicator.Task\n\ttasksInSubTaskListRequest.Workspace = fmt.Sprint(keyOrId)\n\ttasksInSubTaskListRequest.SubTask = fmt.Sprint(subTaskKeyOrId)\n\ttasksInSubTasksResponse, err := utility.GetUtilitiesSingleton().MavenlinkClient.GetTasksBySubTaskParentTaskAndProjectId(\n\t\tutility.GetUtilitiesSingleton().CommsContext, &tasksInSubTaskListRequest)\n\tif err == nil && tasksInSubTasksResponse.Error == nil &&\n\t\ttasksInSubTasksResponse != nil &&\n\t\ttasksInSubTasksResponse.Tasks != nil {\n\t\tfor _, taskInSubTask := range tasksInSubTasksResponse.Tasks {\n\t\t\ttasksInSubTask = append(tasksInSubTask, *taskInSubTask)\n\t\t}\n\t}\n\ttasks <- tasksInSubTask\n}", "func (o OceanOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringArrayOutput { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func SubnetCount(ipStrRange string) (int, error) {\n\trangeNumber, _ := strconv.Atoi(strings.Split(ipStrRange, \"/\")[1])\n\treturn int(math.Pow(2, float64(32-rangeNumber))), nil\n}", "func getChildren(store storage.Store, topLayer string) ([]string, error) {\n\tvar children []string\n\timages, err := store.Images()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to retrieve images from store\")\n\t}\n\tlayers, err := store.Layers()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to retrieve layers from store\")\n\t}\n\n\tfor _, layer := range layers {\n\t\tif layer.Parent == topLayer {\n\t\t\tif imageID := getImageOfTopLayer(images, layer.ID); len(imageID) > 0 {\n\t\t\t\tchildren = append(children, imageID...)\n\t\t\t}\n\t\t}\n\t}\n\treturn children, nil\n}", "func GetVPC(connectionName string, rsType string, nameID string) (*cres.VPCInfo, error) {\n\tcblog.Info(\"call GetVPC()\")\n\n\t// check empty and trim user inputs\n connectionName, err := EmptyCheckAndTrim(\"connectionName\", connectionName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n nameID, err = EmptyCheckAndTrim(\"nameID\", nameID)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n\tcldConn, err := ccm.GetCloudConnection(connectionName)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\thandler, err := cldConn.CreateVPCHandler()\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tvpcSPLock.RLock(connectionName, nameID)\n\tdefer vpcSPLock.RUnlock(connectionName, nameID)\n\t// (1) get spiderIID(NameId)\n\tiidInfo, err := iidRWLock.GetIID(iidm.IIDSGROUP, connectionName, rsType, cres.IID{nameID, \"\"})\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (2) get resource(driverIID)\n\tinfo, err := handler.GetVPC(getDriverIID(iidInfo.IId))\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\t// (3) set ResourceInfo(userIID)\n\tinfo.IId = getUserIID(iidInfo.IId)\n\n\t// set NameId for SubnetInfo List\n\t// create new SubnetInfo List\n\tsubnetInfoList := []cres.SubnetInfo{}\n\tfor _, subnetInfo := range info.SubnetInfoList {\t\t\n\t\tsubnetIIDInfo, err := iidRWLock.GetIIDbySystemID(iidm.SUBNETGROUP, connectionName, info.IId.NameId, subnetInfo.IId) // VPC info.IId.NameId => rsType\n\t\tif err != nil {\n\t\t\tcblog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif subnetIIDInfo.IId.NameId != \"\" { // insert only this user created.\n\t\t\tsubnetInfo.IId = getUserIID(subnetIIDInfo.IId)\n\t\t\tsubnetInfoList = append(subnetInfoList, subnetInfo)\n\t\t}\n\t}\n\tinfo.SubnetInfoList = subnetInfoList\n\n\treturn &info, nil\n}", "func (o *CreateLoadBalancerRequest) GetSubregionNames() []string {\n\tif o == nil || o.SubregionNames == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubregionNames\n}", "func ExampleDelegatedSubnetServiceClient_NewListByResourceGroupPager() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdelegatednetwork.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpager := clientFactory.NewDelegatedSubnetServiceClient().NewListByResourceGroupPager(\"testRG\", nil)\n\tfor pager.More() {\n\t\tpage, err := pager.NextPage(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to advance page: %v\", err)\n\t\t}\n\t\tfor _, v := range page.Value {\n\t\t\t// You could use page here. We use blank identifier for just demo purposes.\n\t\t\t_ = v\n\t\t}\n\t\t// If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t\t// page.DelegatedSubnets = armdelegatednetwork.DelegatedSubnets{\n\t\t// \tValue: []*armdelegatednetwork.DelegatedSubnet{\n\t\t// \t\t{\n\t\t// \t\t\tName: to.Ptr(\"delegated1\"),\n\t\t// \t\t\tType: to.Ptr(\"Microsoft.DelegatedNetwork/delegatedSubnets\"),\n\t\t// \t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.DelegatedNetwork/delegatedSubnets/delegated1\"),\n\t\t// \t\t\tLocation: to.Ptr(\"West US\"),\n\t\t// \t\t\tProperties: &armdelegatednetwork.DelegatedSubnetProperties{\n\t\t// \t\t\t\tControllerDetails: &armdelegatednetwork.ControllerDetails{\n\t\t// \t\t\t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.DelegatedNetwork/controller/dnctestcontroller\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t\tProvisioningState: to.Ptr(armdelegatednetwork.DelegatedSubnetStateSucceeded),\n\t\t// \t\t\t\tResourceGUID: to.Ptr(\"5a82cbcf-e8ea-4175-ac2b-ad36a73f9801\"),\n\t\t// \t\t\t\tSubnetDetails: &armdelegatednetwork.SubnetDetails{\n\t\t// \t\t\t\t\tID: to.Ptr(\"/subscriptions/613192d7-503f-477a-9cfe-4efc3ee2bd60/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testvnet/subnets/testsubnet\"),\n\t\t// \t\t\t\t},\n\t\t// \t\t\t},\n\t\t// \t}},\n\t\t// }\n\t}\n}", "func (o *FiltersSubnet) GetSubregionNames() []string {\n\tif o == nil || o.SubregionNames == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.SubregionNames\n}", "func ListVPC(connectionName string, rsType string) ([]*cres.VPCInfo, error) {\n\tcblog.Info(\"call ListVPC()\")\n\n\t// check empty and trim user inputs\n connectionName, err := EmptyCheckAndTrim(\"connectionName\", connectionName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n\tcldConn, err := ccm.GetCloudConnection(connectionName)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\thandler, err := cldConn.CreateVPCHandler()\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (1) get IID:list\n\tiidInfoList, err := iidRWLock.ListIID(iidm.IIDSGROUP, connectionName, rsType)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tvar infoList []*cres.VPCInfo\n\tif iidInfoList == nil || len(iidInfoList) <= 0 {\n\t\tinfoList = []*cres.VPCInfo{}\n\t\treturn infoList, nil\n\t}\n\n\t// (2) Get VPCInfo-list with IID-list\n\twg := new(sync.WaitGroup)\n\tresultInfoList := []*cres.VPCInfo{}\n var retChanInfos []chan ResultVPCInfo\n for i:=0 ; i<len(iidInfoList); i++ {\n retChanInfos = append(retChanInfos, make(chan ResultVPCInfo))\n }\n\n for idx, iidInfo := range iidInfoList {\n\n wg.Add(1)\n\n go getVPCInfo(connectionName, handler, iidInfo.IId, retChanInfos[idx])\n\n wg.Done()\n\n }\n wg.Wait()\n\n var errList []string\n for idx, retChanInfo := range retChanInfos {\n chanInfo := <-retChanInfo\n\n if chanInfo.err != nil {\n if checkNotFoundError(chanInfo.err) {\n cblog.Info(chanInfo.err) } else {\n errList = append(errList, connectionName + \":VPC:\" + iidInfoList[idx].IId.NameId + \" # \" + chanInfo.err.Error())\n }\n } else {\n resultInfoList = append(resultInfoList, &chanInfo.vpcInfo)\n }\n\n close(retChanInfo)\n }\n\n if len(errList) > 0 {\n cblog.Error(strings.Join(errList, \"\\n\"))\n return nil, errors.New(strings.Join(errList, \"\\n\"))\n }\n\n return resultInfoList, nil\n}", "func Explore(client *storage.Client, thinClient *ThinClient, bucket string, prefix string) ([]*Node, error) {\n // Combine bucket lifecycle to each node\n ctx := context.Background()\n lifecycle, err := thinClient.Lifecycle(ctx, bucket)\n if err != nil {\n return nil, err\n }\n\n objs, err := listq(client, bucket, prefix, \"/\", false, true)\n if err != nil {\n return nil, err\n }\n var nodes []*Node\n for _, element := range objs {\n var node Node\n node.Bucket = bucket\n node.Lifecycle = lifecycle\n if element.Name == \"\" && element.Prefix != \"\" {\n node.Ntype = \"DIR\"\n node.Name = element.Prefix\n node.FQPN = element.Prefix\n } else {\n node.Ntype = \"OBJ\"\n pathSlice := strings.Split(element.Name, \"/\")\n pathLength := len(pathSlice)\n node.Name = pathSlice[pathLength - 1]\n node.FQPN = element.Name\n }\n node.ACL = element.ACL\n node.Owner = element.Owner\n node.Size = element.Size\n\n nodes = append(nodes, &node)\n }\n return nodes, nil\n}", "func (c *MockSubnetsClient) List(ctx context.Context, resourceGroupName, virtualNetworkName string) ([]network.Subnet, error) {\n\tvar l []network.Subnet\n\tfor _, subnet := range c.Subnets {\n\t\tl = append(l, subnet)\n\t}\n\treturn l, nil\n}", "func (c *TestClient) DeleteSubnetwork(project, region, name string) error {\n\tif c.DeleteSubnetworkFn != nil {\n\t\treturn c.DeleteSubnetworkFn(project, region, name)\n\t}\n\treturn c.client.DeleteSubnetwork(project, region, name)\n}", "func handleNetworks(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {\n\tcursor := getCursor(r.URL)\n\twr, err := sm.WatchNetworks(ctx, cursor)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprint(w, err)\n\t\treturn\n\t}\n\n\tswitch wr.Cursor.(type) {\n\tcase string:\n\tcase fmt.Stringer:\n\t\twr.Cursor = wr.Cursor.(fmt.Stringer).String()\n\tdefault:\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprint(w, fmt.Errorf(\"internal error: watch cursor is of unknown type\"))\n\t\treturn\n\t}\n\n\tjsonResponse(w, http.StatusOK, wr)\n}", "func (s Subnet) String() string {\n\treturn s.IPNet().String()\n}", "func (o TopicRuleDestinationVpcConfigurationOutput) SubnetIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TopicRuleDestinationVpcConfiguration) []string { return v.SubnetIds }).(pulumi.StringArrayOutput)\n}", "func (subnet *VirtualNetworksSubnet) GetType() string {\n\treturn \"Microsoft.Network/virtualNetworks/subnets\"\n}", "func remoteBucketList(remoteURLObj interface{}) (interface{}, error) {\n\tremoteURL := remoteURLObj.(string)\n\treturn couchbase.GetBucketList(remoteURL)\n}", "func (esr *etcdSubnetRegistry) getSubnets(ctx context.Context, network string) ([]Lease, uint64, error) {\n\tkey := path.Join(esr.etcdCfg.Prefix, network, \"subnets\")\n\tresp, err := esr.client().Get(ctx, key, &etcd.GetOptions{Recursive: true})\n\tif err != nil {\n\t\tif etcdErr, ok := err.(etcd.Error); ok && etcdErr.Code == etcd.ErrorCodeKeyNotFound {\n\t\t\t// key not found: treat it as empty set\n\t\t\treturn []Lease{}, etcdErr.Index, nil\n\t\t}\n\t\treturn nil, 0, err\n\t}\n\n\tleases := []Lease{}\n\tfor _, node := range resp.Node.Nodes {\n\t\tl, err := nodeToLease(node)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Ignoring bad subnet node: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tleases = append(leases, *l)\n\t}\n\n\treturn leases, resp.Index, nil\n}" ]
[ "0.723031", "0.6620508", "0.6411955", "0.6318514", "0.63050175", "0.5996598", "0.5794883", "0.57582545", "0.5556765", "0.55465174", "0.55422586", "0.552744", "0.55186445", "0.5517332", "0.547852", "0.5456509", "0.5452419", "0.54115504", "0.5392458", "0.5382887", "0.53803706", "0.5355942", "0.5349027", "0.53387356", "0.531813", "0.5239935", "0.5221057", "0.5216952", "0.521469", "0.5087227", "0.50816405", "0.50516343", "0.49775168", "0.4967109", "0.49665937", "0.49599263", "0.4955489", "0.49101928", "0.48931226", "0.48584995", "0.48461857", "0.48461857", "0.48038164", "0.47800398", "0.47674212", "0.47572052", "0.4750294", "0.4746249", "0.47322696", "0.46995756", "0.4684503", "0.4664804", "0.46530497", "0.4648762", "0.4633029", "0.46143335", "0.4572591", "0.45593905", "0.45430577", "0.45181602", "0.4489751", "0.44856268", "0.4446347", "0.44395718", "0.4428593", "0.4423125", "0.4413099", "0.44096825", "0.4404927", "0.4400044", "0.43964", "0.4384655", "0.4382647", "0.43807405", "0.43780807", "0.43771097", "0.4376913", "0.43768504", "0.43606722", "0.43583557", "0.43570268", "0.4352833", "0.4351853", "0.43469328", "0.43462566", "0.43265212", "0.43250245", "0.43201733", "0.43104038", "0.4291397", "0.42896163", "0.42894784", "0.42659304", "0.4253101", "0.42455417", "0.42399755", "0.42380488", "0.4235234", "0.4234301", "0.4233873" ]
0.7949222
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseCloudSubnetworksExecute(r ApiBrowseCloudSubnetworksRequest) (CloudSubnetworksPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue CloudSubnetworksPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseCloudSubnetworks") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/cloudSubnetworks" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.cloudNetworkId != nil { localVarQueryParams.Add("cloudNetworkId", parameterToString(*r.cloudNetworkId, "")) } if r.availabilityZone != nil { localVarQueryParams.Add("availabilityZone", parameterToString(*r.availabilityZone, "")) } if r.offset != nil { localVarQueryParams.Add("Offset", parameterToString(*r.offset, "")) } if r.limit != nil { localVarQueryParams.Add("Limit", parameterToString(*r.limit, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
/ BrowseEncryptionKeys Method for BrowseEncryptionKeys
func (a *AmazonConnectionsApiService) BrowseEncryptionKeys(ctx _context.Context, amazonConnectionId string) ApiBrowseEncryptionKeysRequest { return ApiBrowseEncryptionKeysRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) BrowseEncryptionKeysExecute(r ApiBrowseEncryptionKeysRequest) (CloudEncryptionKeysPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudEncryptionKeysPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.BrowseEncryptionKeys\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/cloudEncryptionKeys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tif r.offset != nil {\n\t\tlocalVarQueryParams.Add(\"Offset\", parameterToString(*r.offset, \"\"))\n\t}\n\tif r.limit != nil {\n\t\tlocalVarQueryParams.Add(\"Limit\", parameterToString(*r.limit, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c *CryptohomeBinary) ListKeysEx(ctx context.Context, username string) ([]byte, error) {\n\treturn c.call(ctx, \"--action=list_keys_ex\", \"--user=\"+username)\n}", "func (api *PublicEthereumAPI) GetKeys() []ethsecp256k1.PrivKey {\n\treturn api.keys\n}", "func (orm ksORM) GetEncryptedV1CSAKeys() (retrieved []csakey.Key, err error) {\n\treturn retrieved, orm.q.Select(&retrieved, `SELECT * FROM csa_keys`)\n}", "func ReadPrivEncKeys(filenames []string) ([]PrivEncKey, error) {\n\tkeys := make([]PrivEncKey, len(filenames))\n\tfor i, filename := range filenames {\n\t\tkey, err := ReadPrivEncKey(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkeys[i] = key\n\t}\n\n\treturn keys, nil\n}", "func (spotify *Spotify) getEncodedKeys() string {\n\n\tdata := fmt.Sprintf(\"%v:%v\", spotify.clientID, spotify.clientSecret)\n\tencoded := base64.StdEncoding.EncodeToString([]byte(data))\n\n\treturn encoded\n}", "func (m *Application) GetKeyCredentials()([]KeyCredentialable) {\n return m.keyCredentials\n}", "func ListAccountKeys(w http.ResponseWriter, r *http.Request) {\n\tlogin := mux.Vars(r)[\"login\"]\n\toauth, ok := OAuthToken(r)\n\tif !ok {\n\t\tpanic(\"Request was authorized but no OAuth token is available!\") // this should never happen\n\t}\n\n\taccount, ok := data.GetAccountByLogin(login)\n\tif !ok {\n\t\tPrintErrorJSON(w, r, \"The requested account does not exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif oauth.Token.AccountUUID.String != account.UUID || !oauth.Match.Contains(\"account-read\") && !oauth.Match.Contains(\"account-admin\") {\n\t\tPrintErrorJSON(w, r, \"Access to requested key forbidden\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tkeys := account.SSHKeys()\n\tmarshal := make([]data.SSHKeyMarshaler, 0, len(keys))\n\tfor i := 0; i < len(keys); i++ {\n\t\tmarshal = append(marshal, data.SSHKeyMarshaler{SSHKey: &keys[i], Account: account})\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func RetrieveKeys(w http.ResponseWriter, req *http.Request) {\n\thaddr, err := address.NewHashFromHash(mux.Vars(req)[\"addr\"])\n\tif err != nil {\n\t\tErrorOut(w, http.StatusBadRequest, \"incorrect address\")\n\t\treturn\n\t}\n\n\t// Check if account exists\n\tar := container.GetAccountRepo()\n\tif !ar.Exists(*haddr) {\n\t\tErrorOut(w, http.StatusNotFound, \"public keys not found\")\n\t\treturn\n\t}\n\n\tkeys, err := ar.FetchKeys(*haddr)\n\tif err != nil {\n\t\tErrorOut(w, http.StatusNotFound, \"public keys not found\")\n\t\treturn\n\t}\n\n\t// Return public keys\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\t_ = json.NewEncoder(w).Encode(jsonOut{\n\t\t\"public_keys\": keys,\n\t})\n}", "func (me *XElemsEncryptedKey) Walk() (err error) {\n\tif fn := WalkHandlers.XElemsEncryptedKey; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.EncryptedKeys {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (ks *VRF) ListKeys() (publicKeys []*secp256k1.PublicKey, err error) {\n\tenc, err := ks.Get()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while listing db keys\")\n\t}\n\tfor _, enckey := range enc {\n\t\tpublicKeys = append(publicKeys, &enckey.PublicKey)\n\t}\n\treturn publicKeys, nil\n}", "func (m *ApplicationResource) ListApplicationKeys(ctx context.Context, appId string) ([]*JsonWebKey, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/credentials/keys\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jsonWebKey []*JsonWebKey\n\n\tresp, err := rq.Do(ctx, req, &jsonWebKey)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jsonWebKey, resp, nil\n}", "func (a *HyperflexApiService) GetHyperflexKeyEncryptionKeyList(ctx context.Context) ApiGetHyperflexKeyEncryptionKeyListRequest {\n\treturn ApiGetHyperflexKeyEncryptionKeyListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (ce *ClientEncryption) GetKeys(ctx context.Context) (*Cursor, error) {\n\treturn ce.keyVaultColl.Find(ctx, bson.D{})\n}", "func ShowSSHKeys(ctx *context.Context) {\n\tkeys, err := asymkey_model.ListPublicKeys(ctx.ContextUser.ID, db.ListOptions{})\n\tif err != nil {\n\t\tctx.ServerError(\"ListPublicKeys\", err)\n\t\treturn\n\t}\n\n\tvar buf bytes.Buffer\n\tfor i := range keys {\n\t\tbuf.WriteString(keys[i].OmitEmail())\n\t\tbuf.WriteString(\"\\n\")\n\t}\n\tctx.PlainTextBytes(http.StatusOK, buf.Bytes())\n}", "func (c *Conn) listKeys(prefix string, keyType int) ([]string, error) {\n\tkeys := []string{}\n\n\tlister := c.bucket.List(&blob.ListOptions{\n\t\tDelimiter: \"/\",\n\t\tPrefix: prefix,\n\t})\n\tfor {\n\t\tobj, err := lister.Next(c.ctx)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\tc.Log.Errorf(\"Failed to get next blob err=%v\", err)\n\t\t\treturn keys, err\n\t\t}\n\n\t\tswitch keyType {\n\t\tcase ListKeyBoth:\n\t\tcase ListKeyFile:\n\t\t\tif obj.IsDir {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase ListKeyDir:\n\t\t\tif !obj.IsDir {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tc.Log.Warningf(\"Invalid keyType=%d, Ignored\", keyType)\n\t\t\tcontinue\n\t\t}\n\n\t\tkeys = append(keys, obj.Key)\n\t}\n\treturn keys, nil\n}", "func (d *database) getKeys(sender ...string) (s []keypair.KeyPair, err error) {\n\ts = []keypair.KeyPair{}\n\n\tvar query string\n\tif len(sender) > 0 {\n\t\tquery = fmt.Sprintf(\"SELECT letter_content FROM letters WHERE opened == 1 AND letter_purpose == '%s' AND sender == '%s' ORDER BY time DESC;\", purpose.ShareKey, sender[0])\n\t} else {\n\t\tquery = fmt.Sprintf(\"SELECT letter_content FROM letters WHERE opened == 1 AND letter_purpose == '%s' ORDER BY time DESC;\", purpose.ShareKey)\n\t}\n\tlogger.Log.Debug(query)\n\trows, err := d.db.Query(query)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"getKeys\")\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\t// loop through rows\n\tfor rows.Next() {\n\t\tvar mKeyPair string\n\t\terr = rows.Scan(&mKeyPair)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"getKeys\")\n\t\t\treturn\n\t\t}\n\n\t\tvar kp keypair.KeyPair\n\t\terr = json.Unmarshal([]byte(mKeyPair), &kp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\ts = append(s, kp)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"getKeys\")\n\t}\n\treturn\n}", "func (digitalocean *DigitalOcean) ListKeys() ([]godo.Key, error) {\n\topt := &godo.ListOptions{\n\t\tPage: 1,\n\t\tPerPage: 200,\n\t}\n\n\tclient, err := DigitalOceanClient()\n\n\tkeys, _, err := client.client.Keys.List(client.context, opt)\n\n\treturn keys, err\n}", "func ShowGPGKeys(ctx *context.Context) {\n\tkeys, err := asymkey_model.ListGPGKeys(ctx, ctx.ContextUser.ID, db.ListOptions{})\n\tif err != nil {\n\t\tctx.ServerError(\"ListGPGKeys\", err)\n\t\treturn\n\t}\n\n\tentities := make([]*openpgp.Entity, 0)\n\tfailedEntitiesID := make([]string, 0)\n\tfor _, k := range keys {\n\t\te, err := asymkey_model.GPGKeyToEntity(k)\n\t\tif err != nil {\n\t\t\tif asymkey_model.IsErrGPGKeyImportNotExist(err) {\n\t\t\t\tfailedEntitiesID = append(failedEntitiesID, k.KeyID)\n\t\t\t\tcontinue // Skip previous import without backup of imported armored key\n\t\t\t}\n\t\t\tctx.ServerError(\"ShowGPGKeys\", err)\n\t\t\treturn\n\t\t}\n\t\tentities = append(entities, e)\n\t}\n\tvar buf bytes.Buffer\n\n\theaders := make(map[string]string)\n\tif len(failedEntitiesID) > 0 { // If some key need re-import to be exported\n\t\theaders[\"Note\"] = fmt.Sprintf(\"The keys with the following IDs couldn't be exported and need to be reuploaded %s\", strings.Join(failedEntitiesID, \", \"))\n\t} else if len(entities) == 0 {\n\t\theaders[\"Note\"] = \"This user hasn't uploaded any GPG keys.\"\n\t}\n\twriter, _ := armor.Encode(&buf, \"PGP PUBLIC KEY BLOCK\", headers)\n\tfor _, e := range entities {\n\t\terr = e.Serialize(writer) // TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange)\n\t\tif err != nil {\n\t\t\tctx.ServerError(\"ShowGPGKeys\", err)\n\t\t\treturn\n\t\t}\n\t}\n\twriter.Close()\n\tctx.PlainTextBytes(http.StatusOK, buf.Bytes())\n}", "func (p *pinner) DirectKeys() []util.Key {\n\treturn p.directPin.GetKeys()\n}", "func (v *Vault) List(path string) interface{} {\n\tsecret, err := v.Client.Logical().List(path)\n\tif err != nil || secret == nil || secret.Data == nil || secret.Data[\"keys\"] == nil {\n\t\tv.logger.Warn(\"Failed to list keys\", zap.Error(err))\n\t\t// return empty interface\n\t\treturn interface{}(nil)\n\t}\n\treturn secret.Data[\"keys\"]\n}", "func GetAllPrivateKeys(s *aklib.DBConfig) ([]string, error) {\n\tvar pk []string\n\terr := s.DB.View(func(txn *badger.Txn) error {\n\t\tit := txn.NewIterator(badger.DefaultIteratorOptions)\n\t\tdefer it.Close()\n\t\tfor it.Seek([]byte{byte(db.HeaderWallet)}); it.ValidForPrefix([]byte{byte(db.HeaderWallet)}); it.Next() {\n\t\t\tpk = append(pk, string(it.Item().KeyCopy(nil)))\n\t\t}\n\t\treturn nil\n\t})\n\treturn pk, err\n}", "func (a *SubAccountApiService) ListSubAccountKeys(ctx context.Context, userId int32) ([]SubAccountKey, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []SubAccountKey\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/sub_accounts/{user_id}/keys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"user_id\"+\"}\", url.QueryEscape(parameterToString(userId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tif ctx.Value(ContextGateAPIV4) == nil {\n\t\t// for compatibility, set configuration key and secret to context if ContextGateAPIV4 value is not present\n\t\tctx = context.WithValue(ctx, ContextGateAPIV4, GateAPIV4{\n\t\t\tKey: a.client.cfg.Key,\n\t\t\tSecret: a.client.cfg.Secret,\n\t\t})\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, gateErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func getKeys() (sshKey, error) {\n\tvar keys sshKey\n\n\tecdsaPriv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\n\tpkiPriv := pki.NewPrivateKey(ecdsaPriv)\n\n\tkeys.Private, err = pkiPriv.MarshalText()\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\tkeys.Public, err = getECDSAPublicKey(&pkiPriv.PrivateKey.PublicKey)\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\n\treturn keys, nil\n\n}", "func (client DnsClient) listTsigKeys(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tsigKeys\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListTsigKeysResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (rs *RatchetServer) GetKeys() []byte {\n\t// Separate all memory.\n\tkl := make([]byte, len(rs.keylist))\n\tcopy(kl, rs.keylist)\n\treturn kl\n}", "func (dcr *ExchangeWallet) getKeys(addr dcrutil.Address) (*secp256k1.PrivateKey, *secp256k1.PublicKey, error) {\n\twif, err := dcr.node.DumpPrivKey(dcr.ctx, addr)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"%w (is wallet locked?)\", translateRPCCancelErr(err))\n\t}\n\n\tpriv := secp256k1.PrivKeyFromBytes(wif.PrivKey())\n\treturn priv, priv.PubKey(), nil\n}", "func ListAllKeys() error {\n\n\tdb := Connect()\n\n\tif ExistDb(PathDb) {\n\n\t\tfmt.Println(\"Exist\", db)\n\n\t} else {\n\n\t\tfmt.Println(\"Not exist!\")\n\t\tos.Exit(1)\n\t}\n\n\tdb.View(func(tx *bolt.Tx) error {\n\n\t\t// Assume bucket exists and has keys\n\t\tb := tx.Bucket([]byte(Database))\n\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\n\t\t\tfmt.Printf(\"key=%s, value=%s\\n\", k, v)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn nil\n\n}", "func getSecretKeys(w http.ResponseWriter, r *http.Request) {\n\tdefer traceTime(here())()\n\n\tval, err := api.secretEngine.SecretKeys()\n\tif err != nil {\n\t\tTLog.Printf(ERROR_CONTENT, \"\", err.Error())\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresultJSON, err := json.Marshal(val)\n\n\tif err != nil {\n\t\tTLog.Printf(ERROR_CONTENT, \"\", err.Error())\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\tTResult.Print(string(resultJSON))\n\tw.Header().Set(\"Content-Type\", MimeTypeJSON)\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(resultJSON)\n}", "func expandImageSourceSnapshotEncryptionKeyMap(c *Client, f map[string]ImageSourceSnapshotEncryptionKey) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandImageSourceSnapshotEncryptionKey(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (r *reflectorStore) ListKeys() []string {\n\tpanic(\"not implemented\")\n}", "func (kb *Keybase) List() ([]keys.Info, error) {\n\tkb.mx.Lock()\n\tdefer kb.mx.Unlock()\n\treturn kb.kb.List()\n}", "func (u *CryptohomeClient) ListVaultKeys(ctx context.Context, username string) ([]string, error) {\n\tbinaryOutput, err := u.binary.listKeysEx(ctx, username)\n\tif err != nil {\n\t\treturn []string{}, errors.Wrap(err, \"failed to call list keys\")\n\t}\n\n\toutput := string(binaryOutput)\n\tlines := strings.Split(output, \"\\n\")\n\tvar result []string\n\tfor _, s := range lines {\n\t\tif strings.HasPrefix(s, listKeysExLabelPrefix) {\n\t\t\tresult = append(result, s[len(listKeysExLabelPrefix):])\n\t\t}\n\t}\n\treturn result, nil\n}", "func expandImageImageEncryptionKeyMap(c *Client, f map[string]ImageImageEncryptionKey) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandImageImageEncryptionKey(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (*Key) Descriptor() ([]byte, []int) {\n\treturn file_credential_proto_rawDescGZIP(), []int{2}\n}", "func (me *XElemEncryptedKey) Walk() (err error) {\n\tif fn := WalkHandlers.XElemEncryptedKey; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.EncryptedKey.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (ks *VRF) get(k ...secp256k1.PublicKey) ([]*vrfkey.EncryptedVRFKey,\n\terror) {\n\tif len(k) > 1 {\n\t\treturn nil, errors.Errorf(\"can get at most one secret key at a time\")\n\t}\n\tvar where []vrfkey.EncryptedVRFKey\n\tif len(k) == 1 { // Search for this specific public key\n\t\twhere = append(where, vrfkey.EncryptedVRFKey{PublicKey: k[0]})\n\t}\n\tkeys, err := ks.orm.FindEncryptedSecretVRFKeys(where...)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to find public key %s in DB\", k)\n\t}\n\treturn keys, nil\n}", "func (key *Key) MarshalJSON(passphrase string) ([]byte, error) {\n\tsalt, err := crypto.RandomEntropy(32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdk, err := scrypt.Key([]byte(passphrase), salt, scryptN, scryptR, scryptP, scryptKeyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv, err := crypto.RandomEntropy(aes.BlockSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenckey := dk[:16]\n\n\tprivateKeyBytes, err := key.KeyPair.Private.Bytes()\n\tprivateKeyBytes = privateKeyBytes[4:]\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taesBlock, err := aes.NewCipher(enckey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstream := cipher.NewCTR(aesBlock, iv)\n\tcipherText := make([]byte, len(privateKeyBytes))\n\tstream.XORKeyStream(cipherText, privateKeyBytes)\n\n\tmac := crypto.Keccak256(dk[16:32], cipherText)\n\tcipherParamsJSON := cipherparamsJSON{\n\t\tIV: hex.EncodeToString(iv),\n\t}\n\n\tsp := ScryptParams{\n\t\tN: scryptN,\n\t\tR: scryptR,\n\t\tP: scryptP,\n\t\tDKeyLength: scryptKeyLen,\n\t\tSalt: hex.EncodeToString(salt),\n\t}\n\n\tkeyjson := cryptoJSON{\n\t\tCipher: ksCipher,\n\t\tCipherText: hex.EncodeToString(cipherText),\n\t\tCipherParams: cipherParamsJSON,\n\t\tKDF: nameKDF,\n\t\tKDFParams: sp,\n\t\tMAC: hex.EncodeToString(mac),\n\t}\n\n\tencjson := encryptedKeyJSON{\n\t\tAddress: key.KeyPair.Address,\n\t\tCrypto: keyjson,\n\t\tID: key.ID.String(),\n\t\tVersion: ksVersion,\n\t}\n\tdata, err := json.MarshalIndent(&encjson, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (client IdentityClient) listApiKeys(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/users/{userId}/apiKeys\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListApiKeysResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client IotHubResourceClient) ListKeysSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (ctrl *CSAKeysController) Index(c *gin.Context) {\n\tkeys, err := ctrl.App.GetKeyStore().CSA().ListCSAKeys()\n\tif err != nil {\n\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tjsonAPIResponse(c, presenters.NewCSAKeyResources(keys), \"csaKeys\")\n}", "func (*EncryptedData) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_v3_keys_proto_rawDescGZIP(), []int{1}\n}", "func (client IotHubResourceClient) ListKeys(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.sasarlr.Response.Response != nil {\n\t\t\t\tsc = result.sasarlr.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listKeysNextResults\n\treq, err := client.ListKeysPreparer(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListKeysSender(req)\n\tif err != nil {\n\t\tresult.sasarlr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.sasarlr, err = client.ListKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.sasarlr.hasNextLink() && result.sasarlr.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func (ks *VRF) ListKeysIncludingArchived() (publicKeys []*secp256k1.PublicKey, err error) {\n\tallKeys, err := ks.orm.FindEncryptedSecretVRFKeysIncludingArchived()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, enckey := range allKeys {\n\t\tpublicKeys = append(publicKeys, &enckey.PublicKey)\n\t}\n\treturn publicKeys, nil\n}", "func (c *KeysClient) List(ctx context.Context, _ *ListKeysInput) ([]*Key, error) {\n\tfullPath := path.Join(\"/\", c.client.AccountName, \"keys\")\n\treqInputs := client.RequestInput{\n\t\tMethod: http.MethodGet,\n\t\tPath: fullPath,\n\t}\n\trespReader, err := c.client.ExecuteRequest(ctx, reqInputs)\n\tif respReader != nil {\n\t\tdefer respReader.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to list keys\")\n\t}\n\n\tvar result []*Key\n\tdecoder := json.NewDecoder(respReader)\n\tif err = decoder.Decode(&result); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to decode list keys response\")\n\t}\n\n\treturn result, nil\n}", "func (client IotHubResourceClient) GetKeysForKeyNameSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (b *B2) ListKeys(maxKeyCount int64, startApplicationKeyId string) (*ApplicationKeys, error) {\n\tvar (\n\t\turl = fmt.Sprintf(\"%s/b2api/v1/b2_list_keys\", b.auth.ApiUrl)\n\t\trequestBody = &struct {\n\t\t\tAccountId string `json:\"accountId\"`\n\t\t\tMaxKeyCount int64 `json:\"maxKeyCount,omitempty\"`\n\t\t\tStartApplicationKeyId string `json:\"startApplicationKeyId,omitempty\"`\n\t\t}{b.auth.AccountId, maxKeyCount, startApplicationKeyId}\n\t\tresponseBody = &ApplicationKeys{}\n\t)\n\n\tresponse, err := b.makeAuthedRequest(url, requestBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\tcase response.StatusCode == 200:\n\t\tif err = unmarshalResponseBody(response, responseBody); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn responseBody, nil\n\tcase response.StatusCode == 400 || response.StatusCode == 401:\n\t\treturn nil, handleErrorResponse(response)\n\tdefault:\n\t\treturn nil, handleUnknownResponse(response)\n\t}\n}", "func (client IotHubResourceClient) ListKeysComplete(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultIterator, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response().Response.Response != nil {\n\t\t\t\tsc = result.page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.page, err = client.ListKeys(ctx, resourceGroupName, resourceName)\n\treturn\n}", "func (a *HyperflexApiService) GetHyperflexEncryptionList(ctx context.Context) ApiGetHyperflexEncryptionListRequest {\n\treturn ApiGetHyperflexEncryptionListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (v *Vault) ListTransitKeys() {\n\td, err := v.Client.Logical().List(\"transit/keys\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Vault error: %v\", err)\n\t}\n\n\tif d != nil {\n\t\ttable := tablewriter.NewWriter(os.Stdout)\n\t\ttable.SetHeader([]string{\"Key\"})\n\t\tfor _, l := range d.Data[\"keys\"].([]interface{}) {\n\t\t\ttable.Append([]string{l.(string)})\n\t\t}\n\t\ttable.Render()\n\t}\n}", "func (k *KeyStore) List() []string {\n\tvar keys []string\n\tfor k := range k.Values {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func lunaListKeys(p *pkcs11.Ctx, session pkcs11.SessionHandle) (map[string]trustmanager.KeyInfo, error) {\n\n\tkeys := make(map[string]trustmanager.KeyInfo)\n\tfindTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),\n\t}\n\n\tobjects, err := findObjects(p, session, findTemplate)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error finding objects: %v\", err)\n\t}\n\n\tif len(objects) == 0 {\n\t\treturn nil, errors.New(\"No keys found in Luna.\")\n\t}\n\n\tattrTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VALUE, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte{0}),\n\t}\n\n\tfor _, obj := range objects {\n\t\tvar (\n\t\t\tcert *x509.Certificate\n\t\t\tid []byte\n\t\t\tlabel string\n\t\t\tgun string\n\t\t)\n\t\t// Retrieve the public-key material to be able to create a new ECDSA\n\t\tattr, err := p.GetAttributeValue(session, obj, attrTemplate)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"Failed to get Attribute for: %v\", obj)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, a := range attr {\n\t\t\tif a.Type == pkcs11.CKA_ID {\n\t\t\t\tid = a.Value\n\t\t\t}\n\t\t\tif a.Type == pkcs11.CKA_VALUE {\n\t\t\t\tcert, err = x509.ParseCertificate(a.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !data.ValidRole(data.RoleName(cert.Subject.CommonName)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif a.Type == pkcs11.CKA_LABEL {\n\t\t\t\tif !strings.HasPrefix(string(a.Value), \"notary-\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlabel = string(a.Value)\n\t\t\t}\n\t\t}\n\n\t\tif id == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif cert == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif cert.PublicKeyAlgorithm != x509.ECDSA && cert.PublicKeyAlgorithm != x509.RSA {\n\t\t\tcontinue\n\t\t}\n\n\t\tfieldsSplit := strings.Split(label, \"notary-\")\n\t\tif len(fieldsSplit) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tsplit := strings.Split(fieldsSplit[1], \";\")\n\t\tif len(split) < 1 {\n\t\t\tcontinue\n\t\t}\n\t\tgun = split[0]\n\n\t\tif cert.Subject.CommonName == \"root\" {\n\t\t\tif isRootKeyFiltered(string(id)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tkeys[string(id)] = trustmanager.KeyInfo{Role: data.RoleName(cert.Subject.CommonName), Gun: data.GUN(gun)}\n\t}\n\treturn keys, nil\n}", "func (l Locksmith) GetKey(u string) ([]string, error) {\n\turl := u\n\tif !isURL.MatchString(u) {\n\t\tswitch u {\n\t\tcase \"new\":\n\t\t\turl = SSHKEYS_ONLINE\n\t\tdefault:\n\t\t\turl = fmt.Sprintf(\"%s/%s.keys\", l.URL, u)\n\t\t}\n\t}\n\tclient := &http.Client{}\n\t// create a new request\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", \"ssh-vault\")\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\treader := bufio.NewReader(res.Body)\n\ttp := textproto.NewReader(reader)\n\tkeys := []string{}\n\trsa := bytes.Buffer{}\n\tisRSA := false\n\tfor {\n\t\tif line, err := tp.ReadLine(); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tif len(keys) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"key %q not found\", u)\n\t\t\t\t}\n\t\t\t\treturn keys, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t} else if strings.HasPrefix(line, \"ssh-rsa\") {\n\t\t\tkeys = append(keys, line)\n\t\t} else if strings.HasPrefix(line, \"-----BEGIN RSA PRIVATE KEY-----\") {\n\t\t\tisRSA = true\n\t\t\tif _, err := rsa.WriteString(line + \"\\n\"); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else if strings.HasPrefix(line, \"-----END RSA PRIVATE KEY-----\") {\n\t\t\tif _, err := rsa.WriteString(line); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn []string{rsa.String()}, nil\n\t\t} else if isRSA {\n\t\t\tif _, err := rsa.WriteString(line + \"\\n\"); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) ListSecretKeys(secretBlindName string) ([]*api.EncryptedSecretKey, error) {\n\tout := []*api.EncryptedSecretKey{}\n\trawURL := fmt.Sprintf(pathSecretKeys, c.base.String(), secretBlindName)\n\terr := c.get(rawURL, true, &out)\n\treturn out, errio.Error(err)\n}", "func (c *Conn) Keys() ([][]byte, error) {\n\tresponse := c.client.Cmd(cmdKeys)\n\titems, err := response.Array()\n\tif err != nil {\n\t\treturn nil, errx.Annotatef(err, \"response array\")\n\t}\n\tkeys := make([][]byte, len(items))\n\tfor index, item := range items {\n\t\tkey, err := item.Bytes()\n\t\tif err != nil {\n\t\t\treturn nil, errx.Annotatef(err, \"response bytes\")\n\t\t}\n\t\tkeys[index] = key\n\t}\n\treturn keys, nil\n}", "func (c defaultSTSClient) ListAccessKeys(username string) ([]KeyInfo, error) {\n\tif username == \"\" {\n\t\treturn nil, errors.New(\"empty username\")\n\t}\n\tresp, err := resty.R().\n\t\tGet(c.stsURLPrefix + \"/users/\" + username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody := resp.Body()\n\tif resp.StatusCode() != http.StatusOK {\n\t\tglog.Errorf(\"Cannot query username '%s'\\nBody: %s\", username, string(body))\n\t\treturn nil, pion_clients.ErrInternalError\n\t}\n\n\tvar keyInfos []KeyInfo\n\terr = json.Unmarshal(body, &keyInfos)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to parse response from STS::List(): %v\", err)\n\t\treturn nil, err\n\t}\n\treturn keyInfos, nil\n}", "func QueryObject(stub shim.ChaincodeStubInterface, objectType string, keys []string) ([]byte, error) {\n\n // Check how many keys\n\n err := VerifyAtLeastOneKeyIsPresent(objectType, keys )\n if err != nil {\n return nil, err\n }\n\n compoundKey, _ := stub.CreateCompositeKey(objectType, keys)\n fmt.Println(\"QueryObject() : Compound Key : \", compoundKey)\n\n Avalbytes, err := stub.GetState(compoundKey)\n if err != nil {\n return nil, err\n }\n\n return Avalbytes, nil\n}", "func (rpcMethod *RPCMethod) listKeys(response *ResponseParameters) error {\n\n\t//open a read transaction\n\trpcMethod.rpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\n\t\t//append to reselt the list of buckets\n\t\tresponse.Result = make([]interface{}, 0, 10)\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\trpcMethod.rpcServer.logger.Println(\"BUCKET \", string(k))\n\t\t\tresponse.Result = append(response.Result, string(k))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tresponse.Error = nil\n\n\treturn nil\n\n}", "func (rpcMethod *RPCMethod) listKeys(response *ResponseParameters) error {\n\n\t//open a read transaction\n\trpcMethod.rpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\n\t\t//append to reselt the list of buckets\n\t\tresponse.Result = make([]interface{}, 0, 10)\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\trpcMethod.rpcServer.logger.Println(\"BUCKET \", string(k))\n\t\t\tresponse.Result = append(response.Result, string(k))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tresponse.Error = nil\n\n\treturn nil\n\n}", "func (a *HyperflexApiService) GetHyperflexKeyEncryptionKeyListExecute(r ApiGetHyperflexKeyEncryptionKeyListRequest) (*HyperflexKeyEncryptionKeyResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexKeyEncryptionKeyResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexKeyEncryptionKeyList\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/KeyEncryptionKeys\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif r.filter != nil {\n\t\tlocalVarQueryParams.Add(\"$filter\", parameterToString(*r.filter, \"\"))\n\t}\n\tif r.orderby != nil {\n\t\tlocalVarQueryParams.Add(\"$orderby\", parameterToString(*r.orderby, \"\"))\n\t}\n\tif r.top != nil {\n\t\tlocalVarQueryParams.Add(\"$top\", parameterToString(*r.top, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"$skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.select_ != nil {\n\t\tlocalVarQueryParams.Add(\"$select\", parameterToString(*r.select_, \"\"))\n\t}\n\tif r.expand != nil {\n\t\tlocalVarQueryParams.Add(\"$expand\", parameterToString(*r.expand, \"\"))\n\t}\n\tif r.apply != nil {\n\t\tlocalVarQueryParams.Add(\"$apply\", parameterToString(*r.apply, \"\"))\n\t}\n\tif r.count != nil {\n\t\tlocalVarQueryParams.Add(\"$count\", parameterToString(*r.count, \"\"))\n\t}\n\tif r.inlinecount != nil {\n\t\tlocalVarQueryParams.Add(\"$inlinecount\", parameterToString(*r.inlinecount, \"\"))\n\t}\n\tif r.at != nil {\n\t\tlocalVarQueryParams.Add(\"at\", parameterToString(*r.at, \"\"))\n\t}\n\tif r.tags != nil {\n\t\tlocalVarQueryParams.Add(\"tags\", parameterToString(*r.tags, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (s *SyncStorage) ListKeys(ns string, pattern string) ([]string, error) {\n\tnsPrefix := getNsPrefix(ns)\n\tnsKeys, err := s.getDbBackend(ns).Keys(nsPrefix + pattern)\n\tvar keys []string\n\tif err != nil {\n\t\treturn keys, err\n\t}\n\tfor _, key := range nsKeys {\n\t\tkeys = append(keys, strings.Split(key, nsPrefix)[1])\n\t}\n\treturn keys, err\n}", "func show(keyStr string) {\n\tkeys, err := keybinding.ParseAll(keyStr)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing\", keyStr, \":\", err)\n\t} else {\n\t\tfmt.Println(\"Key: \", keyStr, \"=\", keys)\n\t}\n}", "func (db *memorydb) IterKeys(ctx context.Context) <-chan []byte {\n\tkeys := db.Keys()\n\n\tout := make(chan []byte)\n\tgo func() {\n\t\tdefer close(out)\n\n\t\tfor _, k := range keys {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase out <- k:\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}", "func (b *BigIP) Keys() (*Keys, error) {\n\tvar keys Keys\n\terr, _ := b.getForEntity(&keys, uriSys, uriCrypto, uriKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &keys, nil\n}", "func (a *DeviceAPI) GetKeys(ctx context.Context, req *api.GetDeviceKeysRequest) (*api.GetDeviceKeysResponse, error) {\n\tvar eui lorawan.EUI64\n\tif err := eui.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, err.Error())\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Update, eui); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\tdk, err := a.st.GetDeviceKeys(ctx, eui)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\treturn &api.GetDeviceKeysResponse{\n\t\tDeviceKeys: &api.DeviceKeys{\n\t\t\tDevEui: eui.String(),\n\t\t\tAppKey: dk.AppKey.String(),\n\t\t\tNwkKey: dk.NwkKey.String(),\n\t\t\tGenAppKey: dk.GenAppKey.String(),\n\t\t},\n\t}, nil\n}", "func skykeyListKeys(c client.Client, showPrivateKeys bool) (string, error) {\n\tskykeys, err := c.SkykeySkykeysGet()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar b strings.Builder\n\tw := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0)\n\n\t// Print a title row.\n\tif showPrivateKeys {\n\t\tfmt.Fprintf(w, \"ID\\tName\\tType\\tFull Skykey\\n\")\n\t} else {\n\t\tfmt.Fprintf(w, \"ID\\tName\\tType\\n\")\n\t}\n\n\tif err = w.Flush(); err != nil {\n\t\treturn \"\", err\n\t}\n\ttitleLen := b.Len() - 1\n\tfor i := 0; i < titleLen; i++ {\n\t\tfmt.Fprintf(w, \"-\")\n\t}\n\tfmt.Fprintf(w, \"\\n\")\n\n\tfor _, sk := range skykeys {\n\t\tidStr := sk.ID().ToString()\n\t\tif !showPrivateKeys {\n\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\n\", idStr, sk.Name, sk.Type.ToString())\n\t\t\tcontinue\n\t\t}\n\t\tskStr, err := sk.ToString()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\n\", idStr, sk.Name, sk.Type.ToString(), skStr)\n\t}\n\n\tif err = w.Flush(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn b.String(), nil\n}", "func (c *CoinInfoClient) QueryKeys(ci *CoinInfo) *KeyStoreQuery {\n\tquery := &KeyStoreQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := ci.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(coininfo.Table, coininfo.FieldID, id),\n\t\t\tsqlgraph.To(keystore.Table, keystore.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, coininfo.KeysTable, coininfo.KeysColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(ci.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func expandImageSourceDiskEncryptionKeyMap(c *Client, f map[string]ImageSourceDiskEncryptionKey) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandImageSourceDiskEncryptionKey(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (*ListAccessKeysRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_iam_v1_awscompatibility_access_key_service_proto_rawDescGZIP(), []int{1}\n}", "func (ekc *ETHKeysController) Index(c *gin.Context) {\n\tstore := ekc.App.GetStore()\n\tkeys, err := store.AllKeys()\n\tif err != nil {\n\t\terr = errors.Errorf(\"error fetching ETH keys from database: %v\", err)\n\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tvar pkeys []presenters.ETHKey\n\tfor _, key := range keys {\n\t\tethBalance, err := store.EthClient.BalanceAt(c.Request.Context(), key.Address.Address(), nil)\n\t\tif err != nil {\n\t\t\terr = errors.Errorf(\"error calling getEthBalance on Ethereum node: %v\", err)\n\t\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\tlinkAddress := common.HexToAddress(store.Config.LinkContractAddress())\n\t\tlinkBalance, err := store.EthClient.GetLINKBalance(linkAddress, key.Address.Address())\n\t\tif err != nil {\n\t\t\terr = errors.Errorf(\"error calling getLINKBalance on Ethereum node: %v\", err)\n\t\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\tk, err := store.ORM.KeyByAddress(key.Address.Address())\n\t\tif err != nil {\n\t\t\terr = errors.Errorf(\"error fetching ETH key from DB: %v\", err)\n\t\t\tjsonAPIError(c, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tpkeys = append(pkeys, presenters.ETHKey{\n\t\t\tAddress: k.Address.Hex(),\n\t\t\tEthBalance: (*assets.Eth)(ethBalance),\n\t\t\tLinkBalance: linkBalance,\n\t\t\tNextNonce: k.NextNonce,\n\t\t\tLastUsed: k.LastUsed,\n\t\t\tIsFunding: k.IsFunding,\n\t\t\tCreatedAt: k.CreatedAt,\n\t\t\tUpdatedAt: k.UpdatedAt,\n\t\t\tDeletedAt: k.DeletedAt,\n\t\t})\n\t}\n\tjsonAPIResponse(c, pkeys, \"keys\")\n}", "func (app Application) SSHKeys() []ApplicationKey {\n\tkeys := []ApplicationKey{}\n\tfor _, k := range app.Keys {\n\t\tif k.Type == KeyTypeSSH {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t}\n\treturn keys\n}", "func initialiseEncryption() (rsa.PrivateKey, rsa.PublicKey, []byte) {\n\tkeypath := \"./app/server/hangmangoprivate.pem\"\n\n\tif !fileExists(keypath) {\n\t\tlog.Printf(\"- CRYPTO - No keys identified on disk, generating...\")\n\t\tsize := 2048\n\t\tkey, err := rsa.GenerateKey(rand.Reader, size)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- CRYPTO - %s\", err)\n\t\t}\n\t\terr = key.Validate()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- CRYPTO - key failed to validate - %s\", err)\n\t\t}\n\t\tkObj, err := json.Marshal(key.PublicKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- ENCODING - %s\", err)\n\t\t}\n\n\t\tlog.Printf(\"- CRYPTO - Keys generated, writing private key to file.\")\n\n\t\tpemPrivateFile, err := os.Create(keypath)\n\t\tif err != nil {\n\t\t\tlog.Printf(\" - CRYPTO - failed to open handle to %s - %s\", keypath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tpemPrivateBlock := &pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: x509.MarshalPKCS1PrivateKey(key),\n\t\t}\n\n\t\terr = pem.Encode(pemPrivateFile, pemPrivateBlock)\n\t\tif err != nil {\n\t\t\tlog.Printf(\" - CRYPTO - failed to encode encryption private key %s - %s\", keypath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tpemPrivateFile.Close()\n\n\t\treturn *key, key.PublicKey, kObj\n\t} else {\n\t\t// Keys are on disk, we just read them in.\n\t\tprivateKeyFile, err := os.Open(keypath)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- CRYPTO - Expected to read from %s but failed to open handle - %s\", keypath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tpemfileinfo, _ := privateKeyFile.Stat()\n\t\tvar size int64 = pemfileinfo.Size()\n\t\tpembytes := make([]byte, size)\n\t\tbuffer := bufio.NewReader(privateKeyFile)\n\t\t_, err = buffer.Read(pembytes)\n\t\tdata, _ := pem.Decode([]byte(pembytes))\n\t\tprivateKeyFile.Close()\n\n\t\tkey, err := x509.ParsePKCS1PrivateKey(data.Bytes)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- CRYPTO - Failed to unmarshal private key object from %s bytes - %s\", keypath, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\terr = key.Validate()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- CRYPTO - key failed to validate - %s\", err)\n\t\t}\n\t\tkObj, err := json.Marshal(key.PublicKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"- ENCODING - %s\", err)\n\t\t}\n\t\treturn *key, key.PublicKey, kObj\n\t}\n}", "func keys(c *cli.Context) {\n\tif c.NArg() < 1 {\n\t\tfmt.Fprintln(c.App.ErrWriter, \"keys requires at least 1 argument\")\n\t\tcli.ShowCommandHelp(c, \"keys\")\n\t\treturn\n\t}\n\tfor _, filepath := range c.Args() {\n\t\tdecoder := rdr.NewDecoder()\n\t\tgo decode(c, decoder, filepath)\n\t\tfor e := range decoder.Entries {\n\t\t\tfmt.Fprintf(c.App.Writer, \"%v\\n\", e.Key)\n\t\t}\n\t}\n}", "func (client *SQLResourcesClient) listClientEncryptionKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, databaseName string, options *SQLResourcesClientListClientEncryptionKeysOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/clientEncryptionKeys\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif databaseName == \"\" {\n\t\treturn nil, errors.New(\"parameter databaseName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{databaseName}\", url.PathEscape(databaseName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *Repository) GetSelection(page int, itemsPerPage int) ([]SSHKey, error) {\n\tvar response sshKeysWrapper\n\tparams := url.Values{\n\t\t\"pageSize\": []string{fmt.Sprintf(\"%d\", itemsPerPage)},\n\t\t\"page\": []string{fmt.Sprintf(\"%d\", page)},\n\t}\n\n\trestRequest := rest.Request{Endpoint: \"/ssh-keys\", Parameters: params}\n\terr := r.Client.Get(restRequest, &response)\n\n\treturn response.SSHKeys, err\n}", "func (k *FileKeystore) List() ([]string, error) {\n\tk.RLock()\n\tdefer k.RUnlock()\n\n\tkeys := make([]string, 0, len(k.secrets))\n\tfor key := range k.secrets {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys, nil\n}", "func encryptionKeys(seedStr string) (validKeys []crypto.TwofishKey) {\n\tdicts := []mnemonics.DictionaryID{\"english\", \"german\", \"japanese\"}\n\tfor _, dict := range dicts {\n\t\tseed, err := modules.StringToSeed(seedStr, dict)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tvalidKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(seed)))\n\t}\n\tvalidKeys = append(validKeys, crypto.TwofishKey(crypto.HashObject(seedStr)))\n\treturn validKeys\n}", "func expandImageSourceImageEncryptionKeyMap(c *Client, f map[string]ImageSourceImageEncryptionKey) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandImageSourceImageEncryptionKey(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (i *Instance) AllKeys() []string {\n\trows, err := i.db.Query(`SELECT key FROM config`)\n\tif err != nil {\n\t\tmultilog.Error(\"config:AllKeys query failed: %s\", errs.JoinMessage(err))\n\t\treturn nil\n\t}\n\tvar keys []string\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar key string\n\t\trows.Scan(&key)\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}", "func (k *Ed25519PrivateKey) Bytes() ([]byte, error) {\n\treturn MarshalPrivateKey(k)\n}", "func (s *SmartContract) queryChainKey(stub shim.ChaincodeStubInterface, args []string) sc.Response {\n\tif len(args) != 1 {\n\t\tshim.Error(\"Incorrect number of arguments, Expecting 1\")\n\t}\n\tchainkeyAsBytes, _ := stub.GetState(args[0])\n\tdata := string(chainkeyAsBytes)\n\tfmt.Println(\"Returning list of Asset %s args[0]\", data)\n\n\tif chainkeyAsBytes == nil {\n\t\treturn shim.Error(\"could not locate Asset\")\n\t}\n\treturn shim.Success(chainkeyAsBytes)\n}", "func (s *SmartContract) listChainKeys(stub shim.ChaincodeStubInterface) sc.Response {\n\tstartKey := \"0\"\n\tendKey := \"999999\"\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\tbArrayMemberAlreadyWritten := false\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\t\tfmt.Printf(\"We are trying to print raw data\")\n\t\tfmt.Printf(string(queryResponse.Value))\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\t// Add comma before array members, supress it for first array memeber\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResponse.Key)\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(\",\\\"Record\\\":\")\n\t\t// Record is a JSON object so we can re-write it as\n\n\t\tbuffer.WriteString(string(queryResponse.Value))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\tfmt.Printf(\"List of Contracts: \\n%s \\n\", buffer.String())\n\treturn shim.Success(buffer.Bytes())\n}", "func (c *jsiiProxy_CfnDataCatalogEncryptionSettings) Inspect(inspector awscdk.TreeInspector) {\n\t_jsii_.InvokeVoid(\n\t\tc,\n\t\t\"inspect\",\n\t\t[]interface{}{inspector},\n\t)\n}", "func encodeKeys(privateKeyRaw *ecdsa.PrivateKey, publicKeyRaw *ecdsa.PublicKey) (string, string) {\n\n\ts := \"START encodeKeys() - Encodes privateKeyRaw & publicKeyRaw to privateKeyHex & publicKeyHex\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\tprivateKeyx509Encoded, _ := x509.MarshalECPrivateKey(privateKeyRaw)\n\tprivateKeyPEM := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"PRIVATE KEY\",\n\t\t\tBytes: privateKeyx509Encoded,\n\t\t})\n\tprivateKeyHex := hex.EncodeToString(privateKeyPEM)\n\n\tpublicKeyx509Encoded, _ := x509.MarshalPKIXPublicKey(publicKeyRaw)\n\tpublicKeyPEM := pem.EncodeToMemory(\n\t\t&pem.Block{\n\t\t\tType: \"PUBLIC KEY\",\n\t\t\tBytes: publicKeyx509Encoded,\n\t\t})\n\tpublicKeyHex := hex.EncodeToString(publicKeyPEM)\n\n\ts = \"END encodeKeys() - Encodes privateKeyRaw & publicKeyRaw to privateKeyHex & publicKeyHex\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn privateKeyHex, publicKeyHex\n\n}", "func (v *WorkspaceFolder) NKeys() int { return 2 }", "func (a *Client) GetEncryptionKeys(params *GetEncryptionKeysParams) (*GetEncryptionKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetEncryptionKeysParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getEncryptionKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/encryption_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetEncryptionKeysReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetEncryptionKeysOK), nil\n\n}", "func (b *Backend) streamKeys(t *template.Template) {\n\t// define ssm request parameters\n\tparams := &ssm.GetParametersByPathInput{\n\t\tMaxResults: aws.Int64(10),\n\t\tPath: aws.String(t.Prefix),\n\t\tRecursive: aws.Bool(true),\n\t\tWithDecryption: aws.Bool(true),\n\t}\n\n\t// define parameter page handler\n\thandler := func(output *ssm.GetParametersByPathOutput, last bool) bool {\n\t\tfor _, p := range output.Parameters {\n\t\t\tb.keys <- &template.Key{\n\t\t\t\tName: *p.Name,\n\t\t\t\tValue: *p.Value,\n\t\t\t}\n\t\t}\n\t\treturn !last\n\t}\n\n\t// process all parameters until there are no parameters left to process\n\tif err := b.svc.GetParametersByPathPagesWithContext(context.Background(), params, handler); err != nil {\n\t\tb.log.WithError(err).Errorln(\"ssm error detected\")\n\t\tb.keys <- &template.Key{\n\t\t\tError: err,\n\t\t}\n\t}\n\tclose(b.keys)\n}", "func (*CredentialsKVProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{1}\n}", "func doGetAllIpKeys(d *db.DB, dbSpec *db.TableSpec) ([]db.Key, error) {\n\n var keys []db.Key\n\n intfTable, err := d.GetTable(dbSpec)\n if err != nil {\n return keys, err\n }\n\n keys, err = intfTable.GetKeys()\n log.Infof(\"Found %d INTF table keys\", len(keys))\n return keys, err\n}", "func (defaultStorage) GetKeyList(section string) []string {\n\tpanic(noConfigStorage)\n}", "func deriveKeys(forwardSecure bool, sharedSecret, nonces []byte, connID protocol.ConnectionID, chlo, scfg, cert, divNonce []byte, keyLen int, swap bool) ([]byte, []byte, []byte, []byte, error) {\n\tvar info bytes.Buffer\n\tif forwardSecure {\n\t\tinfo.Write([]byte(\"QUIC forward secure key expansion\\x00\"))\n\t} else {\n\t\tinfo.Write([]byte(\"QUIC key expansion\\x00\"))\n\t}\n\tinfo.Write(connID)\n\tinfo.Write(chlo)\n\tinfo.Write(scfg)\n\tinfo.Write(cert)\n\n\tr := hkdf.New(sha256.New, sharedSecret, nonces, info.Bytes())\n\n\ts := make([]byte, 2*keyLen+2*4)\n\tif _, err := io.ReadFull(r, s); err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tkey1 := s[:keyLen]\n\tkey2 := s[keyLen : 2*keyLen]\n\tiv1 := s[2*keyLen : 2*keyLen+4]\n\tiv2 := s[2*keyLen+4:]\n\n\tvar otherKey, myKey []byte\n\tvar otherIV, myIV []byte\n\n\tif !forwardSecure {\n\t\tif err := diversify(key2, iv2, divNonce); err != nil {\n\t\t\treturn nil, nil, nil, nil, err\n\t\t}\n\t}\n\n\tif swap {\n\t\totherKey = key2\n\t\tmyKey = key1\n\t\totherIV = iv2\n\t\tmyIV = iv1\n\t} else {\n\t\totherKey = key1\n\t\tmyKey = key2\n\t\totherIV = iv1\n\t\tmyIV = iv2\n\t}\n\n\treturn otherKey, myKey, otherIV, myIV, nil\n}", "func (h *acmeAdminResponder) GetExternalAccountKeys(w http.ResponseWriter, _ *http.Request) {\n\trender.Error(w, admin.NewError(admin.ErrorNotImplementedType, \"this functionality is currently only available in Certificate Manager: https://u.step.sm/cm\"))\n}", "func (el EntityList) DecryptionKeys() (keys []Key) {\n\tfor _, e := range el {\n\t\tfor _, subKey := range e.Subkeys {\n\t\t\tif subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {\n\t\t\t\tkeys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (a *DefaultApiService) ListAPIKeys(consumerId string) (InlineResponse200, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload InlineResponse200\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/consumers/{consumer_id}/key-auth\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"consumer_id\"+\"}\", fmt.Sprintf(\"%v\", consumerId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return successPayload, localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\t\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t \treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (client *Client) DescribeEncryptionKeyListWithOptions(request *DescribeEncryptionKeyListRequest, runtime *util.RuntimeOptions) (_result *DescribeEncryptionKeyListResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"DescribeEncryptionKeyList\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &DescribeEncryptionKeyListResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (t *DIC3) ListKeys(req *ListRequest, reply *ListResponse) error {\n\tvar req2 ListRequest\n\tif req.SourceId == -1 {\n\t\treq2.SourceId = chordid\n\t} else {\n\t\treq2.SourceId = req.SourceId\n\t}\n\tif successor.Chordid == req.SourceId || successor.Chordid == chordid {\n\t\tkeys := make([]string, 1)\n\t\tfor k := range dict3 {\n\t\t\tfound := checkIfPresent(k.KeyA, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, k.KeyA)\n\t\t\t}\n\t\t}\n\t\treply.List = keys\n\t\treply.Err = nil\n\t\treturn nil\n\t} else {\n\t\tclient, err := jsonrpc.Dial(protocol, successor.Address)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"dialing:\", err)\n\t\t}\n\t\tvar reply2 ListResponse\n\t\tRpcCall := client.Go(\"DIC3.ListKeys\", req2, &reply2, nil)\n\t\treplyCall := <-RpcCall.Done\n\t\tif replyCall != nil {\n\t\t}\n\t\tclient.Close()\n\t\tkeys := make([]string, 1)\n\t\tfor k, _ := range dict3 {\n\t\t\tfound := checkIfPresent(k.KeyA, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, k.KeyA)\n\t\t\t}\n\t\t}\n\t\tfor _, j := range reply2.List {\n\t\t\tfound := checkIfPresent(j, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, j)\n\t\t\t}\n\t\t}\n\t\treply.List = keys\n\t\treply.Err = nil\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (svc *SSHKeysService) List(ctx context.Context, prj string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, projectSSHKeysPath(prj), &ret)\n\treturn ret, resp, err\n}", "func GetSSHKeys(username string) string {\n\n\tproviders := map[string]string{\n\t\t\"Github\": \"https://github.com/%s.keys\",\n\t\t\"Gitlab\": \"https://gitlab.com/%s.keys\",\n\t}\n\n\tfoundKeys := \"\"\n\tfor provider, url := range providers {\n\t\turl = fmt.Sprintf(url, username)\n\t\tkeys := getURLContent(url)\n\t\tif len(keys) > 0 {\n\t\t\tfoundKeys += fmt.Sprintf(\"\\n# %s (%s):\\n%s\", username, provider, keys)\n\t\t}\n\t}\n\n\treturn foundKeys\n\n}", "func (*ListAPIKeysRequest) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{16}\n}", "func (privKey PrivKeyEd25519) Bytes() []byte {\n\treturn cdc.MustMarshalBinaryBare(privKey)\n}" ]
[ "0.6310801", "0.621572", "0.5637348", "0.55919635", "0.5549698", "0.55122226", "0.54721636", "0.54239124", "0.5408522", "0.53907734", "0.53089654", "0.53062004", "0.5286327", "0.526129", "0.5254369", "0.52356505", "0.52344084", "0.52311474", "0.5229116", "0.5228397", "0.5198194", "0.5172087", "0.51715577", "0.516691", "0.51412475", "0.5133113", "0.5110844", "0.51060534", "0.5101681", "0.5092248", "0.50909334", "0.5087042", "0.50831753", "0.5080667", "0.5079494", "0.5064647", "0.50627434", "0.5057299", "0.50572276", "0.5033202", "0.5033186", "0.50286293", "0.5026088", "0.5016636", "0.5015597", "0.5011577", "0.49992147", "0.49985114", "0.49944904", "0.49885908", "0.49787754", "0.4975404", "0.49709702", "0.4967132", "0.49602446", "0.4955913", "0.49536964", "0.4951839", "0.4951839", "0.4951508", "0.49502814", "0.49478653", "0.49477258", "0.49468276", "0.49445054", "0.49419236", "0.492914", "0.49250075", "0.49233717", "0.4913716", "0.49117285", "0.4911718", "0.49099833", "0.490266", "0.4901341", "0.48813167", "0.4879185", "0.4876728", "0.48757172", "0.4871522", "0.48690394", "0.4868761", "0.48668435", "0.48650244", "0.4862109", "0.48558825", "0.4852293", "0.48479605", "0.4842556", "0.48409352", "0.48352885", "0.4832936", "0.48273352", "0.48228103", "0.48209178", "0.48183525", "0.48165905", "0.48126373", "0.48053178", "0.48015615" ]
0.75239015
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) BrowseEncryptionKeysExecute(r ApiBrowseEncryptionKeysRequest) (CloudEncryptionKeysPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue CloudEncryptionKeysPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.BrowseEncryptionKeys") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/cloudEncryptionKeys" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.offset != nil { localVarQueryParams.Add("Offset", parameterToString(*r.offset, "")) } if r.limit != nil { localVarQueryParams.Add("Limit", parameterToString(*r.limit, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.7777472", "0.7582237", "0.741292", "0.7358592", "0.7292706", "0.72179556", "0.72150666", "0.7154164", "0.7144244", "0.70236844", "0.6968861", "0.69574517", "0.6857601", "0.68203115", "0.6786843", "0.67499226", "0.6732799", "0.6726702", "0.664588", "0.66373837", "0.66341907", "0.66192603", "0.6618354", "0.65951604", "0.6592189", "0.6544029", "0.65052474", "0.6500035", "0.6499713", "0.6493198", "0.6459492", "0.64537424", "0.64339274", "0.64231", "0.6411837", "0.6354237", "0.6342012", "0.6331562", "0.63293886", "0.63235724", "0.63210624", "0.63129383", "0.63012326", "0.62950426", "0.62711006", "0.6269801", "0.62694305", "0.62559414", "0.62376016", "0.61896044", "0.61866677", "0.6157971", "0.61576515", "0.6157038", "0.61556566", "0.6138981", "0.61365765", "0.61309266", "0.61302364", "0.61298376", "0.6119938", "0.61105776", "0.6102657", "0.6093387", "0.609142", "0.6079346", "0.6078881", "0.6075695", "0.6045966", "0.6045463", "0.60427797", "0.6032737", "0.603158", "0.6027389", "0.60167104", "0.60026646", "0.5987349", "0.5974702", "0.5971437", "0.59703684", "0.5965762", "0.59478134", "0.5939073", "0.59338975", "0.59321105", "0.5925759", "0.5913415", "0.59012485", "0.58960927", "0.5890233", "0.5883923", "0.58764994", "0.5875759", "0.58713603", "0.58534265", "0.5852063", "0.5849181", "0.58465594", "0.5846279", "0.58363706", "0.58326805" ]
0.0
-1
/ CreateAmazonConnection Method for CreateAmazonConnection
func (a *AmazonConnectionsApiService) CreateAmazonConnection(ctx _context.Context) ApiCreateAmazonConnectionRequest { return ApiCreateAmazonConnectionRequest{ ApiService: a, ctx: ctx, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) CreateAmazonConnectionExecute(r ApiCreateAmazonConnectionRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.CreateAmazonConnection\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\tif r.amazonConnectionSpec == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"amazonConnectionSpec is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\t// body params\n\tlocalVarPostBody = r.amazonConnectionSpec\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func NewConnection(secret, access string, r *aws.Region) *Connection {\n\t// TODO a go routine to create a new signature when the date changes?\n\treturn &Connection{defaultClient, aws.NewSignature(secret, access,\n\t\tr, \"glacier\")}\n}", "func awsConnect(i *AwsInfo) *s3.Bucket {\n\tAWSAuth := aws.Auth{\n\t\tAccessKey: i.AccessKey,\n\t\tSecretKey: i.SecretKey,\n\t}\n\tregion := aws.USEast\n\tconnection := s3.New(AWSAuth, region)\n\n\treturn connection.Bucket(i.Bucket)\n}", "func newSqsConn(accessKey string, secretKey string, region aws.Region, queueName string) *sqs.Queue {\n\tauth := aws.Auth{AccessKey: accessKey, SecretKey: secretKey}\n\tclient := sqs.New(auth, region)\n\tqueue, err := client.GetQueue(queueName)\n\tif err != nil {\n\t\tlog.Fatalf(\"SQS connection error: %s\\n\", err)\n\t}\n\tlog.Printf(\"Connected to queue: %s\\n\", queue.Url)\n\treturn queue\n}", "func newConnection(address string, timeout time.Duration) (*Connection, Error) {\n\tnewConn := &Connection{dataBuffer: bufPool.Get().([]byte)}\n\truntime.SetFinalizer(newConn, connectionFinalizer)\n\n\t// don't wait indefinitely\n\tif timeout == 0 {\n\t\ttimeout = 5 * time.Second\n\t}\n\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\tlogger.Logger.Debug(\"Connection to address `%s` failed to establish with error: %s\", address, err.Error())\n\t\treturn nil, errToAerospikeErr(nil, err)\n\t}\n\tnewConn.conn = conn\n\tnewConn.limitReader = &io.LimitedReader{R: conn, N: 0}\n\n\t// set timeout at the last possible moment\n\tif err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil {\n\t\tnewConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn newConn, nil\n}", "func S3NewConn(conf aws.AWSEnvConfig) (*S3, error) {\n\tsess, err := conf.Session()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcli := SDK.New(sess)\n\tsvc := &S3{\n\t\tclient: cli,\n\t\tendpoint: cli.ClientInfo.Endpoint,\n\t\tlogger: log.DefaultLogger,\n\t\tprefix: conf.DefaultPrefix,\n\t\tbuckets: make(map[string]*Bucket),\n\t}\n\treturn svc, nil\n}", "func newConnection(connString string) (*connection, error) {\n\n\tresult := &connection{parameters: make(map[string]string), usePreparedStmts: true}\n\n\tvar err error\n\tresult.connURL, err = url.Parse(connString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.clientPID = os.Getpid()\n\tif client_label := result.connURL.Query().Get(\"client_label\"); client_label != \"\" {\n\t\tresult.sessionID = client_label\n\t} else {\n\t\tresult.sessionID = fmt.Sprintf(\"%s-%s-%d-%d\", driverName, driverVersion, result.clientPID, time.Now().Unix())\n\t}\n\n\t// Read the interpolate flag.\n\tif iFlag := result.connURL.Query().Get(\"use_prepared_statements\"); iFlag != \"\" {\n\t\tresult.usePreparedStmts = iFlag == \"1\"\n\t}\n\n\t// Read Autocommit flag.\n\tif iFlag := result.connURL.Query().Get(\"autocommit\"); iFlag == \"\" || iFlag == \"1\" {\n\t\tresult.autocommit = \"on\"\n\t} else {\n\t\tresult.autocommit = \"off\"\n\t}\n\n\t// Read OAuth access token flag.\n\tresult.oauthaccesstoken = result.connURL.Query().Get(\"oauth_access_token\")\n\n\t// Read connection load balance flag.\n\tloadBalanceFlag := result.connURL.Query().Get(\"connection_load_balance\")\n\n\t// Read connection failover flag.\n\tbackupHostsStr := result.connURL.Query().Get(\"backup_server_node\")\n\tif backupHostsStr == \"\" {\n\t\tresult.connHostsList = []string{result.connURL.Host}\n\t} else {\n\t\t// Parse comma-separated list of backup host-port pairs\n\t\thosts := strings.Split(backupHostsStr, \",\")\n\t\t// Push target host to front of the hosts list\n\t\tresult.connHostsList = append([]string{result.connURL.Host}, hosts...)\n\t}\n\n\t// Read SSL/TLS flag.\n\tsslFlag := strings.ToLower(result.connURL.Query().Get(\"tlsmode\"))\n\tif sslFlag == \"\" {\n\t\tsslFlag = tlsModeNone\n\t}\n\n\tresult.conn, err = result.establishSocketConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load Balancing\n\tif loadBalanceFlag == \"1\" {\n\t\tif err = result.balanceLoad(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif sslFlag != tlsModeNone {\n\t\tif err = result.initializeSSL(sslFlag); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err = result.handshake(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = result.initializeSession(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func createAwsDynamodbConnectGeneric() *promdynamodb.AwsDynamodbConnect {\n\tawsRegion := strings.ReplaceAll(os.Getenv(\"AWS_REGION\"), `\"`, \"\")\n\tawsAccessKeyId := strings.ReplaceAll(os.Getenv(\"AWS_ACCESS_KEY_ID\"), `\"`, \"\")\n\tawsSecretAccessKey := strings.ReplaceAll(os.Getenv(\"AWS_SECRET_ACCESS_KEY\"), `\"`, \"\")\n\tif awsRegion == \"\" || awsAccessKeyId == \"\" || awsSecretAccessKey == \"\" {\n\t\tpanic(\"Please define env AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and optionally AWS_DYNAMODB_ENDPOINT\")\n\t}\n\tcfg := &aws.Config{\n\t\tRegion: aws.String(awsRegion),\n\t\tCredentials: credentials.NewEnvCredentials(),\n\t}\n\tif awsDynamodbEndpoint := strings.ReplaceAll(os.Getenv(\"AWS_DYNAMODB_ENDPOINT\"), `\"`, \"\"); awsDynamodbEndpoint != \"\" {\n\t\tcfg.Endpoint = aws.String(awsDynamodbEndpoint)\n\t\tif strings.HasPrefix(awsDynamodbEndpoint, \"http://\") {\n\t\t\tcfg.DisableSSL = aws.Bool(true)\n\t\t}\n\t}\n\tadc, err := promdynamodb.NewAwsDynamodbConnect(cfg, nil, nil, 10000)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn adc\n}", "func (a *AmazonConnectionsApiService) GetAllAmazonConnections(ctx _context.Context) ApiGetAllAmazonConnectionsRequest {\n\treturn ApiGetAllAmazonConnectionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func NewConnection(username, password, dsn string /*commitMode , pool, twophase bool*/) (\n\tconn Connection, err error) {\n\tconn = Connection{username: username, password: password, dsn: dsn}\n\t/*\n\t\tif pool != nil {\n\t\t\tconn.environment = pool.environment\n\t\t} else\n\t*/\n\tconn.environment, err = NewEnvironment()\n\n\treturn conn, err\n}", "func Connect(c *credentials.Credentials, region string) error {\n\n\tif DynamoTable == \"\" && SearchParam == \"\" && GenericModel == nil{\n\t\treturn &ErrorString{\n\t\t\tReason: \"Injected values are empty or nil\",\n\t\t\tCode: http.StatusBadRequest,\n\t\t}\n\t}\n\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(region),\n\t\tCredentials: c,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDynamoConnection = dynamodb.New(sess)\n\n\treturn nil\n}", "func Connect() *route53.Route53 {\n\tcreds := aws.Creds(os.Getenv(\"AWS_ACCESS_KEY\"), os.Getenv(\"AWS_SECRET_KEY\"), \"\") // HL\n\treturn route53.New(creds, region, nil)\n}", "func (a *AmazonConnectionsApiService) GetAmazonConnectionById(ctx _context.Context, amazonConnectionId string) ApiGetAmazonConnectionByIdRequest {\n\treturn ApiGetAmazonConnectionByIdRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (xmem *XmemNozzle) initializeConnection() (err error) {\n\txmem.Logger().Debugf(\"xmem.config= %v\", xmem.config.connectStr)\n\txmem.Logger().Debugf(\"poolName=%v\", xmem.getPoolName(xmem.config.connectStr))\n\tpool, err := base.ConnPoolMgr().GetOrCreatePool(xmem.getPoolName(xmem.config.connectStr), xmem.config.connectStr, xmem.config.bucketName, xmem.config.password, base.DefaultConnectionSize)\n\tif err == nil {\n\t\txmem.memClient, err = pool.Get()\n\t}\n\treturn err\n}", "func NewConnection(connectionString string) (*Connection, error) {\n\tadabasID := NewAdabasID()\n\treturn NewConnectionID(connectionString, adabasID)\n}", "func newConnection(address string, timeout time.Duration) (*Connection, error) {\n\tnewConn := &Connection{dataBuffer: bufPool.Get().([]byte)}\n\truntime.SetFinalizer(newConn, connectionFinalizer)\n\n\t// don't wait indefinitely\n\tif timeout == 0 {\n\t\ttimeout = 5 * time.Second\n\t}\n\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\tlogger.Logger.Debug(\"Connection to address `%s` failed to establish with error: %s\", address, err.Error())\n\t\treturn nil, errToTimeoutErr(nil, err)\n\t}\n\tnewConn.conn = conn\n\tnewConn.limitReader = &io.LimitedReader{R: conn, N: 0}\n\n\t// set timeout at the last possible moment\n\tif err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil {\n\t\tnewConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn newConn, nil\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var bucket NewBucket\n err = decoder.Decode(&bucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n\n // Add the necessary headers for Metadata Search and Access During Outage\n createBucketHeaders := map[string][]string{}\n createBucketHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n createBucketHeaders[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n createBucketHeaders[\"x-emc-metadata-search\"] = []string{\"ObjectName,x-amz-meta-image-width;Integer,x-amz-meta-image-height;Integer,x-amz-meta-gps-latitude;Decimal,x-amz-meta-gps-longitude;Decimal\"}\n\n createBucketResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/\", createBucketHeaders, \"\")\n\n // Enable CORS after the bucket creation to allow the web browser to send requests directly to ECS\n if createBucketResponse.Code == 200 {\n enableBucketCorsHeaders := map[string][]string{}\n enableBucketCorsHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n corsConfiguration := `\n <CORSConfiguration>\n <CORSRule>\n <AllowedOrigin>*</AllowedOrigin>\n <AllowedHeader>*</AllowedHeader>\n <ExposeHeader>x-amz-meta-image-width</ExposeHeader>\n <ExposeHeader>x-amz-meta-image-height</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-latitude</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-longitude</ExposeHeader>\n <AllowedMethod>HEAD</AllowedMethod>\n <AllowedMethod>GET</AllowedMethod>\n <AllowedMethod>PUT</AllowedMethod>\n <AllowedMethod>POST</AllowedMethod>\n <AllowedMethod>DELETE</AllowedMethod>\n </CORSRule>\n </CORSConfiguration>\n `\n enableBucketCorsResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/?cors\", enableBucketCorsHeaders, corsConfiguration)\n if enableBucketCorsResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, struct {\n CorsConfiguration string `json:\"cors_configuration\"`\n Bucket string `json:\"bucket\"`\n } {\n CorsConfiguration: corsConfiguration,\n Bucket: bucket.Name,\n })\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket created, but CORS can't be enabled\"}\n }\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket can't be created\"}\n }\n return nil\n}", "func (c *Connection) Connect() error {\n\tauth, err := aws.EnvAuth()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Auth = auth\n\tc.Region = aws.EUWest\n\treturn nil\n}", "func createSession(accessKeyId string, secretAccessKey string, profileName string) *session.Session {\n return session.Must(session.NewSessionWithOptions(session.Options{\n Config: aws.Config{\n Region: aws.String(\"eu-west-1\"),\n Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, \"\"),\n },\n Profile: profileName,\n }))\n}", "func NewConnection(ctx *pulumi.Context,\n\tname string, args *ConnectionArgs, opts ...pulumi.ResourceOption) (*Connection, error) {\n\tif args == nil || args.CloudSql == nil {\n\t\treturn nil, errors.New(\"missing required argument 'CloudSql'\")\n\t}\n\tif args == nil {\n\t\targs = &ConnectionArgs{}\n\t}\n\tvar resource Connection\n\terr := ctx.RegisterResource(\"gcp:bigquery/connection:Connection\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func Create(c *gin.Context) {\n\tlogger := correlationid.LogrusLogger(common.Log, c)\n\tlogger.Info(\"creating bucket\")\n\n\tvar request api.CreateBucketRequest\n\tif err := c.ShouldBindJSON(&request); err != nil {\n\t\terr = errors.WrapIf(err, \"could not parse request\")\n\t\tcommon.ErrorHandler.Handle(err)\n\t\tcommon.ErrorResponse(c, err)\n\t\treturn\n\t}\n\n\torg := auth.GetCurrentOrganization(c.Request)\n\n\tif len(request.Location) == 0 && (request.Cloud == providers.Amazon) {\n\t\t// location field is empty in request, get bucket location\n\t\tlocation, err := common.GetBucketLocation(request.Cloud, request.BucketName, request.SecretID, org.ID, logger)\n\t\tif err != nil {\n\t\t\terr = errors.WrapIfWithDetails(err, \"failed to get bucket region\", \"bucket\", request.BucketName)\n\t\t\tcommon.ErrorHandler.Handle(err)\n\t\t\tcommon.ErrorResponse(c, err)\n\t\t\treturn\n\t\t}\n\n\t\trequest.Location = location\n\t}\n\n\tbs := ark.BucketsServiceFactory(org, global.DB(), logger)\n\n\t_, err := bs.GetByRequest(api.FindBucketRequest{\n\t\tCloud: request.Cloud,\n\t\tBucketName: request.BucketName,\n\t\tLocation: request.Location,\n\t})\n\tif err == nil {\n\t\terr = errors.New(\"bucket already exists\")\n\t}\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\terr = errors.WrapIf(err, \"could not create bucket\")\n\t\tcommon.ErrorHandler.Handle(err)\n\t\tcommon.ErrorResponse(c, err)\n\t\treturn\n\t}\n\n\tbucket, err := bs.FindOrCreateBucket(&api.CreateBucketRequest{\n\t\tCloud: request.Cloud,\n\t\tBucketName: request.BucketName,\n\t\tLocation: request.Location,\n\t\tSecretID: request.SecretID,\n\t})\n\tif err != nil {\n\t\terr = errors.WrapIf(err, \"could not persist bucket\")\n\t\tcommon.ErrorHandler.Handle(err)\n\t\tcommon.ErrorResponse(c, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, bucket.ConvertModelToEntity())\n}", "func New(awsConfig *aws.Config) *Client {\n\tctx := aws.BackgroundContext()\n\tsess := session.Must(session.NewSession(awsConfig))\n\tiam := iam.New(sess)\n\troute53 := route53.New(sess)\n\tec2 := ec2.New(sess)\n\treturn &Client{\n\t\tIAM: iam,\n\t\tRoute53: route53,\n\t\tEC2: ec2,\n\t\tContext: ctx,\n\t}\n}", "func InitDynamoConnection(id, secret, tableName string) (DynamoConnection, error) {\n\tvar db DynamoConnection\n\n\tdb.credentials = credentials.NewStaticCredentials(id, secret, \"\")\n\tdb.tableName = tableName\n\n\tdb.initialized = true\n\n\treturn db, nil\n}", "func init() {\n\tdebugMode = (os.Getenv(\"DEBUG\") != \"\")\n\n\tarnPattern = regexp.MustCompile(\"\\\\Aarn:aws:sts::\\\\d+:assumed-role/([a-z0-9_-]+)/(i-[0-9a-f]+)\\\\z\")\n\n\tcaKeyBucket, caKeyPath, err := parseS3URI(os.Getenv(\"CA_KEY_URI\"))\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"CA_KEY_URI: %w\", err)\n\t\treturn\n\t}\n\n\tob, op, err := parseS3URI(os.Getenv(\"OUTPUT_URI_PREFIX\"))\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"OUTPUT_URI_PREFIX: %w\", err)\n\t\treturn\n\t}\n\toutBucket = ob\n\toutPathPrefix = op\n\n\taws, err := newAwsClient()\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"initializing aws client: %w\", err)\n\t\treturn\n\t}\n\tawsCli = aws\n\n\tcaKey, err := awsCli.getS3Object(caKeyBucket, caKeyPath)\n\tif err != nil {\n\t\tfmt.Printf(\"error getting CA key, bucket=%q path=%q\\n\", caKeyBucket, caKeyPath)\n\t\tinitError = fmt.Errorf(\"getting caKey: %w\", err)\n\t\treturn\n\t}\n\n\tsigner, err = NewSigner(caKey)\n\tif err != nil {\n\t\tinitError = fmt.Errorf(\"creating signer: %w\", err)\n\t\treturn\n\t}\n\n\tif debugMode {\n\t\tfmt.Printf(\"init completed\")\n\t}\n}", "func CreateConnection(host string, port int) *RabbitmqConnection {\n\trc := &RabbitmqConnection{Host: host, Port: port}\n\trc.connectToRabbitMQ()\n\treturn rc\n}", "func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lambdaconn\n\n\tfunctionName := d.Get(\"function_name\").(string)\n\treservedConcurrentExecutions := d.Get(\"reserved_concurrent_executions\").(int)\n\tiamRole := d.Get(\"role\").(string)\n\n\tlog.Printf(\"[DEBUG] Creating Lambda Function %s with role %s\", functionName, iamRole)\n\n\tfilename, hasFilename := d.GetOk(\"filename\")\n\ts3Bucket, bucketOk := d.GetOk(\"s3_bucket\")\n\ts3Key, keyOk := d.GetOk(\"s3_key\")\n\ts3ObjectVersion, versionOk := d.GetOk(\"s3_object_version\")\n\n\tif !hasFilename && !bucketOk && !keyOk && !versionOk {\n\t\treturn errors.New(\"filename or s3_* attributes must be set\")\n\t}\n\n\tvar functionCode *lambda.FunctionCode\n\tif hasFilename {\n\t\t// Grab an exclusive lock so that we're only reading one function into\n\t\t// memory at a time.\n\t\t// See https://github.com/hashicorp/terraform/issues/9364\n\t\tawsMutexKV.Lock(awsMutexLambdaKey)\n\t\tdefer awsMutexKV.Unlock(awsMutexLambdaKey)\n\t\tfile, err := loadFileContent(filename.(string))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to load %q: %s\", filename.(string), err)\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tZipFile: file,\n\t\t}\n\t} else {\n\t\tif !bucketOk || !keyOk {\n\t\t\treturn errors.New(\"s3_bucket and s3_key must all be set while using S3 code source\")\n\t\t}\n\t\tfunctionCode = &lambda.FunctionCode{\n\t\t\tS3Bucket: aws.String(s3Bucket.(string)),\n\t\t\tS3Key: aws.String(s3Key.(string)),\n\t\t}\n\t\tif versionOk {\n\t\t\tfunctionCode.S3ObjectVersion = aws.String(s3ObjectVersion.(string))\n\t\t}\n\t}\n\n\tparams := &lambda.CreateFunctionInput{\n\t\tCode: functionCode,\n\t\tDescription: aws.String(d.Get(\"description\").(string)),\n\t\tFunctionName: aws.String(functionName),\n\t\tHandler: aws.String(d.Get(\"handler\").(string)),\n\t\tMemorySize: aws.Int64(int64(d.Get(\"memory_size\").(int))),\n\t\tRole: aws.String(iamRole),\n\t\tRuntime: aws.String(d.Get(\"runtime\").(string)),\n\t\tTimeout: aws.Int64(int64(d.Get(\"timeout\").(int))),\n\t\tPublish: aws.Bool(d.Get(\"publish\").(bool)),\n\t}\n\n\tif v, ok := d.GetOk(\"dead_letter_config\"); ok {\n\t\tdlcMaps := v.([]interface{})\n\t\tif len(dlcMaps) == 1 { // Schema guarantees either 0 or 1\n\t\t\t// Prevent panic on nil dead_letter_config. See GH-14961\n\t\t\tif dlcMaps[0] == nil {\n\t\t\t\treturn fmt.Errorf(\"Nil dead_letter_config supplied for function: %s\", functionName)\n\t\t\t}\n\t\t\tdlcMap := dlcMaps[0].(map[string]interface{})\n\t\t\tparams.DeadLetterConfig = &lambda.DeadLetterConfig{\n\t\t\t\tTargetArn: aws.String(dlcMap[\"target_arn\"].(string)),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"vpc_config\"); ok {\n\n\t\tconfigs := v.([]interface{})\n\t\tconfig, ok := configs[0].(map[string]interface{})\n\n\t\tif !ok {\n\t\t\treturn errors.New(\"vpc_config is <nil>\")\n\t\t}\n\n\t\tif config != nil {\n\t\t\tvar subnetIds []*string\n\t\t\tfor _, id := range config[\"subnet_ids\"].(*schema.Set).List() {\n\t\t\t\tsubnetIds = append(subnetIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tvar securityGroupIds []*string\n\t\t\tfor _, id := range config[\"security_group_ids\"].(*schema.Set).List() {\n\t\t\t\tsecurityGroupIds = append(securityGroupIds, aws.String(id.(string)))\n\t\t\t}\n\n\t\t\tparams.VpcConfig = &lambda.VpcConfig{\n\t\t\t\tSubnetIds: subnetIds,\n\t\t\t\tSecurityGroupIds: securityGroupIds,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"tracing_config\"); ok {\n\t\ttracingConfig := v.([]interface{})\n\t\ttracing := tracingConfig[0].(map[string]interface{})\n\t\tparams.TracingConfig = &lambda.TracingConfig{\n\t\t\tMode: aws.String(tracing[\"mode\"].(string)),\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"environment\"); ok {\n\t\tenvironments := v.([]interface{})\n\t\tenvironment, ok := environments[0].(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn errors.New(\"At least one field is expected inside environment\")\n\t\t}\n\n\t\tif environmentVariables, ok := environment[\"variables\"]; ok {\n\t\t\tvariables := readEnvironmentVariables(environmentVariables.(map[string]interface{}))\n\n\t\t\tparams.Environment = &lambda.Environment{\n\t\t\t\tVariables: aws.StringMap(variables),\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := d.GetOk(\"kms_key_arn\"); ok {\n\t\tparams.KMSKeyArn = aws.String(v.(string))\n\t}\n\n\tif v, exists := d.GetOk(\"tags\"); exists {\n\t\tparams.Tags = tagsFromMapGeneric(v.(map[string]interface{}))\n\t}\n\n\t// IAM profiles can take ~10 seconds to propagate in AWS:\n\t// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#launch-instance-with-role-console\n\t// Error creating Lambda function: InvalidParameterValueException: The role defined for the task cannot be assumed by Lambda.\n\terr := resource.Retry(10*time.Minute, func() *resource.RetryError {\n\t\t_, err := conn.CreateFunction(params)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[DEBUG] Error creating Lambda Function: %s\", err)\n\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The role defined for the function cannot be assumed by Lambda\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"The provided execution role does not have permissions\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif isAWSErr(err, \"InvalidParameterValueException\", \"Your request has been throttled by EC2\") {\n\t\t\t\tlog.Printf(\"[DEBUG] Received %s, retrying CreateFunction\", err)\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Lambda function: %s\", err)\n\t}\n\n\tif reservedConcurrentExecutions > 0 {\n\n\t\tlog.Printf(\"[DEBUG] Setting Concurrency to %d for the Lambda Function %s\", reservedConcurrentExecutions, functionName)\n\n\t\tconcurrencyParams := &lambda.PutFunctionConcurrencyInput{\n\t\t\tFunctionName: aws.String(functionName),\n\t\t\tReservedConcurrentExecutions: aws.Int64(int64(reservedConcurrentExecutions)),\n\t\t}\n\n\t\t_, err := conn.PutFunctionConcurrency(concurrencyParams)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error setting concurrency for Lambda %s: %s\", functionName, err)\n\t\t}\n\t}\n\n\td.SetId(d.Get(\"function_name\").(string))\n\n\treturn resourceAwsLambdaFunctionRead(d, meta)\n}", "func newNetwork(cfg *config.Network, c *ec2.EC2) (*network, error) {\n\tlog.Debug(\"Initializing AWS Network\")\n\tn := &network{\n\t\tResources: resource.NewResources(),\n\t\tNetwork: cfg,\n\t\tec2: c,\n\t}\n\n\tvpc, err := newVpc(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.vpc = vpc\n\tn.Append(vpc)\n\n\trouteTables, err := newRouteTables(c, n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.routeTables = routeTables\n\tn.Append(routeTables)\n\n\tinternetGateway, err := newInternetGateway(c, n, \"public\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.internetGateway = internetGateway\n\tn.Append(internetGateway)\n\n\t// Load the vpc since it is needed for the caches.\n\terr = n.vpc.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn.subnetCache, err = newSubnetCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn.secgroupCache, err = newSecurityGroupCache(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn n, nil\n}", "func (s *S3Store) Connect(accessID, secretKey string, region string, endpoints ...string) (err error) {\n\tif len(endpoints) > 0 {\n\t\ts.endpoint = endpoints[0]\n\t}\n\ts.region = region\n\ts.sess, err = session.NewSession(&aws.Config{\n\t\tEndpoint: aws.String(s.endpoint),\n\t\tRegion: aws.String(s.region),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tCredentials: credentials.NewStaticCredentials(accessID, secretKey, \"\"),\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\ts.svc = s3.New(s.sess)\n\treturn\n}", "func (rm *resourceManager) sdkCreate(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\tinput, err := rm.newCreateRequestPayload(ctx, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.CreateVpcPeeringConnectionWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"CREATE\", \"CreateVpcPeeringConnection\", respErr)\n\tif respErr != nil {\n\t\treturn nil, respErr\n\t}\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.VpcPeeringConnection.AccepterVpcInfo != nil {\n\t\tf0 := &svcapitypes.VPCPeeringConnectionVPCInfo{}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.CidrBlock != nil {\n\t\t\tf0.CIDRBlock = resp.VpcPeeringConnection.AccepterVpcInfo.CidrBlock\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.CidrBlockSet != nil {\n\t\t\tf0f1 := []*svcapitypes.CIDRBlock{}\n\t\t\tfor _, f0f1iter := range resp.VpcPeeringConnection.AccepterVpcInfo.CidrBlockSet {\n\t\t\t\tf0f1elem := &svcapitypes.CIDRBlock{}\n\t\t\t\tif f0f1iter.CidrBlock != nil {\n\t\t\t\t\tf0f1elem.CIDRBlock = f0f1iter.CidrBlock\n\t\t\t\t}\n\t\t\t\tf0f1 = append(f0f1, f0f1elem)\n\t\t\t}\n\t\t\tf0.CIDRBlockSet = f0f1\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.Ipv6CidrBlockSet != nil {\n\t\t\tf0f2 := []*svcapitypes.IPv6CIDRBlock{}\n\t\t\tfor _, f0f2iter := range resp.VpcPeeringConnection.AccepterVpcInfo.Ipv6CidrBlockSet {\n\t\t\t\tf0f2elem := &svcapitypes.IPv6CIDRBlock{}\n\t\t\t\tif f0f2iter.Ipv6CidrBlock != nil {\n\t\t\t\t\tf0f2elem.IPv6CIDRBlock = f0f2iter.Ipv6CidrBlock\n\t\t\t\t}\n\t\t\t\tf0f2 = append(f0f2, f0f2elem)\n\t\t\t}\n\t\t\tf0.IPv6CIDRBlockSet = f0f2\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.OwnerId != nil {\n\t\t\tf0.OwnerID = resp.VpcPeeringConnection.AccepterVpcInfo.OwnerId\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions != nil {\n\t\t\tf0f4 := &svcapitypes.VPCPeeringConnectionOptionsDescription{}\n\t\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowDnsResolutionFromRemoteVpc != nil {\n\t\t\t\tf0f4.AllowDNSResolutionFromRemoteVPC = resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowDnsResolutionFromRemoteVpc\n\t\t\t}\n\t\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowEgressFromLocalClassicLinkToRemoteVpc != nil {\n\t\t\t\tf0f4.AllowEgressFromLocalClassicLinkToRemoteVPC = resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowEgressFromLocalClassicLinkToRemoteVpc\n\t\t\t}\n\t\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowEgressFromLocalVpcToRemoteClassicLink != nil {\n\t\t\t\tf0f4.AllowEgressFromLocalVPCToRemoteClassicLink = resp.VpcPeeringConnection.AccepterVpcInfo.PeeringOptions.AllowEgressFromLocalVpcToRemoteClassicLink\n\t\t\t}\n\t\t\tf0.PeeringOptions = f0f4\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.Region != nil {\n\t\t\tf0.Region = resp.VpcPeeringConnection.AccepterVpcInfo.Region\n\t\t}\n\t\tif resp.VpcPeeringConnection.AccepterVpcInfo.VpcId != nil {\n\t\t\tf0.VPCID = resp.VpcPeeringConnection.AccepterVpcInfo.VpcId\n\t\t}\n\t\tko.Status.AccepterVPCInfo = f0\n\t}\n\tif resp.VpcPeeringConnection.ExpirationTime != nil {\n\t\tko.Status.ExpirationTime = &metav1.Time{*resp.VpcPeeringConnection.ExpirationTime}\n\t}\n\tif resp.VpcPeeringConnection.RequesterVpcInfo != nil {\n\t\tf2 := &svcapitypes.VPCPeeringConnectionVPCInfo{}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.CidrBlock != nil {\n\t\t\tf2.CIDRBlock = resp.VpcPeeringConnection.RequesterVpcInfo.CidrBlock\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.CidrBlockSet != nil {\n\t\t\tf2f1 := []*svcapitypes.CIDRBlock{}\n\t\t\tfor _, f2f1iter := range resp.VpcPeeringConnection.RequesterVpcInfo.CidrBlockSet {\n\t\t\t\tf2f1elem := &svcapitypes.CIDRBlock{}\n\t\t\t\tif f2f1iter.CidrBlock != nil {\n\t\t\t\t\tf2f1elem.CIDRBlock = f2f1iter.CidrBlock\n\t\t\t\t}\n\t\t\t\tf2f1 = append(f2f1, f2f1elem)\n\t\t\t}\n\t\t\tf2.CIDRBlockSet = f2f1\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.Ipv6CidrBlockSet != nil {\n\t\t\tf2f2 := []*svcapitypes.IPv6CIDRBlock{}\n\t\t\tfor _, f2f2iter := range resp.VpcPeeringConnection.RequesterVpcInfo.Ipv6CidrBlockSet {\n\t\t\t\tf2f2elem := &svcapitypes.IPv6CIDRBlock{}\n\t\t\t\tif f2f2iter.Ipv6CidrBlock != nil {\n\t\t\t\t\tf2f2elem.IPv6CIDRBlock = f2f2iter.Ipv6CidrBlock\n\t\t\t\t}\n\t\t\t\tf2f2 = append(f2f2, f2f2elem)\n\t\t\t}\n\t\t\tf2.IPv6CIDRBlockSet = f2f2\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.OwnerId != nil {\n\t\t\tf2.OwnerID = resp.VpcPeeringConnection.RequesterVpcInfo.OwnerId\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions != nil {\n\t\t\tf2f4 := &svcapitypes.VPCPeeringConnectionOptionsDescription{}\n\t\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowDnsResolutionFromRemoteVpc != nil {\n\t\t\t\tf2f4.AllowDNSResolutionFromRemoteVPC = resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowDnsResolutionFromRemoteVpc\n\t\t\t}\n\t\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowEgressFromLocalClassicLinkToRemoteVpc != nil {\n\t\t\t\tf2f4.AllowEgressFromLocalClassicLinkToRemoteVPC = resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowEgressFromLocalClassicLinkToRemoteVpc\n\t\t\t}\n\t\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowEgressFromLocalVpcToRemoteClassicLink != nil {\n\t\t\t\tf2f4.AllowEgressFromLocalVPCToRemoteClassicLink = resp.VpcPeeringConnection.RequesterVpcInfo.PeeringOptions.AllowEgressFromLocalVpcToRemoteClassicLink\n\t\t\t}\n\t\t\tf2.PeeringOptions = f2f4\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.Region != nil {\n\t\t\tf2.Region = resp.VpcPeeringConnection.RequesterVpcInfo.Region\n\t\t}\n\t\tif resp.VpcPeeringConnection.RequesterVpcInfo.VpcId != nil {\n\t\t\tf2.VPCID = resp.VpcPeeringConnection.RequesterVpcInfo.VpcId\n\t\t}\n\t\tko.Status.RequesterVPCInfo = f2\n\t}\n\tif resp.VpcPeeringConnection.Status != nil {\n\t\tf3 := &svcapitypes.VPCPeeringConnectionStateReason{}\n\t\tif resp.VpcPeeringConnection.Status.Code != nil {\n\t\t\tf3.Code = resp.VpcPeeringConnection.Status.Code\n\t\t}\n\t\tif resp.VpcPeeringConnection.Status.Message != nil {\n\t\t\tf3.Message = resp.VpcPeeringConnection.Status.Message\n\t\t}\n\t\tko.Status.Status = f3\n\t}\n\tif resp.VpcPeeringConnection.Tags != nil {\n\t\tf4 := []*svcapitypes.Tag{}\n\t\tfor _, f4iter := range resp.VpcPeeringConnection.Tags {\n\t\t\tf4elem := &svcapitypes.Tag{}\n\t\t\tif f4iter.Key != nil {\n\t\t\t\tf4elem.Key = f4iter.Key\n\t\t\t}\n\t\t\tif f4iter.Value != nil {\n\t\t\t\tf4elem.Value = f4iter.Value\n\t\t\t}\n\t\t\tf4 = append(f4, f4elem)\n\t\t}\n\t\tko.Status.Tags = f4\n\t}\n\tif resp.VpcPeeringConnection.VpcPeeringConnectionId != nil {\n\t\tko.Status.VPCPeeringConnectionID = resp.VpcPeeringConnection.VpcPeeringConnectionId\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\treturn &resource{ko}, nil\n}", "func New(topicARN string, opts ...Option) (*Transport, error) {\n\tsess, err := session.NewSession(&aws.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Transport{\n\t\tClient: _sns.New(sess),\n\t\tTopicARN: topicARN,\n\t}\n\tif err := t.applyOptions(opts...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}", "func (a *AmazonConnectionsApiService) GetAmazonConnectionByIdExecute(r ApiGetAmazonConnectionByIdRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.GetAmazonConnectionById\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *AmazonConnectionsApiService) DeleteAmazonConnection(ctx _context.Context, amazonConnectionId string) ApiDeleteAmazonConnectionRequest {\n\treturn ApiDeleteAmazonConnectionRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (h *VPCPeeringConnectionsHandler) Create(\n\tproject string,\n\tvpcID string,\n\treq CreateVPCPeeringConnectionRequest,\n) (*VPCPeeringConnection, error) {\n\tpath := buildPath(\"project\", project, \"vpcs\", vpcID, \"peering-connections\")\n\trsp, err := h.client.doPostRequest(path, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response *VPCPeeringConnection\n\tif err := json.Unmarshal(rsp, &response); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func newConnection(c net.Conn) *connection {\n\treturn &connection{\n\t\tc: c,\n\t}\n}", "func (h *Handler) InitObjectStoreConnection(endpoint, accessKeyID, secretAccessKey string) error {\n\tklog.Info(\"Preparing S3 settings\")\n\n\tcfg, err := external.LoadDefaultAWSConfig()\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to load aws config. error: \", err)\n\t\treturn err\n\t}\n\t// aws client report error without minio\n\tcfg.Region = \"minio\"\n\n\tdefaultResolver := endpoints.NewDefaultResolver()\n\ts3CustResolverFn := func(service, region string) (aws.Endpoint, error) {\n\t\tif service == \"s3\" {\n\t\t\treturn aws.Endpoint{\n\t\t\t\tURL: endpoint,\n\t\t\t}, nil\n\t\t}\n\n\t\treturn defaultResolver.ResolveEndpoint(service, region)\n\t}\n\n\tcfg.EndpointResolver = aws.EndpointResolverFunc(s3CustResolverFn)\n\tcfg.Credentials = &credentialProvider{\n\t\tAccessKeyID: accessKeyID,\n\t\tSecretAccessKey: secretAccessKey,\n\t}\n\n\th.Client = s3.New(cfg)\n\tif h.Client == nil {\n\t\tklog.Error(\"Failed to connect to s3 service\")\n\t\treturn err\n\t}\n\n\th.Client.ForcePathStyle = true\n\n\tklog.V(2).Info(\"S3 configured \")\n\n\treturn nil\n}", "func (f *IBMPICloudConnectionClient) Create(body *models.CloudConnectionCreate, powerinstanceid string) (*models.CloudConnection, *models.CloudConnectionCreateResponse, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsPostParamsWithTimeout(helpers.PICreateTimeOut).WithCloudInstanceID(powerinstanceid).WithBody(body)\n\tpostok, postcreated, postAccepted, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsPost(params, ibmpisession.NewAuth(f.session, powerinstanceid))\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(errors.CreateCloudConnectionOperationFailed, powerinstanceid, err)\n\t}\n\tif postok != nil {\n\t\treturn postok.Payload, nil, nil\n\t}\n\tif postcreated != nil {\n\t\treturn postcreated.Payload, nil, nil\n\t}\n\tif postAccepted != nil {\n\t\treturn nil, postAccepted.Payload, nil\n\t}\n\treturn nil, nil, nil\n}", "func (app *App) Amazon() *amazon.Client {\n\tclient := app.AmazonClients[currentClient]\n\tcurrentClient++\n\tapp.Log.Printf(\"Using Amazon Client %d of %d\", currentClient, len(app.AmazonClients))\n\tif currentClient == len(app.AmazonClients) {\n\t\tcurrentClient = 0\n\t}\n\treturn client\n}", "func (f *IBMPICloudConnectionClient) Create(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsPostParams, powerinstanceid string) (*models.CloudConnection, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsPostParamsWithTimeout(postTimeOut).WithCloudInstanceID(powerinstanceid).WithBody(pclouddef.Body)\n\tpostok, postcreated, err, _ := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsPost(params, ibmpisession.NewAuth(f.session, powerinstanceid))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create cloud connection %s\", err)\n\t}\n\tif postok != nil {\n\t\treturn postok.Payload, nil\n\t}\n\tif postcreated != nil {\n\t\treturn postcreated.Payload, nil\n\t}\n\treturn nil, nil\n}", "func NewConnectionID(connectionString string, adabasID *ID) (connection *Connection, err error) {\n\tonce.Do(onceBody)\n\tparts := strings.Split(connectionString, \";\")\n\tif parts[0] != \"acj\" && parts[0] != \"ada\" {\n\t\treturn nil, adatypes.NewGenericError(51)\n\t}\n\tvar adabasToData *Adabas\n\tvar adabasToMap *Adabas\n\tvar mapName string\n\tvar adabasMap *Map\n\n\tvar repositoryParameter [][]string\n\tvar repository *Repository\n\tadatypes.Central.Log.Debugf(\"New connection to %s\", connectionString)\n\tfor _, p := range parts {\n\t\tadatypes.Central.Log.Debugf(\"Work on %s\", p)\n\t\tswitch {\n\t\tcase p == \"acj\" || p == \"ada\":\n\t\tcase strings.HasPrefix(p, \"target=\"):\n\t\t\ttarget := strings.Split(parts[1], \"=\")\n\t\t\tadatypes.Central.Log.Debugf(\"Connection to target : %s\", target[1])\n\t\t\turl, err := NewURL(target[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tadabasToData = adabasID.getAdabas(url)\n\t\tcase strings.HasPrefix(p, \"map\"):\n\t\t\tif strings.Contains(p, \"=\") {\n\t\t\t\tmaps := strings.Split(parts[1], \"=\")\n\t\t\t\tadatypes.Central.Log.Debugf(\"Connection to map : %v\", maps)\n\t\t\t\tmapName = maps[1]\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"inmap\"):\n\t\t\tif strings.Contains(p, \"=\") {\n\t\t\t\tmaps := strings.Split(parts[1], \"=\")\n\t\t\t\tadatypes.Central.Log.Debugf(\"Connection to map : %v\", maps)\n\t\t\t\t// mapName = inmapMapName\n\t\t\t\tadabasMap = NewAdabasMap(inmapMapName)\n\t\t\t\tref := strings.Split(maps[1], \",\")\n\t\t\t\turl, err := NewURL(ref[0])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tadabasMap.Data = &DatabaseURL{URL: *url}\n\t\t\t\tfnr := 0\n\t\t\t\tif len(ref) > 1 {\n\t\t\t\t\tfnr, err = strconv.Atoi(ref[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif fnr < 0 || fnr > 32000 {\n\t\t\t\t\treturn nil, adatypes.NewGenericError(116, fnr)\n\t\t\t\t}\n\t\t\t\tadabasMap.Data.Fnr = Fnr(fnr)\n\t\t\t\tadatypes.Central.Log.Debugf(\"inmap %s,%d\", url, fnr)\n\t\t\t\tadabasToData = adabasID.getAdabas(url)\n\t\t\t\t// NewAdabas(url, adabasID)\n\t\t\t\t// if err != nil {\n\t\t\t\t// \treturn nil, err\n\t\t\t\t// }\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"config=\"):\n\t\t\te := strings.Index(p, \"]\")\n\t\t\ta := strings.Index(p, \"[\") + 1\n\t\t\tconfig := p[a:e]\n\t\t\tre := regexp.MustCompile(`(?m)([^,]*),([[:digit:]]*)\\|?`)\n\t\t\trr := re.FindAllStringSubmatch(config, 10)\n\t\t\tfor _, r1 := range rr {\n\t\t\t\tvar r = []string{r1[1], r1[2]}\n\t\t\t\trepositoryParameter = append(repositoryParameter, r)\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"auth=\"):\n\t\t\tx := strings.Index(p, \",\")\n\t\t\tif x != -1 {\n\t\t\t\tx++\n\t\t\t\terr := parseAuth(adabasID, p[x:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, adatypes.NewGenericError(84, p)\n\t\t}\n\t}\n\n\tif len(repositoryParameter) > 0 {\n\t\tfor _, r := range repositoryParameter {\n\t\t\tadatypes.Central.Log.Debugf(\"Add repository search of dbid=%s fnr=%s\", r[0], r[1])\n\t\t\tfnr, serr := strconv.Atoi(r[1])\n\t\t\tif serr != nil {\n\t\t\t\treturn nil, serr\n\t\t\t}\n\t\t\tif fnr < 0 || fnr > 32000 {\n\t\t\t\treturn nil, adatypes.NewGenericError(116, fnr)\n\t\t\t}\n\t\t\turl, err := NewURL(r[0])\n\t\t\t//NewAdabas(r[0], adabasID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tadabasToMap = adabasID.getAdabas(url)\n\t\t\tadatypes.Central.Log.Debugf(\"Created adabas reference\")\n\t\t\trepository = NewMapRepository(adabasToMap.URL, Fnr(fnr))\n\t\t\tadatypes.Central.Log.Debugf(\"Created repository\")\n\t\t}\n\t} else {\n\t\t// TODO check id\n\t\tif adabasToData == nil {\n\t\t\tadabasToData, _ = NewAdabas(1, adabasID)\n\t\t}\n\t\tadabasToMap = adabasToData\n\t}\n\n\tconnection = &Connection{adabasToData: adabasToData, ID: adabasID,\n\t\tadabasToMap: adabasToMap, adabasMap: adabasMap, repository: repository}\n\tif mapName != \"\" {\n\t\terr = connection.searchRepository(adabasID, repository, mapName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tadatypes.Central.Log.Debugf(\"Ready created connection handle %s\", connection.String())\n\treturn\n}", "func CreateConnection(brkrAddress string) (*kafka.AdminClient, error) {\n\treturn kafka.NewAdminClient(&kafka.ConfigMap{\"bootstrap.servers\": brkrAddress})\n}", "func newAWSCommand() *cobra.Command {\n\tvar (\n\t\tclusterName string\n\t\troleARN string\n\t)\n\tvar command = &cobra.Command{\n\t\tUse: \"aws\",\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tctx := c.Context()\n\n\t\t\tpresignedURLString, err := getSignedRequestWithRetry(ctx, time.Minute, 5*time.Second, clusterName, roleARN, getSignedRequest)\n\t\t\terrors.CheckError(err)\n\t\t\ttoken := v1Prefix + base64.RawURLEncoding.EncodeToString([]byte(presignedURLString))\n\t\t\t// Set token expiration to 1 minute before the presigned URL expires for some cushion\n\t\t\ttokenExpiration := time.Now().Local().Add(presignedURLExpiration - 1*time.Minute)\n\t\t\t_, _ = fmt.Fprint(os.Stdout, formatJSON(token, tokenExpiration))\n\t\t},\n\t}\n\tcommand.Flags().StringVar(&clusterName, \"cluster-name\", \"\", \"AWS Cluster name\")\n\tcommand.Flags().StringVar(&roleARN, \"role-arn\", \"\", \"AWS Role ARN\")\n\treturn command\n}", "func NewConnection(cycle int) (Connection, error){\n return NewConnectionToURLS(cycle, os.Getenv(\"DISQUE_NODES\"))\n}", "func (p *AWS) Initialize(config *types.ProviderConfig) error {\n\tp.Storage = &S3{}\n\n\tif config.Zone == \"\" {\n\t\treturn errors.New(\"zone missing\")\n\t}\n\n\terr := loadAWSCreds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := session.NewSession(\n\t\t&aws.Config{\n\t\t\tRegion: aws.String(stripZone(config.Zone)),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.session = session\n\tp.dnsService = route53.New(session)\n\tp.ec2 = ec2.New(session)\n\tp.volumeService = ebs.New(session,\n\t\taws.NewConfig().\n\t\t\tWithRegion(stripZone(config.Zone)).\n\t\t\tWithMaxRetries(7))\n\n\t_, err = p.ec2.DescribeRegions(&ec2.DescribeRegionsInput{RegionNames: aws.StringSlice([]string{stripZone(config.Zone)})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"region with name %v is invalid\", config.Zone)\n\t}\n\n\treturn nil\n}", "func (s S3Service) connectToS3() *session.Session {\n\n\t//connect\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(s.Region),\n\t\tCredentials: credentials.NewStaticCredentials(s.AccessKeyID, s.SecretAccessKey, s.Token),\n\t})\n\n\tif err != nil {\n\t\tfmt.Println(\"Connecting to s3 failed\")\n\t\treturn sess\n\t}\n\n\treturn sess\n\n}", "func AWSCreate() {\n\tSetClusterName()\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/.terraform\"); err == nil {\n\t\tfmt.Println(\"Configuration folder already exists\")\n\t} else {\n\t\tsshUser, osLabel := distSelect()\n\t\tfmt.Printf(\"Prepairing Setup for user %s on %s\\n\", sshUser, osLabel)\n\t\tos.MkdirAll(\"./inventory/\"+common.Name+\"/provisioner\", 0755)\n\t\terr := exec.Command(\"cp\", \"-rfp\", \"./kubespray/contrib/terraform/aws/.\", \"./inventory/\"+common.Name+\"/provisioner\").Run()\n\t\tcommon.ErrorCheck(\"provisioner could not provided: %v\", err)\n\t\tprepareConfigFiles(osLabel)\n\t\tprovisioner.ExecuteTerraform(\"init\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\t}\n\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\n\t// waiting for Loadbalancer and other not completed stuff\n\tfmt.Println(\"Infrastructure is upcoming.\")\n\ttime.Sleep(15 * time.Second)\n\treturn\n\n}", "func NewAmazonSQS(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {\n\ts, err := reader.NewAmazonSQS(conf.SQS, log, stats)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewAsyncReader(TypeSQS, true, reader.NewAsyncBundleUnacks(s), log, stats)\n}", "func newPair() (pcOffer *PeerConnection, pcAnswer *PeerConnection, err error) {\n\tpca, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpcb, err := NewPeerConnection(Configuration{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn pca, pcb, nil\n}", "func setupAWS(ctx *context.Context, config *ConfigParams) (*blob.Bucket, error) {\n\tc := &aws.Config{\n\t\t// Either hard-code the region or use AWS_REGION.\n\t\tRegion: aws.String(config.Region),\n\t\t// credentials.NewEnvCredentials assumes two environment variables are\n\t\t// present:\n\t\t// 1. AWS_ACCESS_KEY_ID, and\n\t\t// 2. AWS_SECRET_ACCESS_KEY.\n\t\t// Credentials: credentials.NewEnvCredentials(),\n\t\tCredentials: credentials.NewStaticCredentials(\n\t\t\tconfig.AccessKey,\n\t\t\tconfig.SecretKey,\n\t\t\tconfig.Token,\n\t\t),\n\t}\n\ts := session.Must(session.NewSession(c))\n\treturn s3blob.OpenBucket(*ctx, config.Bucket, s, nil)\n}", "func createConnection() (io.Closer, error) {\n\tid := atomic.AddInt32(&idCounter, 1)\n\tfmt.Println(\"--> Create: New Connection\", id)\n\treturn &dbConnection{id}, nil\n}", "func createConnection() (io.Closer, error) {\n\tid := atomic.AddInt32(&idCounter, 1)\n\tlog.Println(\"Create: New Connection\", id)\n\treturn &dbConnection{id}, nil\n}", "func initAerospikeConnection(host string, username string, password string) (*aerospike.Connection, error) {\n\tclientPolicy := aerospike.NewClientPolicy()\n\ttlsConfig := initTLSConfig()\n\n\tif securityEnabled == \"true\" {\n\t\tclientPolicy.User = username\n\t\tclientPolicy.Password = password\n\n\t\tif authMode == \"external\" {\n\t\t\tclientPolicy.AuthMode = aerospike.AuthModeExternal\n\t\t}\n\t}\n\n\t// only one connection\n\tclientPolicy.ConnectionQueueSize = 1\n\tclientPolicy.Timeout = 5 * time.Second\n\tclientPolicy.TlsConfig = tlsConfig\n\n\tport := servicePlainPort\n\ttlsName := \"\"\n\tif clientPolicy.TlsConfig != nil {\n\t\tport = serviceTLSPort\n\t\ttlsName = serviceTLSName\n\t}\n\tportInt, _ := strconv.Atoi(port)\n\n\tserver := aerospike.NewHost(host, portInt)\n\tserver.TLSName = tlsName\n\tzap.S().Debugf(\"Connecting to aerospike node %s:%d.\", host, portInt)\n\n\tconnection, err := aerospike.NewConnection(clientPolicy, server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif clientPolicy.RequiresAuthentication() {\n\t\tif err := connection.Login(clientPolicy); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn connection, nil\n}", "func NewConnection(s *mgo.Session, db, cname string) *Connection {\n\treturn &Connection{\n\t\tsession: s,\n\t\tDatabase: db,\n\t\tName: cname,\n\t}\n}", "func CreateConnectionURL(args *args.ArgumentList) string {\n\n\tconnectionString := \"\"\n\n\tconnectionURL := &url.URL{\n\t\tScheme: \"sqlserver\",\n\t\tUser: url.UserPassword(args.Username, args.Password),\n\t\tHost: args.Hostname,\n\t}\n\n\t// If port is present use port if not user instance\n\tif args.Port != \"\" {\n\t\tconnectionURL.Host = fmt.Sprintf(\"%s:%s\", connectionURL.Host, args.Port)\n\t} else {\n\t\tconnectionURL.Path = args.Instance\n\t}\n\n\t// Format query parameters\n\tquery := url.Values{}\n\tquery.Add(\"dial timeout\", args.Timeout)\n\tquery.Add(\"connection timeout\", args.Timeout)\n\n\tif args.ExtraConnectionURLArgs != \"\" {\n\t\textraArgsMap, err := url.ParseQuery(args.ExtraConnectionURLArgs)\n\t\tif err == nil {\n\t\t\tfor k, v := range extraArgsMap {\n\t\t\t\tquery.Add(k, v[0])\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warn(\"Could not successfully parse ExtraConnectionURLArgs.\", err.Error())\n\t\t}\n\n\t}\n\n\tif args.EnableSSL {\n\t\tquery.Add(\"encrypt\", \"true\")\n\n\t\tquery.Add(\"TrustServerCertificate\", strconv.FormatBool(args.TrustServerCertificate))\n\n\t\tif !args.TrustServerCertificate {\n\t\t\tquery.Add(\"certificate\", args.CertificateLocation)\n\t\t}\n\t}\n\n\tconnectionURL.RawQuery = query.Encode()\n\n\tconnectionString = connectionURL.String()\n\n\treturn connectionString\n}", "func newAwsConfig(args arguments) aws.Config {\n\t// The options array will be updated within this function based on the provided command line arguments. At the end\n\t// the array will be passed to 'LoadDefaultConfig()' to create a AWS configuration for the DynamoDB client that\n\t// reflects the options the user has selected on the command line.\n\tvar options []func(*config.LoadOptions) error\n\n\tif args.region != \"\" {\n\t\toptions = append(options, config.WithRegion(args.region))\n\t}\n\n\tif args.profile != \"\" {\n\t\toptions = append(options, config.WithSharedConfigProfile(args.profile))\n\t}\n\n\toptions = append(options, config.WithRetryer(func() aws.Retryer {\n\t\treturn retry.AddWithMaxAttempts(retry.NewStandard(), 5)\n\t}))\n\n\tif args.endpoint != \"\" {\n\t\tresolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {\n\t\t\tif service == dynamodb.ServiceID {\n\t\t\t\treturn aws.Endpoint{\n\t\t\t\t\tPartitionID: \"aws\",\n\t\t\t\t\tURL: args.endpoint,\n\t\t\t\t\tSigningRegion: region,\n\t\t\t\t}, nil\n\t\t\t}\n\n\t\t\treturn aws.Endpoint{}, fmt.Errorf(\"unknown endpoint requested\")\n\t\t})\n\n\t\toptions = append(options, config.WithEndpointResolver(resolver))\n\t}\n\n\t// TODO: handle error.\n\tcfg, _ := config.LoadDefaultConfig(context.TODO(), options...)\n\n\treturn cfg\n}", "func NewConnection(nodes []string) connection {\n\t_, logger = tools.NewTools(0)\n\n\tlogger.Println(\"Establish NewConnection to nodes:\", nodes)\n\n\t// Create RPC client for contacting the server.\n\tvar clients []*rpc.Client\n\tsort.Strings(nodes)\n\n\tfor _, node := range nodes {\n if newClient := createRPCClient(node); newClient != nil {\n clients = append(clients, newClient)\n }\n\t}\n\n\treturn &KVConn{clients: clients, nodes: nodes}\n}", "func NewAsconn(t mockConstructorTestingTNewAsconn) *Asconn {\n\tmock := &Asconn{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func setupAWS(ctx context.Context, bucket string) (*blob.Bucket, error) {\n\tc := &aws.Config{\n\t\t// Either hard-code the region or use AWS_REGION.\n\t\tRegion: aws.String(\"us-east-2\"),\n\t\t// credentials.NewEnvCredentials assumes two environment variables are\n\t\t// present:\n\t\t// 1. AWS_ACCESS_KEY_ID, and\n\t\t// 2. AWS_SECRET_ACCESS_KEY.\n\t\tCredentials: credentials.NewEnvCredentials(),\n\t}\n\ts := session.Must(session.NewSession(c))\n\treturn s3blob.OpenBucket(ctx, s, bucket)\n}", "func NewConnection(w http.ResponseWriter, r *http.Request) (conn *Connection) {\n\trequestID := uuid.New().String()\n\treturn &Connection{requestID, make(chan []byte, 10), w, r}\n}", "func NewConnection(d string) (*amqp.Connection, error) {\n\treturn amqp.Dial(d)\n}", "func newCloudConnection(config io.Reader) (cloudprovider.Interface, error) {\n\tklog.V(4).Infof(\"newCloudConnection called with %+v\", config)\n\tif config != nil {\n\t\tklog.Warningf(\"supplied config is not read by this version. Using environment\")\n\t}\n\tnewCloud := &cloud{}\n\t_, err := newCloud.cloudClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newCloud, nil\n}", "func connect(dbPath string) (*bolt.DB, error) {\n\tvar (\n\t\tdb *bolt.DB\n\t\terr error\n\t)\n\n\t// setup database configuration\n\tdbCfg := &bolt.Options{Timeout: 1 * time.Second}\n\n\t// get database object\n\tdb, err = bolt.Open(dbPath, 0600, dbCfg)\n\tif err != nil {\n\t\treturn db, errors.Wrap(err, \"Could not open bolt DB\")\n\t}\n\n\t// Return db object and error (if any)\n\t// The closure checks if bucketName exists and creates if it doesn't\n\treturn db, db.Update(func(tx *bolt.Tx) error {\n\t\tif _, err := tx.CreateBucketIfNotExists(bucketName); err != nil {\n\t\t\treturn errors.Wrapf(err, \"Could not create bucket: %s\", string(bucketName))\n\t\t}\n\t\treturn nil\n\t})\n}", "func New(options ...Option) *Connection {\n\tc := Connection{\n\t\tdebug: false,\n\t\tusetor: true,\n\t\ttimeout: 180 * time.Second,\n\t\tname: \"\", // TOOD: use UUID?\n\t\theaders: make(map[string]string),\n\t}\n\tfor _, o := range options {\n\t\to(&c)\n\t}\n\n\treturn &c\n}", "func New(config *aws.Config) (*SQS, error) {\n\n\tsess, err := session.NewSession(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to initialize sns session\")\n\t}\n\n\treturn &SQS{\n\t\tsqs: sqs.New(sess),\n\t}, nil\n\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateS3(bucketName, pathPrefix string) error {\n\treturn nil\n}", "func NewAWSBroker(o Options, awssess GetAwsSession, clients AwsClients, getCallerId GetCallerIder, updateCatalog UpdateCataloger, pollUpdate PollUpdater) (*AwsBroker, error) {\n\n\tsess := awssess(o.KeyID, o.SecretKey, o.Region, \"\", o.Profile, map[string]string{})\n\ts3sess := awssess(o.KeyID, o.SecretKey, o.S3Region, \"\", o.Profile, map[string]string{})\n\ts3svc := clients.NewS3(s3sess)\n\tddbsvc := clients.NewDdb(sess)\n\tstssvc := clients.NewSts(sess)\n\tcallerid, err := getCallerId(stssvc)\n\tif err != nil {\n\t\treturn &AwsBroker{}, err\n\t}\n\taccountid := *callerid.Account\n\taccountuuid := uuid.NewV5(uuid.NullUUID{}.UUID, accountid+o.BrokerID)\n\n\tglog.Infof(\"Running as caller identity '%+v'.\", callerid)\n\n\tvar db Db\n\tdb.Brokerid = o.BrokerID\n\tdb.Accountid = accountid\n\tdb.Accountuuid = accountuuid\n\n\t// connect DynamoDB adapter to storage port\n\tdb.DataStorePort = dynamodbadapter.DdbDataStore{\n\t\tAccountid: accountid,\n\t\tAccountuuid: accountuuid,\n\t\tBrokerid: o.BrokerID,\n\t\tRegion: o.Region,\n\t\tDdb: *ddbsvc,\n\t\tTablename: o.TableName,\n\t}\n\n\t// setup in memory cache\n\tvar catalogcache = cache.NewMemoryWithTTL(time.Duration(CacheTTL))\n\tvar listingcache = cache.NewMemoryWithTTL(time.Duration(CacheTTL))\n\tlistingcache.StartGC(time.Minute * 5)\n\tbd := &BucketDetailsRequest{\n\t\to.S3Bucket,\n\t\to.S3Key,\n\t\to.TemplateFilter,\n\t}\n\n\t// populate broker variables\n\tbl := AwsBroker{\n\t\taccountId: accountid,\n\t\tkeyid: o.KeyID,\n\t\tsecretkey: o.SecretKey,\n\t\tprofile: o.Profile,\n\t\ttablename: o.TableName,\n\t\ts3bucket: o.S3Bucket,\n\t\ts3region: o.S3Region,\n\t\ts3key: addTrailingSlash(o.S3Key),\n\t\ttemplatefilter: o.TemplateFilter,\n\t\tregion: o.Region,\n\t\ts3svc: s3svc,\n\t\tcatalogcache: catalogcache,\n\t\tlistingcache: listingcache,\n\t\tbrokerid: o.BrokerID,\n\t\tdb: db,\n\t\tGetSession: awssess,\n\t\tClients: clients,\n\t\tprescribeOverrides: o.PrescribeOverrides,\n\t\tglobalOverrides: getGlobalOverrides(o.BrokerID),\n\t}\n\n\t// get catalog and setup periodic updates from S3\n\terr = updateCatalog(listingcache, catalogcache, *bd, s3svc, db, bl, ListTemplates, ListingUpdate, MetadataUpdate)\n\tif err != nil {\n\t\treturn &AwsBroker{}, err\n\t}\n\tgo pollUpdate(600, listingcache, catalogcache, *bd, s3svc, db, bl, updateCatalog, ListTemplates)\n\treturn &bl, nil\n}", "func NewAWS(ctx arn.Ctx, r ...Router) *AWS {\n\troot := append(ChainRouter{STSRouter{}}, r...)\n\tw := &AWS{\n\t\tCtxRouter: CtxRouter{arn.Ctx{}: &root},\n\t\tCtx: ctx,\n\t}\n\tw.Cfg = awsmock.Config(func(q *aws.Request) {\n\t\tw.mu.Lock()\n\t\tdefer w.mu.Unlock()\n\t\tif q := w.newRequest(q); !w.Route(q) {\n\t\t\tpanic(\"mock: \" + q.Name() + \" not handled\")\n\t\t}\n\t})\n\tw.Cfg.Region = ctx.Region\n\tw.Cfg.Credentials = w.UserCreds(\"\", \"alice\")\n\treturn w\n}", "func NewConn(conn net.Conn) *AGI {\n\ta := New(conn, conn)\n\ta.conn = conn\n\treturn a\n}", "func (b *Bucket) CreateBucket(name string) (*Bucket, error) { panic(\"n/i\") }", "func NewAWS(aws config.AWSConfig, bucket config.S3BucketConfig, noLocks, noVersioning bool) *AWS {\n\tif bucket.Bucket == \"\" {\n\t\treturn nil\n\t}\n\n\tsess := session.Must(session.NewSession())\n\tawsConfig := aws_sdk.NewConfig()\n\tvar creds *credentials.Credentials\n\tif len(aws.APPRoleArn) > 0 {\n\t\tlog.Debugf(\"Using %s role\", aws.APPRoleArn)\n\t\tcreds = stscreds.NewCredentials(sess, aws.APPRoleArn, func(p *stscreds.AssumeRoleProvider) {\n\t\t\tif aws.ExternalID != \"\" {\n\t\t\t\tp.ExternalID = aws_sdk.String(aws.ExternalID)\n\t\t\t}\n\t\t})\n\t} else {\n\t\tif aws.AccessKey == \"\" || aws.SecretAccessKey == \"\" {\n\t\t\tlog.Fatal(\"Missing AccessKey or SecretAccessKey for AWS provider. Please check your configuration and retry\")\n\t\t}\n\t\tcreds = credentials.NewStaticCredentials(aws.AccessKey, aws.SecretAccessKey, aws.SessionToken)\n\t}\n\tawsConfig.WithCredentials(creds)\n\n\tif e := aws.Endpoint; e != \"\" {\n\t\tawsConfig.WithEndpoint(e)\n\t}\n\tif e := aws.Region; e != \"\" {\n\t\tawsConfig.WithRegion(e)\n\t}\n\tawsConfig.S3ForcePathStyle = &bucket.ForcePathStyle\n\n\treturn &AWS{\n\t\tsvc: s3.New(sess, awsConfig),\n\t\tbucket: bucket.Bucket,\n\t\tkeyPrefix: bucket.KeyPrefix,\n\t\tfileExtension: bucket.FileExtension,\n\t\tdynamoSvc: dynamodbiface.DynamoDBAPI(dynamodb.New(sess, awsConfig)),\n\t\tdynamoTable: aws.DynamoDBTable,\n\t\tnoLocks: noLocks,\n\t\tnoVersioning: noVersioning,\n\t}\n}", "func (x *graphql__resolver_ActionsService) CreateConnection(ctx context.Context) (*grpc.ClientConn, func(), error) {\n\t// If x.conn is not nil, user injected their own connection\n\tif x.conn != nil {\n\t\treturn x.conn, func() {}, nil\n\t}\n\n\t// Otherwise, this handler opens connection with specified host\n\tconn, err := grpc.DialContext(ctx, x.host, x.dialOptions...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn conn, func() { conn.Close() }, nil\n}", "func New(streamName, applicationName, clientName string, config Config, role string, consumerARNvalue string) (*Kinsumer, error) {\n\ts, err := session.NewSession()\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t}).Error(\"error starting new AWS session\")\n\t\treturn nil, err\n\t}\n\treturn NewWithSession(s, streamName, applicationName, clientName, config, role, consumerARNvalue)\n}", "func NewAWSClient(config *types.Configuration, stats *types.Statistics, statsdClient, dogstatsdClient *statsd.Client) (*Client, error) {\r\n\r\n\tif config.AWS.AccessKeyID != \"\" && config.AWS.SecretAccessKey != \"\" && config.AWS.Region != \"\" {\r\n\t\tos.Setenv(\"AWS_ACCESS_KEY_ID\", config.AWS.AccessKeyID)\r\n\t\tos.Setenv(\"AWS_SECRET_ACCESS_KEY\", config.AWS.SecretAccessKey)\r\n\t\tos.Setenv(\"AWS_DEFAULT_REGION\", config.AWS.Region)\r\n\t}\r\n\r\n\tsess, err := session.NewSession(&aws.Config{\r\n\t\tRegion: aws.String(config.AWS.Region)},\r\n\t)\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS - %v\\n\", \"Error while creating AWS Session\")\r\n\t\treturn nil, errors.New(\"Error while creating AWS Session\")\r\n\t}\r\n\r\n\t_, err = sts.New(session.New()).GetCallerIdentity(&sts.GetCallerIdentityInput{})\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS - %v\\n\", \"Error while getting AWS Token\")\r\n\t\treturn nil, errors.New(\"Error while getting AWS Token\")\r\n\t}\r\n\r\n\tvar endpointURL *url.URL\r\n\tendpointURL, err = url.Parse(config.AWS.SQS.URL)\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] : AWS SQS - %v\\n\", err.Error())\r\n\t\treturn nil, ErrClientCreation\r\n\t}\r\n\r\n\treturn &Client{\r\n\t\tOutputType: \"AWS\",\r\n\t\tEndpointURL: endpointURL,\r\n\t\tConfig: config,\r\n\t\tAWSSession: sess,\r\n\t\tStats: stats,\r\n\t\tStatsdClient: statsdClient,\r\n\t\tDogstatsdClient: dogstatsdClient,\r\n\t}, nil\r\n}", "func (self *server) CreateConnection(ctx context.Context, rsqt *smtppb.CreateConnectionRqst) (*smtppb.CreateConnectionRsp, error) {\n\tfmt.Println(\"Try to create a new connection\")\n\t// sqlpb\n\tfmt.Println(\"Try to create a new connection\")\n\tvar c connection\n\tvar err error\n\n\t// Set the connection info from the request.\n\tc.Id = rsqt.Connection.Id\n\tc.Host = rsqt.Connection.Host\n\tc.Port = rsqt.Connection.Port\n\tc.User = rsqt.Connection.User\n\tc.Password = rsqt.Connection.Password\n\n\t// set or update the connection and save it in json file.\n\tself.Connections[c.Id] = c\n\n\t// In that case I will save it in file.\n\terr = self.save()\n\tif err != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Internal,\n\t\t\tUtility.JsonErrorStr(Utility.FunctionName(), Utility.FileLine(), err))\n\t}\n\n\t// test if the connection is reacheable.\n\t// _, err = self.ping(ctx, c.Id)\n\n\tif err != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Internal,\n\t\t\tUtility.JsonErrorStr(Utility.FunctionName(), Utility.FileLine(), err))\n\t}\n\n\t// Print the success message here.\n\tlog.Println(\"Connection \" + c.Id + \" was created with success!\")\n\n\treturn &smtppb.CreateConnectionRsp{\n\t\tResult: true,\n\t}, nil\n}", "func pushEC2Connect(profile, instanceID, instanceUser, pubKey string) (string, string, error) {\n\tctx := log.WithField(\"instance_id\", instanceID)\n\tcfg, err := config.LoadDefaultConfig(context.TODO(),\n\t\tconfig.WithSharedConfigProfile(profile))\n\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get aws session: %s\", err)\n\t}\n\tec2Svc := ec2.NewFromConfig(cfg)\n\tec2Result, err := ec2Svc.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []string{instanceID},\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get ec2 instance: %s\", err)\n\t}\n\n\tif len(ec2Result.Reservations) == 0 || len(ec2Result.Reservations[0].Instances) == 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"Couldn't find the instance %s\", instanceID)\n\t}\n\n\tec2Instance := ec2Result.Reservations[0].Instances[0]\n\tec2ICSvc := ec2instanceconnect.NewFromConfig(cfg)\n\n\t// no username has been provided, so we try to get it fom the instance tag first\n\tif instanceUser == \"\" {\n\t\tctx.Debug(\"no user has been set provided, trying to get it from the tags\")\n\t\t// next try to get username from the instance tags\n\t\tif instanceUser = lib.GetUserFromTags(ec2Instance.Tags); instanceUser == \"\" {\n\t\t\t// otherwise fallback to default\n\t\t\tctx.WithField(\"user\", defaultUser).Debugf(\"got no user from the instance tags, setting to default\")\n\t\t\tinstanceUser = defaultUser\n\t\t} else {\n\t\t\tctx.WithField(\"user\", instanceUser).Debugf(\"got username from tags\")\n\t\t}\n\t}\n\n\tctx.WithField(\"user\", instanceUser).Info(\"pushing SSH key...\")\n\n\tif _, err := ec2ICSvc.SendSSHPublicKey(context.TODO(), &ec2instanceconnect.SendSSHPublicKeyInput{\n\t\tInstanceId: ec2Instance.InstanceId,\n\t\tInstanceOSUser: aws.String(instanceUser),\n\t\tAvailabilityZone: ec2Instance.Placement.AvailabilityZone,\n\t\tSSHPublicKey: aws.String(pubKey),\n\t}); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't push ssh key: %s\", err)\n\t}\n\tvar address = aws.ToString(ec2Instance.PrivateIpAddress)\n\tif aws.ToString(ec2Instance.PublicIpAddress) != \"\" {\n\t\taddress = aws.ToString(ec2Instance.PublicIpAddress)\n\t}\n\treturn address, instanceUser, nil\n}", "func (a *AmazonConnectionsApiService) DeleteAmazonConnectionExecute(r ApiDeleteAmazonConnectionRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.DeleteAmazonConnection\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func NewConnection(pathname string, key string) (*Connection, error) {\n\tc := &Connection{}\n\n\tcert, err := CertificateFromP12(pathname, key)\n\tif err != nil {\n\t\t//fmt.Printf(\"Error creating Connection: %v\", err)\n\t\treturn nil, err\n\t}\n\tc.Certificate = cert\n\n\ttlsConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cert},\n\t}\n\n\t//no check if Certificate is present to fail hard if this requirement is not met\n\ttlsConfig.BuildNameToCertificate()\n\n\ttransport := &http2.Transport{TLSClientConfig: tlsConfig}\n\n\tc.HTTPClient = http.Client{Transport: transport}\n\t//Default Host is Development Host.\n\tc.Host = HostDevelopment\n\n\treturn c, nil\n}", "func (rm *resourceManager) sdkCreate(\n\tctx context.Context,\n\tr *resource,\n) (*resource, error) {\n\tinput, err := rm.newCreateRequestPayload(ctx, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, respErr := rm.sdkapi.CreateVpnConnectionWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"CREATE\", \"CreateVpnConnection\", respErr)\n\tif respErr != nil {\n\t\treturn nil, respErr\n\t}\n\t// Merge in the information we read from the API call above to the copy of\n\t// the original Kubernetes object we passed to the function\n\tko := r.ko.DeepCopy()\n\n\tif resp.VpnConnection.Category != nil {\n\t\tko.Status.Category = resp.VpnConnection.Category\n\t}\n\tif resp.VpnConnection.CustomerGatewayConfiguration != nil {\n\t\tko.Status.CustomerGatewayConfiguration = resp.VpnConnection.CustomerGatewayConfiguration\n\t}\n\tif resp.VpnConnection.Routes != nil {\n\t\tf4 := []*svcapitypes.VPNStaticRoute{}\n\t\tfor _, f4iter := range resp.VpnConnection.Routes {\n\t\t\tf4elem := &svcapitypes.VPNStaticRoute{}\n\t\t\tif f4iter.DestinationCidrBlock != nil {\n\t\t\t\tf4elem.DestinationCIDRBlock = f4iter.DestinationCidrBlock\n\t\t\t}\n\t\t\tif f4iter.Source != nil {\n\t\t\t\tf4elem.Source = f4iter.Source\n\t\t\t}\n\t\t\tif f4iter.State != nil {\n\t\t\t\tf4elem.State = f4iter.State\n\t\t\t}\n\t\t\tf4 = append(f4, f4elem)\n\t\t}\n\t\tko.Status.Routes = f4\n\t}\n\tif resp.VpnConnection.State != nil {\n\t\tko.Status.State = resp.VpnConnection.State\n\t}\n\tif resp.VpnConnection.Tags != nil {\n\t\tf6 := []*svcapitypes.Tag{}\n\t\tfor _, f6iter := range resp.VpnConnection.Tags {\n\t\t\tf6elem := &svcapitypes.Tag{}\n\t\t\tif f6iter.Key != nil {\n\t\t\t\tf6elem.Key = f6iter.Key\n\t\t\t}\n\t\t\tif f6iter.Value != nil {\n\t\t\t\tf6elem.Value = f6iter.Value\n\t\t\t}\n\t\t\tf6 = append(f6, f6elem)\n\t\t}\n\t\tko.Status.Tags = f6\n\t}\n\tif resp.VpnConnection.VgwTelemetry != nil {\n\t\tf9 := []*svcapitypes.VGWTelemetry{}\n\t\tfor _, f9iter := range resp.VpnConnection.VgwTelemetry {\n\t\t\tf9elem := &svcapitypes.VGWTelemetry{}\n\t\t\tif f9iter.AcceptedRouteCount != nil {\n\t\t\t\tf9elem.AcceptedRouteCount = f9iter.AcceptedRouteCount\n\t\t\t}\n\t\t\tif f9iter.CertificateArn != nil {\n\t\t\t\tf9elem.CertificateARN = f9iter.CertificateArn\n\t\t\t}\n\t\t\tif f9iter.LastStatusChange != nil {\n\t\t\t\tf9elem.LastStatusChange = &metav1.Time{*f9iter.LastStatusChange}\n\t\t\t}\n\t\t\tif f9iter.OutsideIpAddress != nil {\n\t\t\t\tf9elem.OutsideIPAddress = f9iter.OutsideIpAddress\n\t\t\t}\n\t\t\tif f9iter.Status != nil {\n\t\t\t\tf9elem.Status = f9iter.Status\n\t\t\t}\n\t\t\tif f9iter.StatusMessage != nil {\n\t\t\t\tf9elem.StatusMessage = f9iter.StatusMessage\n\t\t\t}\n\t\t\tf9 = append(f9, f9elem)\n\t\t}\n\t\tko.Status.VGWTelemetry = f9\n\t}\n\tif resp.VpnConnection.VpnConnectionId != nil {\n\t\tko.Status.VPNConnectionID = resp.VpnConnection.VpnConnectionId\n\t}\n\n\trm.setStatusDefaults(ko)\n\n\treturn &resource{ko}, nil\n}", "func Initialize() error {\n // Initialize the AWS session.\n sess, err := session.NewSession(&aws.Config{\n Region: aws.String(config.Settings.AWS.Region),\n Credentials: credentials.NewStaticCredentials(config.Settings.AWS.AccessKeyID, config.Settings.AWS.SecretAccessKeyID, \"\")},\n )\n if err != nil {\n return fmt.Errorf(\"INITIALIZATION ERROR: %v\", err)\n }\n\n // Initialize the DynamoDB instance.\n Items = Products{dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody))}\n Items.listTables()\n\n tableExists, err := Items.tableExists(TableName)\n if err != nil {\n return fmt.Errorf(\"INITIALIZATION ERROR: %v\", err)\n }\n\n if !tableExists {\n createTable()\n } else {\n fmt.Println(\"Table already exists!\")\n }\n\n return nil\n}", "func CreateKeyPair(conn *ec2.EC2) (KeyPair, error) {\n\tname := generateKeyPairName()\n\tvar kp KeyPair\n\tkp.KeyName = name\n\n\tparams := &ec2.CreateKeyPairInput{\n\t\tKeyName: aws.String(name),\n\t}\n\n\tresp, err := conn.CreateKeyPair(params)\n\tif err != nil {\n\t\treturn kp, err\n\t}\n\n\tkp.Fingerprint = *resp.KeyFingerprint\n\tkp.PrivateKeyPEM = *resp.KeyMaterial\n\tkp.Created = true\n\n\treturn kp, nil\n}", "func NewAccessKey(ctx *pulumi.Context,\n\tname string, args *AccessKeyArgs, opts ...pulumi.ResourceOption) (*AccessKey, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.UserName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserName'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource AccessKey\n\terr := ctx.RegisterResource(\"aws-native:iam:AccessKey\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func createConnection(port string, baudrate Baud, databit DataBit,\n\tstopbit StopBit, parity Parity) (*Connection, error) {\n\tconnection := &Connection{Port: port, Baud: baudrate,\n\t\tDataBit: databit, StopBit: stopbit, Parity: parity}\n\treturn connection, connection.check()\n}", "func (a *CloudProviderCredentialsApiService) CreateAWSCredentials(ctx _context.Context, organizationId string) ApiCreateAWSCredentialsRequest {\n\treturn ApiCreateAWSCredentialsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\torganizationId: organizationId,\n\t}\n}", "func createSession(bucket string, settings map[string]string) (*session.Session, error) {\n\tconfig := getDefaultConfig(settings)\n\tconfig.MaxRetries = &MaxRetries\n\tif _, err := config.Credentials.Get(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get AWS credentials; please specify %s and %s\", AccessKeyIdSetting, SecretAccessKeySetting)\n\t}\n\n\tif endpoint, ok := settings[EndpointSetting]; ok {\n\t\tconfig.Endpoint = aws.String(endpoint)\n\t}\n\n\tif s3ForcePathStyleStr, ok := settings[ForcePathStyleSetting]; ok {\n\t\ts3ForcePathStyle, err := strconv.ParseBool(s3ForcePathStyleStr)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to parse %s\", ForcePathStyleSetting)\n\t\t}\n\t\tconfig.S3ForcePathStyle = aws.Bool(s3ForcePathStyle)\n\t}\n\n\tregion, err := getAWSRegion(bucket, config, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig = config.WithRegion(region)\n\n\tfilePath := settings[s3CertFile]\n\tif filePath != \"\" {\n\t\tif file, err := os.Open(filePath); err == nil {\n\t\t\tdefer file.Close()\n\t\t\treturn session.NewSessionWithOptions(session.Options{Config: *config, CustomCABundle: file})\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn session.NewSession(config)\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, ecsBucket.User, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n log.Print(bucketCreateResponse)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n log.Print(err)\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func New(auth stacks.AuthenticationOptions, localCfg stacks.AWSConfiguration, cfg stacks.ConfigurationOptions) (*stack, error) { // nolint\n\tif localCfg.Ec2Endpoint == \"\" {\n\t\tlocalCfg.Ec2Endpoint = fmt.Sprintf(\"https://ec2.%s.amazonaws.com\", localCfg.Region)\n\t}\n\tif localCfg.SsmEndpoint == \"\" {\n\t\tlocalCfg.SsmEndpoint = fmt.Sprintf(\"https://ssm.%s.amazonaws.com\", localCfg.Region)\n\t}\n\n\tstack := &stack{\n\t\tConfig: &cfg,\n\t\tAuthOptions: &auth,\n\t\tAwsConfig: &localCfg,\n\t}\n\n\taccessKeyID := auth.AccessKeyID\n\tsecretAccessKey := auth.SecretAccessKey\n\n\tss3 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.S3Endpoint),\n\t}))\n\n\tsec2 := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.Ec2Endpoint),\n\t}))\n\n\tsssm := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(localCfg.Region),\n\t\tEndpoint: aws.String(localCfg.SsmEndpoint),\n\t}))\n\n\tspricing := session.Must(session.NewSession(&aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tRegion: aws.String(endpoints.UsEast1RegionID),\n\t}))\n\n\tstack.S3Service = s3.New(ss3, &aws.Config{})\n\tstack.EC2Service = ec2.New(sec2, &aws.Config{})\n\tstack.SSMService = ssm.New(sssm, &aws.Config{})\n\tstack.PricingService = pricing.New(spricing, &aws.Config{})\n\n\tif cfg.Timings != nil {\n\t\tstack.MutableTimings = cfg.Timings\n\t} else {\n\t\tstack.MutableTimings = temporal.NewTimings()\n\t}\n\n\treturn stack, nil\n}", "func createConnection(ip string) net.Conn {\n\tconn, err := net.DialTimeout(\"tcp\", ip,10*time.Second)\n\n\t//Check for errors\n\tif err != nil {\n\t\tlog.Printf(\"createConnection: %s, check if the ip is correct or cgminer's api is enabled or if the miner is offline\\n\", err)\n\t\treturn nil\n\t}\n\treturn conn\n}", "func NewAWS(crypto appencryption.AEAD, preferredRegion string, arnMap map[string]string) (*AWSKMS, error) {\n\treturn newAWS(crypto, preferredRegion, awsARNMap(arnMap))\n}", "func initializeBucket() {\n\tclient := getClient()\n\tparams := &s3.GetBucketLocationInput{\n\t\tBucket: aws.String(S3_BUCKET_NAME), // Required\n\t}\n\t_, err := client.GetBucketLocation(params)\n\tif err != nil {\n\t\t// bucket does not exist\n\t\tparams := &s3.CreateBucketInput{\n\t\t\tBucket: aws.String(S3_BUCKET_NAME), // Required\n\t\t}\n\t\t_, err := client.CreateBucket(params)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Attempted to create bucket with name \" + S3_BUCKET_NAME + \", but failed.\")\n\t\t\tfmt.Println(\"Error was: \" + err.Error())\n\t\t\tos.Exit(2)\n\t\t}\n\t\t// fmt.Println(\"created new bucket with name: \" + S3_BUCKET_NAME)\n\t}\n}", "func New() *AwsAsg {\n\n\tcfg, err := config.LoadDefaultConfig()\n\tif err != nil {\n\t\tpanic(\"unable to load SDK config, \" + err.Error())\n\t}\n\tsvc := autoscaling.NewFromConfig(cfg)\n\treturn &AwsAsg{\n\t\tsvc: svc,\n\t}\n}", "func (s *S3Connecter) Connect(file *FileInfo) (s3iface.S3API, error) {\n\tcred := credentials.NewStaticCredentials(file.AccessKeyID, file.SecretKey, file.SessionToken)\n\tcred.Get()\n\tconfig := aws.NewConfig().\n\t\tWithCredentials(cred).\n\t\tWithRegion(file.Region)\n\tsess, err := session.NewSession(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s3.New(sess), nil\n}", "func PutConnection(connectionID string) error {\n\titem := ConnectionItem{ConnectionID: connectionID}\n\treturn dynamodb.Put(connectionTable, item)\n}", "func NewConnection(requestPath string) (httpClient *http.Client, err error) {\n\trequestURL, err := url.Parse(requestPath)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestHost := requestURL.Host\n\t//Create a new security connection and update the cache\n\thttpClient, err = createConnection()\n\tif err == nil {\n\t\tconnectionPool.Lock()\n\t\tconnectionPool.pool[requestHost] = httpClient\n\t\tconnectionPool.Unlock()\n\t}\n\treturn\n}", "func NewConnectionTo(hostURL string) *Connection {\n\tclient := resty.New()\n\tclient.HostURL = hostURL\n\treturn newConnection(client)\n}", "func NewConnection(byteSize int, expirySeconds int) veldt.StoreCtor {\n\treturn func() (veldt.Store, error) {\n\t\treturn &Connection{\n\t\t\tcache: getCache(byteSize),\n\t\t\texpiry: expirySeconds,\n\t\t}, nil\n\t}\n}", "func (ks *KopiaSnapshotter) ConnectOrCreateS3WithServer(serverAddr, bucketName, pathPrefix string) (*exec.Cmd, error) {\n\treturn nil, nil\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func newAwsSession(p Params) (*session.Session, error) {\n\n\tconfig := aws.NewConfig()\n\tif p.region != \"\" {\n\t\tconfig.Region = aws.String(p.region)\n\t}\n\n\toptions := session.Options{\n\t\tConfig: *config,\n\t\tAssumeRoleTokenProvider: stscreds.StdinTokenProvider,\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}\n\tif p.profile != \"\" {\n\t\toptions.Profile = p.profile\n\t}\n\tsess := session.Must(session.NewSessionWithOptions(options))\n\n\treturn sess, nil\n}", "func (c *EBSVolumeResizer) ConnectToProvider() error {\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(c.AWSRegion)})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not establish AWS session: %v\", err)\n\t}\n\tc.connection = ec2.New(sess)\n\treturn nil\n}", "func (d *DynamoConn) Create(sess *session.Session) error {\n\t// Assume client is may already be authorized\n\tif d.Client != nil {\n\t\treturn errors.New(\"db: dynamodb client already exists\")\n\t}\n\n\t// Create DynamoDB client using session\n\td.Client = dynamodb.New(sess)\n\treturn nil\n}", "func createRabbitConnection(cr *Credentials) (*Rabbit, error) {\n\tconnectionStr := fmt.Sprintf(\"amqp://%v:%v@%v:%v/\", cr.Username, cr.Password, cr.Host, cr.Port)\n\tconn, err := amqp.Dial(connectionStr)\n\tfailOnError(err, \"Failed to connect to RabbitMQ; Connection string:\"+connectionStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch, err := conn.Channel()\n\tfailOnError(err, \"Failed to open a channel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rabbit{\n\t\tConnection: conn,\n\t\tChannel: ch,\n\t\tCredentials: cr,\n\t}, nil\n}" ]
[ "0.6522948", "0.6131977", "0.6120262", "0.58307123", "0.552645", "0.5447285", "0.54411185", "0.5439992", "0.5357866", "0.5345272", "0.52972656", "0.5217575", "0.5182514", "0.5162646", "0.51575994", "0.51429814", "0.5121698", "0.5072095", "0.50574315", "0.5050541", "0.50468385", "0.501418", "0.5012674", "0.5007821", "0.4986546", "0.49622265", "0.49452272", "0.494439", "0.49367133", "0.49271742", "0.4891853", "0.48888943", "0.48808265", "0.48691216", "0.4867711", "0.48609298", "0.4860477", "0.4858521", "0.4853363", "0.4851771", "0.48511487", "0.48500708", "0.4841831", "0.48371768", "0.48349297", "0.48346317", "0.482851", "0.48145905", "0.48114392", "0.48094547", "0.48040673", "0.48029503", "0.4779092", "0.47785947", "0.4777629", "0.47767666", "0.47691354", "0.47667077", "0.47493994", "0.47479996", "0.47465414", "0.47431156", "0.47352454", "0.4734704", "0.47342193", "0.47269034", "0.47260243", "0.47243854", "0.47059292", "0.47041976", "0.4694096", "0.4693373", "0.46836925", "0.4680843", "0.46738362", "0.4669066", "0.46620277", "0.46551853", "0.46454203", "0.46439847", "0.4639864", "0.46377826", "0.4634827", "0.46300098", "0.46287498", "0.4624933", "0.46177888", "0.461359", "0.4612971", "0.46122938", "0.4609577", "0.460837", "0.46076718", "0.46027982", "0.4597984", "0.45930308", "0.45917472", "0.45911816", "0.45900545", "0.4584603" ]
0.7173758
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) CreateAmazonConnectionExecute(r ApiCreateAmazonConnectionRequest) (AmazonConnection, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue AmazonConnection ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.CreateAmazonConnection") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } if r.amazonConnectionSpec == nil { return localVarReturnValue, nil, reportError("amazonConnectionSpec is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") // body params localVarPostBody = r.amazonConnectionSpec if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
/ DeleteAmazonConnection Method for DeleteAmazonConnection
func (a *AmazonConnectionsApiService) DeleteAmazonConnection(ctx _context.Context, amazonConnectionId string) ApiDeleteAmazonConnectionRequest { return ApiDeleteAmazonConnectionRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) DeleteAmazonConnectionExecute(r ApiDeleteAmazonConnectionRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.DeleteAmazonConnection\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func DeleteConnection(connectionID string) error {\n\treturn dynamodb.Delete(connectionTable, \"connectionId\", connectionID)\n}", "func (f *IBMPICloudConnectionClient) Delete(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsDeleteParams) (models.Object, error) {\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsDeleteParams().WithCloudInstanceID(pclouddef.CloudInstanceID).WithCloudConnectionID(pclouddef.CloudConnectionID)\n\trespok, _, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsDelete(params, ibmpisession.NewAuth(f.session, pclouddef.CloudInstanceID))\n\n\tif err != nil || respok.Payload == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to Delete all cloud connection %s\", err)\n\t}\n\treturn respok.Payload, nil\n}", "func (f *IBMPICloudConnectionClient) Delete(id, cloudInstanceID string) (models.Object, *models.JobReference, error) {\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsDeleteParamsWithTimeout(helpers.PIDeleteTimeOut).WithCloudInstanceID(cloudInstanceID).WithCloudConnectionID(id)\n\trespOk, respAccepted, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsDelete(params, ibmpisession.NewAuth(f.session, cloudInstanceID))\n\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(errors.DeleteCloudConnectionOperationFailed, id, err)\n\t}\n\tif respOk != nil {\n\t\treturn respOk.Payload, nil, nil\n\t}\n\tif respAccepted != nil {\n\t\treturn nil, respAccepted.Payload, nil\n\t}\n\treturn nil, nil, nil\n}", "func (m *OrganizationManager) DeleteConnection(id string, connectionID string, opts ...RequestOption) (err error) {\n\terr = m.Request(\"DELETE\", m.URI(\"organizations\", id, \"enabled_connections\", connectionID), nil, opts...)\n\treturn\n}", "func TestDeleteConnection(t *testing.T) {\n\tcc := getClientConnection()\n\n\t// when done the connection will be close.\n\tdefer cc.Close()\n\n\t// Create a new client service...\n\tc := ldappb.NewLdapServiceClient(cc)\n\n\t// I will execute a simple ldap search here...\n\trqst := &ldappb.DeleteConnectionRqst{\n\t\tId: \"test_ldap\",\n\t}\n\n\t_, err := c.DeleteConnection(context.Background(), rqst)\n\tif err != nil {\n\t\tlog.Fatalf(\"error while deleting the connection: %v\", err)\n\t}\n\n\tlog.Println(\"Delete connection success!\")\n}", "func (self *server) DeleteConnection(ctx context.Context, rqst *smtppb.DeleteConnectionRqst) (*smtppb.DeleteConnectionRsp, error) {\n\tid := rqst.GetId()\n\tif _, ok := self.Connections[id]; !ok {\n\t\treturn &smtppb.DeleteConnectionRsp{\n\t\t\tResult: true,\n\t\t}, nil\n\t}\n\n\tdelete(self.Connections, id)\n\n\t// In that case I will save it in file.\n\terr := self.save()\n\tif err != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Internal,\n\t\t\tUtility.JsonErrorStr(Utility.FunctionName(), Utility.FileLine(), err))\n\t}\n\n\t// return success.\n\treturn &smtppb.DeleteConnectionRsp{\n\t\tResult: true,\n\t}, nil\n}", "func Delete(svc *dynamodb.DynamoDB, id string) error {\n\t_, err := svc.DeleteItem(&dynamodb.DeleteItemInput{\n\t\tTableName: aws.String(userTableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"ConnectionID\": {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rm *resourceManager) sdkDelete(\n\tctx context.Context,\n\tr *resource,\n) error {\n\n\tinput, err := rm.newDeleteRequestPayload(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, respErr := rm.sdkapi.DeleteVpnConnectionWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"DELETE\", \"DeleteVpnConnection\", respErr)\n\treturn respErr\n}", "func (r DeleteConnectionRequest) Send(ctx context.Context) (*DeleteConnectionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DeleteConnectionResponse{\n\t\tDeleteConnectionOutput: r.Request.Data.(*DeleteConnectionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (r *ExternalConnectionRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (h *ConnectionPoolsHandler) Delete(ctx context.Context, project, serviceName, poolName string) error {\n\tpath := buildPath(\"project\", project, \"service\", serviceName, \"connection_pool\", poolName)\n\tbts, err := h.client.doDeleteRequest(ctx, path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn checkAPIResponse(bts, nil)\n}", "func Delete(conn redis.Conn, key string) error {\n\t_, err := conn.Do(\"DEL\", key)\n\treturn err\n}", "func (rm *resourceManager) sdkDelete(\n\tctx context.Context,\n\tr *resource,\n) error {\n\n\tinput, err := rm.newDeleteRequestPayload(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, respErr := rm.sdkapi.DeleteVpcPeeringConnectionWithContext(ctx, input)\n\trm.metrics.RecordAPICall(\"DELETE\", \"DeleteVpcPeeringConnection\", respErr)\n\treturn respErr\n}", "func (h *VPCPeeringConnectionsHandler) Delete(project, vpcID, peerCloudAccount, peerVPC string) error {\n\tpath := buildPath(\n\t\t\"project\",\n\t\tproject,\n\t\t\"vpcs\",\n\t\tvpcID,\n\t\t\"peering-connections\",\n\t\t\"peer-accounts\",\n\t\tpeerCloudAccount,\n\t\t\"peer-vpcs\",\n\t\tpeerVPC,\n\t)\n\tbts, err := h.client.doDeleteRequest(path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn handleDeleteResponse(bts)\n}", "func ExampleBotConnectionClient_Delete() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armbotservice.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\t_, err = clientFactory.NewBotConnectionClient().Delete(ctx, \"OneResourceGroupName\", \"samplebotname\", \"sampleConnection\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n}", "func deleteKeyPair(cf *Cloudformation, keyPair string, err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"Key pair deleted %s because stack failed with err: \\n %s \\n\", keyPair, err)\n\t\tos.Exit(1)\n\t}\n\t_, keyErr := cf.ec2Res.deleteKeyPair(keyPair)\n\tif keyErr != nil {\n\t\tfmt.Printf(\"Delete key pair err: %s \\n\", keyErr)\n\t}\n}", "func (s stack) DeleteKeyPair(ctx context.Context, id string) fail.Error {\n\treturn fail.NotImplementedError(\"DeleteKeyPair() not implemented yet\") // FIXME: Technical debt\n}", "func (c defaultSTSClient) DeleteAccessKey(accessKey string) error {\n\tpayload := map[string]string{\n\t\t\"accessKey\": accessKey,\n\t}\n\tresp, err := resty.R().SetBody(payload).Delete(c.stsURLPrefix + \"/accesskey\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcode := resp.StatusCode()\n\tswitch code {\n\tcase http.StatusNotFound:\n\t\treturn pion_clients.ErrAccessKeyNotFound\n\tcase http.StatusOK:\n\t\treturn nil\n\tdefault:\n\t\tglog.Errorf(\"Failed to delete accesskey='%s': status='%d', body='%v'\", accessKey, code, string(resp.Body()))\n\t\treturn pion_clients.ErrInternalError\n\t}\n}", "func (pool *PoolHandler) Delete(request *restful.Request, response *restful.Response) {\n\tstarted := time.Now()\n\tnetKey := request.PathParameter(\"net\")\n\tnetCluster := request.PathParameter(\"cluster\")\n\tnetRes := &types.NetResponse{\n\t\tType: types.ResponseType_POOL,\n\t}\n\tif len(netKey) == 0 || len(netCluster) == 0 {\n\t\tnetRes.Code = 1\n\t\tnetRes.Message = \"Lost param needed\"\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"deleteIPPool\", \"4xx\", started)\n\t\treturn\n\t}\n\tif err := pool.netSvr.DeletePool(netCluster + \"/\" + netKey); err != nil {\n\t\tblog.Errorf(\"NetPool Delete %s/%s request err: %s\", netCluster, netKey, err.Error())\n\t\tnetRes.Code = 1\n\t\tnetRes.Message = err.Error()\n\t\tresponse.WriteEntity(netRes)\n\t\treportMetrics(\"deleteIPPool\", \"5xx\", started)\n\t\treturn\n\t}\n\tnetRes.Code = 0\n\tnetRes.Message = SUCCESS\n\tif err := response.WriteEntity(netRes); err != nil {\n\t\tblog.Errorf(\"PoolHandler reply client DELETE request Err: %v\", err)\n\t}\n\treportMetrics(\"deleteIPPool\", \"2xx\", started)\n}", "func (c Connector) Delete(connections ...*Connection) Connector {\n\tfor _, connection := range connections {\n\t\tdelete(c, connection.Name)\n\t}\n\treturn c\n}", "func (client IdentityClient) DeleteTag(ctx context.Context, request DeleteTagRequest) (response DeleteTagResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteTag, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = DeleteTagResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteTagResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteTagResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteTagResponse\")\n\t}\n\treturn\n}", "func (p awsPeeringServiceOp) Delete(ctx context.Context, input *models.DeleteAwsPeeringInput) (*models.Result, *Response, error) {\n\tvar peeringResult models.Result\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"deleteAwsPeering\",\n\t\tOperation: models.Mutation,\n\t\tInput: nil,\n\t\tArgs: *input,\n\t\tResponse: peeringResult,\n\t}\n\treq, err := p.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := p.client.Do(ctx, req, &peeringResult)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &peeringResult, resp, err\n}", "func deleteClientConn(s *redis.Client, c []string){\n\tfor _, v := range c {\n\t\tres := s.ClientKill(v)\n\t\tfmt.Println(\"Connection killed: \", res)\n\t}\n}", "func S3Delete (fileID *string)error {\r\n\terr := godotenv.Load()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\ts, err := session.NewSession(&aws.Config{Region: aws.String(os.Getenv(\"S3_REGION\"))})\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t_,err = s3.New(s).DeleteObject(&s3.DeleteObjectInput{\r\n\t\tBucket: aws.String(os.Getenv(\"S3_BUCKET\")),\r\n\t\tKey: aws.String(*fileID),\r\n\t})\r\n\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func deleteObject(objectName string,\n\tbucketName string,\n\tsess *session.Session) (*s3.DeleteObjectOutput, error) {\n\tsvc := s3.New(sess)\n\tinput := &s3.DeleteObjectInput{\n\t\tBucket: aws.String(bucketName),\n\t\tKey: aws.String(objectName),\n\t}\n\tcount.Incr(\"aws-delete\")\n\toutput, err := svc.DeleteObject(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase s3.ErrCodeObjectNotInActiveTierError:\n\t\t\t\tfmt.Println(s3.ErrCodeObjectNotInActiveTierError, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\tfmt.Println(\"Got error on delete ******** \", bucketName, objectName)\n\t\tcount.Incr(\"error-delete\")\n\t\tif strings.Contains(err.Error(), \"SlowDown\") {\n\t\t\tfmt.Println(\"Got slow down, sleeping for a few minutes\")\n\t\t\tcount.Incr(\"slow-down\")\n\t\t\ttime.Sleep(60 * time.Second)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn output, nil\n}", "func (nsxtAlbPool *NsxtAlbPool) Delete() error {\n\tclient := nsxtAlbPool.vcdClient.Client\n\tendpoint := types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointAlbPools\n\tminimumApiVersion, err := client.checkOpenApiEndpointCompatibility(endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif nsxtAlbPool.NsxtAlbPool.ID == \"\" {\n\t\treturn fmt.Errorf(\"cannot delete NSX-T ALB Pool without ID\")\n\t}\n\n\turlRef, err := client.OpenApiBuildEndpoint(endpoint, nsxtAlbPool.NsxtAlbPool.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = client.OpenApiDeleteItem(minimumApiVersion, urlRef, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error deleting NSX-T ALB Pool: %s\", err)\n\t}\n\n\treturn nil\n}", "func (s *BaseAspidaListener) ExitConnection(ctx *ConnectionContext) {}", "func (mp *MongoPool) TerminateConnection(conn *mongo.Client) {\n\tfor i, v := range mp.pool {\n\t\tif v == conn {\n\t\t\tmp.pool = append(mp.pool[:i], mp.pool[i+1:]...)\n\t\t\tmp.poolSize++\n\t\t\tbreak\n\t\t}\n\t}\n\tdefer conn.Disconnect(nil)\n}", "func deleteAccessKey(iamSvc *iam.IAM, accessKeyId string) error {\n\tdeleteAccessKeyInput := &iam.DeleteAccessKeyInput{\n\t\tAccessKeyId: aws.String(accessKeyId),\n\t}\n\n\t_, err := iamSvc.DeleteAccessKey(deleteAccessKeyInput)\n\treturn err\n}", "func (driver *S3Driver) Terminate() error {\n\treturn nil\n}", "func (client IdentityClient) deleteTag(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/tagNamespaces/{tagNamespaceId}/tags/{tagName}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteTagResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client *Client) DeleteKeyPair(id string) error {\n\treturn client.osclt.DeleteKeyPair(id)\n}", "func DeleteFederatedConnection(cmd *cobra.Command, args []string) error {\n\n\tclient, err := auth.GetClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Parse all flags\n\n\tvar connectionName string\n\terr = flags.ParseFlag(cmd.Flags(), \"connection-name\", &connectionName)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"connection-name\": ` + err.Error())\n\t}\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\terr = client.SearchService.DeleteFederatedConnection(connectionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) Delete(rawurl string) error {\n\treturn c.Do(rawurl, \"DELETE\", nil, nil)\n}", "func (client IdentityClient) deleteTagNamespace(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/tagNamespaces/{tagNamespaceId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteTagNamespaceResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func DeleteFromAWS(filehash string) {\n\n\tfileToBeDeleted := &s3.DeleteObjectInput{\n\t\tBucket: aws.String(AWSS3Bucket),\n\t\tKey: aws.String(filehash),\n\t}\n\n\tresult, err := svc.DeleteObject(fileToBeDeleted)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (a *Client) DeleteAPI24Connections(params *DeleteAPI24ConnectionsParams) (*DeleteApi24ConnectionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteAPI24ConnectionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"DeleteAPI24Connections\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/api/2.4/connections\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &DeleteAPI24ConnectionsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*DeleteApi24ConnectionsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for DeleteAPI24Connections: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (be *s3) Delete() error {\n\talltypes := []backend.Type{\n\t\tbackend.Data,\n\t\tbackend.Key,\n\t\tbackend.Lock,\n\t\tbackend.Snapshot,\n\t\tbackend.Index}\n\n\tfor _, t := range alltypes {\n\t\terr := be.removeKeys(t)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn be.Remove(backend.Config, \"\")\n}", "func (asg *Asg) Delete() error {\n\treturn cloudprovider.ErrNotImplemented\n}", "func (e Manager) UnregisterConnection(id int) {\n\te.index.unregister(id)\n}", "func (c *OperatorDNS) Delete(bucket string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), defaultOperatorContextTimeout)\n\tdefer cancel()\n\te, err := c.endpoint(bucket, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, e, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.addAuthHeader(req); err != nil {\n\t\treturn err\n\t}\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\txhttp.DrainBody(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"request to delete the service for bucket %s, failed with status %s\", bucket, resp.Status)\n\t}\n\treturn nil\n}", "func Delete(req handler.Request, prevModel *Model, currentModel *Model) (handler.ProgressEvent, error) {\n\t// Add your code here:\n\t// * Make API calls (use req.Session)\n\t// * Mutate the model\n\t// * Check/set any callback context (req.CallbackContext / response.CallbackContext)\n\tiotSvc := iot.New(req.Session)\n\ts3Svc := s3.New(req.Session)\n\n\tinactiveStatus := \"INACTIVE\"\n\tiotSvc.UpdateCertificate(&iot.UpdateCertificateInput{\n\t\tCertificateId: currentModel.Id,\n\t\tNewStatus: &inactiveStatus,\n\t})\n\n\tvar key string\n\tkey = fmt.Sprintf(\"%s.pem\", *currentModel.Id)\n\n\t_, err := s3Svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &key,\n\t})\n\tif err != nil {\n\t\taerr, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tfmt.Printf(\"%v\", aerr)\n\t\t}\n\t\tresponse := handler.ProgressEvent{\n\t\t\tOperationStatus: handler.Failed,\n\t\t\tMessage: \"Bucket is not accessible\",\n\t\t}\n\t\treturn response, nil\n\n\t}\n\n\tkey = fmt.Sprintf(\"%s.key\", *currentModel.Id)\n\n\t_, err = s3Svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: currentModel.Bucket,\n\t\tKey: &key,\n\t})\n\tif err != nil {\n\t\taerr, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tfmt.Printf(\"%v\", aerr)\n\t\t}\n\t\tresponse := handler.ProgressEvent{\n\t\t\tOperationStatus: handler.Failed,\n\t\t\tMessage: \"Bucket is not accessible\",\n\t\t}\n\t\treturn response, nil\n\n\t}\n\n\t_, err = iotSvc.DeleteCertificate(&iot.DeleteCertificateInput{\n\t\tCertificateId: currentModel.Id,\n\t})\n\n\tif err != nil {\n\t\taerr, ok := err.(awserr.Error)\n\t\tif ok {\n\t\t\tfmt.Printf(\"%v\", aerr)\n\t\t}\n\t\tresponse := handler.ProgressEvent{\n\t\t\tOperationStatus: handler.Failed,\n\t\t\tMessage: fmt.Sprintf(\"Failed deleting the certificate: %s\", aerr.Error()),\n\t\t}\n\t\treturn response, nil\n\n\t}\n\n\tresponse := handler.ProgressEvent{\n\t\tOperationStatus: handler.Success,\n\t\tMessage: \"Certificate delete successfully\",\n\t\tResourceModel: currentModel,\n\t}\n\treturn response, nil\n}", "func (client *Client) DeleteKeyPair(id string) error {\n\treturn client.feclt.DeleteKeyPair(id)\n}", "func (*BgpAmazonVpc) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/amazon_vpc/%s\", ref)\n}", "func (h *Handler) handleConnectionTerminate() {\n\terr := h.client.Disconnect()\n\tif err != nil {\n\t\th.logger.Error(\"subscription.Handler.handleConnectionTerminate()\",\n\t\t\tabstractlogger.Error(err),\n\t\t)\n\t}\n}", "func TeardownConnection() {\n\tRconn.Close()\n}", "func Delete(client *gophercloud.ServiceClient, instanceID, dbName string) (r DeleteResult) {\n\tresp, err := client.Delete(dbURL(client, instanceID, dbName), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (p *pool) Del(connectionString string) {\n\tkey, err := makeKey(connectionString)\n\tif err != nil {\n\t\treturn\n\t}\n\tdelete(p.clients, key)\n}", "func (i *Docker) Delete(assembly *global.AssemblyWithComponents, id string) (string, error) {\n\n\tpair_endpoint, perrscm := global.ParseKeyValuePair(assembly.Inputs, \"endpoint\")\n\tif perrscm != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", perrscm)\n\t}\n\n\tpair_id, iderr := global.ParseKeyValuePair(assembly.Components[0].Outputs, \"id\")\n\tif iderr != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", iderr)\n\t}\n\n\tvar endpoint string\n\tif pair_endpoint.Value == BAREMETAL {\n\n\t\tapi_host, _ := config.GetString(\"docker:swarm_host\")\n\t\tendpoint = api_host\n\n\t} else {\n\t\tendpoint = pair_endpoint.Value\n\t}\n\n\tclient, _ := docker.NewClient(endpoint)\n\tkerr := client.KillContainer(docker.KillContainerOptions{ID: pair_id.Value})\n\tif kerr != nil {\n\t\tlog.Error(\"Failed to kill the container : %s\", kerr)\n\t\treturn \"\", kerr\n\t}\n\tlog.Info(\"Container is killed\")\n\treturn \"\", nil\n}", "func (client IdentityClient) DeleteTagNamespace(ctx context.Context, request DeleteTagNamespaceRequest) (response DeleteTagNamespaceResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteTagNamespace, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = DeleteTagNamespaceResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteTagNamespaceResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteTagNamespaceResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteTagNamespaceResponse\")\n\t}\n\treturn\n}", "func (conn Connection) Delete(cmd string, content, result interface{}) (resp *http.Response, err error) {\n\treturn conn.Send(http.MethodDelete, cmd, content, result)\n}", "func DestroyConnection() {\n\n\tdb.Close()\n\n}", "func deleteConsumber(c *cli.Context) error {\n\tid := c.String(\"id\")\n\tusername := c.String(\"username\")\n\n\tvar requestURL string\n\tif id != \"\" {\n\t\trequestURL = fmt.Sprintf(\"%s/%s\", CONSUMER_RESOURCE_OBJECT, id)\n\t} else if username != \"\" {\n\t\trequestURL = fmt.Sprintf(\"%s/%s\", CONSUMER_RESOURCE_OBJECT, username)\n\t} else {\n\t\treturn fmt.Errorf(\"username and id invalid.\")\n\t}\n\n\tctx, cannel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cannel()\n\n\tserverResponse, err := client.GatewayClient.Delete(ctx, requestURL, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif serverResponse.StatusCode == http.StatusNoContent {\n\t\tfmt.Printf(\"delete consumer success.\")\n\t} else {\n\t\treturn fmt.Errorf(\"failed to delete consumer success: %v\", err)\n\t}\n\n\treturn nil\n}", "func (driver *S3Driver) Delete(id string) error {\n\treturn driver.client.RemoveObject(context.Background(), driver.bucket, id+\".json\", minio.RemoveObjectOptions{})\n}", "func Close(connectionId uint64) {\n\tmutex.Lock()\n\tdelete(connections, connectionId)\n\tmutex.Unlock()\n}", "func main() {\n\tif len(os.Args) != 2 {\n\t\texitErrorf(\"Bucket name is required\\nUsage: %s bucket_name\", os.Args[0])\n\t}\n\tbucket := os.Args[1]\n\n\t//Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials\n\tsess, _ := session.NewSession(&aws.Config {Region: aws.String(\"eu-west-1\")},)\n\tsvc := s3.New(sess)\n\n\t//Create a list iterator to iterate through the list of bucket objects and deleting each object.\n\titer := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{\n\t\tBucket: aws.String(bucket),\n\t})\n\n\tif err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil {\n\t\texitErrorf(\"Unable to delete objects from bucket %q, %v\", bucket, err)\n\t}\n\tfmt.Printf(\"Objects successfully deleted from %q\\n\", bucket)\n}", "func (s *State) DeleteActive(c *conn.Conn) {\n\te := s.get(c.InfoHash(), c.PeerID())\n\tif e.status != _active {\n\t\treturn\n\t}\n\tif e.conn != c {\n\t\t// It is possible that some new conn shares the same hash/peer as the old conn,\n\t\t// so we need to make sure we're deleting the right one.\n\t\treturn\n\t}\n\ts.delete(c.InfoHash(), c.PeerID())\n\n\ts.log(\"hash\", c.InfoHash(), \"peer\", c.PeerID()).Infof(\n\t\t\"Deleted active conn, capacity now at %d\", s.capacity(c.InfoHash()))\n\ts.netevents.Produce(networkevent.DropActiveConnEvent(\n\t\tc.InfoHash(), s.localPeerID, c.PeerID()))\n}", "func (r *ScanRequest) Delete(*cloudformationevt.Event, *runtime.Context) error {\n return nil\n}", "func (c *Client) Delete(ctx context.Context, p *DeletePayload) (err error) {\n\t_, err = c.DeleteEndpoint(ctx, p)\n\treturn\n}", "func DeleteKeyPair(conn *ec2.EC2, kp KeyPair) (KeyPair, error) {\n\tparams := &ec2.DeleteKeyPairInput{\n\t\tKeyName: aws.String(kp.KeyName),\n\t}\n\n\t_, err := conn.DeleteKeyPair(params)\n\tif err != nil {\n\t\treturn kp, err\n\t}\n\n\tkp.Created = false\n\treturn kp, nil\n}", "func (h *Handler) Delete(bucket, name string) error {\n\treq := h.Client.DeleteObjectRequest(&s3.DeleteObjectInput{\n\t\tBucket: &bucket,\n\t\tKey: &name,\n\t})\n\n\tresp, err := req.Send(context.Background())\n\tif err != nil {\n\t\tklog.Error(\"Failed to send Delete request. error: \", err)\n\t\treturn err\n\t}\n\n\tklog.V(10).Info(\"Delete Success\", resp)\n\n\treturn nil\n}", "func (client *IPPoolClient) Delete(pool *hcipamTypes.NSIPPool) error {\n\te := client.Cli\n\t_, err := concurrency.NewSTM(e, func(s concurrency.STM) error {\n\t\thcPoolKey := fmt.Sprintf(hcipamTypes.NS_POOL_Key, pool.Namespace, pool.Name)\n\t\ts.Del(hcPoolKey)\n\t\treturn nil\n\t})\n\treturn err\n}", "func Delete(client *gophercloud.ServiceClient, regionID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, regionID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (t *TestHandler) ObjectDeleted(obj interface{}) {\n\n\ttableName := strings.Split(obj.(string), \"/\")[1]\n\tfmt.Println(\"Object deleted\")\n\tfmt.Println(tableName)\n\t// fmt.Println(tableName)\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"eu-west-1\"),\n\t\tCredentials: credentials.NewSharedCredentials(\"\", \"saml\"),\n\t})\n\n\t// Create DynamoDB client\n\tsvc := dynamodb.New(sess)\n\n\tinput := &dynamodb.DeleteTableInput{\n\t\tTableName: aws.String(tableName),\n\t}\n\tresult, err := svc.DeleteTable(input)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\t// if aerr, ok := err.(awserr.Error); ok {\n\t// \tswitch aerr.Code() {\n\t// \tcase dynamodb.ErrCodeResourceInUseException:\n\t// \t\tfmt.Println(dynamodb.ErrCodeResourceInUseException, aerr.Error())\n\t// \tcase dynamodb.ErrCodeResourceNotFoundException:\n\t// \t\tfmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())\n\t// \tcase dynamodb.ErrCodeLimitExceededException:\n\t// \t\tfmt.Println(dynamodb.ErrCodeLimitExceededException, aerr.Error())\n\t// \tcase dynamodb.ErrCodeInternalServerError:\n\t// \t\tfmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())\n\t// \tdefault:\n\t// \t\tfmt.Println(aerr.Error())\n\t// \t}\n\t// } else {\n\t// \t// Print the error, cast err to awserr.Error to get the Code and\n\t// \t// Message from an error.\n\t// \tfmt.Println(err.Error())\n\t// }\n\t// return\n\t// }\n\tfmt.Println(result)\n\tfmt.Println(\"TestHandler.ObjectDeleted\")\n}", "func (b *Bucket) Delete(filename string) error {\n\t// set session\n\tsess, err := b.setSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsvc := b.newS3func(sess)\n\t_, err = svc.DeleteObject(&s3.DeleteObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting %s from bucket %s : %s\", filename, b.BucketName, err.Error())\n\t}\n\n\terr = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(b.BucketName),\n\t\tKey: aws.String(crPath + filename),\n\t})\n\treturn err\n}", "func (k *KernelForwarder) deleteRemoteConnection(connID string, localConnection, remoteConnection *connection.Connection, direction uint8) (map[string]monitoring.Device, error) {\n\tlogrus.Info(\"remote: deleting connection...\")\n\n\tifaceName := localConnection.GetMechanism().GetParameters()[common2.InterfaceNameKey]\n\tvar xconName string\n\tif direction == INCOMING {\n\t\txconName = \"DST-\" + connID\n\t} else {\n\t\txconName = \"SRC-\" + connID\n\t}\n\n\t/* Lock the OS thread so we don't accidentally switch namespaces */\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tnsInode, localErr := ClearInterfaceSetup(ifaceName, localConnection)\n\tremoteErr := k.remoteConnect.DeleteInterface(ifaceName, remoteConnection)\n\n\tif localErr != nil || remoteErr != nil {\n\t\treturn nil, errors.Errorf(\"remote: %v - %v\", localErr, remoteErr)\n\t}\n\n\tlogrus.Infof(\"remote: deletion completed for device - %s\", ifaceName)\n\treturn map[string]monitoring.Device{nsInode: {Name: ifaceName, XconName: xconName}}, nil\n}", "func disconnect(connection mysql.Conn) {\n\n\tconnection.Close()\n\n}", "func DeleteNamespace(projectCode, clusterID, name string) error {\n\tbcsCCConf := config.GlobalConf.BCSCC\n\tif !bcsCCConf.Enable {\n\t\treturn nil\n\t}\n\tmodel := store.GetModel()\n\tp, err := model.GetProject(context.Background(), projectCode)\n\tif err != nil {\n\t\tlogging.Error(\"get project by code %s failed, err: %s\", projectCode, err.Error())\n\t\treturn err\n\t}\n\t// get id from paascc\n\tnsList, err := ListNamespaces(projectCode, clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar id int\n\tfor _, namespace := range nsList.Results {\n\t\tif namespace.Name == name {\n\t\t\tid = namespace.ID\n\t\t\tbreak\n\t\t}\n\t}\n\tif id == 0 {\n\t\tlogging.Error(\"namespace %s/%s/%s not exists in paas-cc\", projectCode, clusterID, name)\n\t\treturn fmt.Errorf(\"namespace %s/%s/%s not exists in paas-cc\", projectCode, clusterID, name)\n\t}\n\trealPath := fmt.Sprintf(deleteNamespacePath, p.ProjectID, clusterID, id)\n\treqURL := fmt.Sprintf(\"%s%s\", bcsCCConf.Host, realPath)\n\treq := gorequest.SuperAgent{\n\t\tUrl: reqURL,\n\t\tMethod: \"DELETE\",\n\t}\n\treq.QueryData = url.Values{}\n\tif bcsCCConf.UseGateway {\n\t\treq.QueryData.Add(\"app_code\", config.GlobalConf.App.Code)\n\t\treq.QueryData.Add(\"app_secret\", config.GlobalConf.App.Secret)\n\t} else {\n\t\taccessToken, err := GetAccessToken()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.QueryData.Add(\"access_token\", accessToken)\n\t}\n\treturn requestCommonAndParse(req)\n}", "func (c *SubresourceClient) Delete(namespace, name string) (e error) {\n\tif c.Error != \"\" {\n\t\te = fmt.Errorf(c.Error)\n\t}\n\treturn\n}", "func (b *Bucket) Delete(_ context.Context, name string) error {\n\treturn b.client.DeleteObject(b.name, name)\n}", "func (a *AmazonConnectionsApiService) GetAllAmazonConnections(ctx _context.Context) ApiGetAllAmazonConnectionsRequest {\n\treturn ApiGetAllAmazonConnectionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func ExampleWebAppsClient_BeginDeletePrivateEndpointConnectionSlot() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armappservice.NewWebAppsClient(\"34adfa4f-cedf-4dc0-ba29-b6d1a69ab345\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := client.BeginDeletePrivateEndpointConnectionSlot(ctx,\n\t\t\"rg\",\n\t\t\"testSite\",\n\t\t\"connection\",\n\t\t\"stage\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (cs *CachingAuthClient) DeleteTunnelConnection(clusterName, connName string) error {\n\treturn cs.ap.DeleteTunnelConnection(clusterName, connName)\n}", "func Delete(c *drycc.Client, appID string, name string, port int, protocol string) error {\n\tu := fmt.Sprintf(\"/v2/apps/%s/gateways/\", appID)\n\n\treq := api.GatewayRemoveRequest{Name: name, Port: port, Protocol: protocol}\n\n\tbody, err := json.Marshal(req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := c.Request(\"DELETE\", u, body)\n\tif err == nil {\n\t\tres.Body.Close()\n\t}\n\treturn err\n}", "func CloseConnection(conn bolt.Conn) {\n\terr := conn.Close()\n\tif err != nil {\n\t\tfmt.Println(\"CloseConnection (reclaim) : \" + err.Error())\n\t}\n}", "func Delete() error {\n\n}", "func Delete(client *golangsdk.ServiceClient, instanceId, authId string) (r DeleteResult) {\n\t_, r.Err = client.Delete(resourceURL(client, instanceId, authId), nil)\n\treturn\n}", "func (a InstancePoolsAPI) Delete(instancePoolID string) error {\n\treturn a.C.Post(\"/instance-pools/delete\", map[string]string{\n\t\t\"instance_pool_id\": instancePoolID,\n\t}, nil)\n}", "func (net *NetworkComponentInput) DeleteIgws(con aws.EstablishConnectionInput) error {\n\n\tec2, seserr := con.EstablishConnection()\n\tif seserr != nil {\n\t\treturn seserr\n\t}\n\n\tfor _, igw := range net.IgwIds {\n\t\terr := ec2.DeleteIgw(\n\t\t\t&aws.DescribeNetworkInput{\n\t\t\t\tIgwIds: []string{igw},\n\t\t\t\tVpcIds: net.VpcIds,\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t//Waiting till internetgateways deletion is successfully completed\n\t\tigwwait, igwwaiterr := ec2.WaitUntilIgwDeleted(\n\t\t\t&aws.DescribeNetworkInput{\n\t\t\t\tIgwIds: []string{igw},\n\t\t\t},\n\t\t)\n\t\tif igwwaiterr != nil {\n\t\t\treturn igwwaiterr\n\t\t}\n\t\tif igwwait == false {\n\t\t\treturn fmt.Errorf(\"An error occurred while deleting a igws\")\n\t\t}\n\t}\n\treturn nil\n}", "func (conn Connection) Delete(cmd string, content, result interface{}) (effect *SideEffect, resp *http.Response, err error) {\n\treturn conn.Send(http.MethodDelete, cmd, content, result)\n}", "func ExampleTimeSeriesDatabaseConnectionsClient_BeginDelete() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armdigitaltwins.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewTimeSeriesDatabaseConnectionsClient().BeginDelete(ctx, \"resRg\", \"myDigitalTwinsService\", \"myConnection\", &armdigitaltwins.TimeSeriesDatabaseConnectionsClientBeginDeleteOptions{CleanupConnectionArtifacts: nil})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.TimeSeriesDatabaseConnection = armdigitaltwins.TimeSeriesDatabaseConnection{\n\t// \tName: to.Ptr(\"myConnection\"),\n\t// \tType: to.Ptr(\"Microsoft.DigitalTwins/digitalTwinsInstances/timeSeriesDatabaseConnections\"),\n\t// \tID: to.Ptr(\"/subscriptions/50016170-c839-41ba-a724-51e9df440b9e/resourcegroups/resRg/providers/Microsoft.DigitalTwins/digitalTwinsInstances/myDigitalTwinsService/timeSeriesDatabaseConnections/myConnection\"),\n\t// \tProperties: &armdigitaltwins.AzureDataExplorerConnectionProperties{\n\t// \t\tConnectionType: to.Ptr(armdigitaltwins.ConnectionTypeAzureDataExplorer),\n\t// \t\tProvisioningState: to.Ptr(armdigitaltwins.TimeSeriesDatabaseConnectionStateSucceeded),\n\t// \t\tAdxDatabaseName: to.Ptr(\"myDatabase\"),\n\t// \t\tAdxEndpointURI: to.Ptr(\"https://mycluster.kusto.windows.net\"),\n\t// \t\tAdxResourceID: to.Ptr(\"/subscriptions/c493073e-2460-45ba-a403-f3e0df1e9feg/resourceGroups/testrg/providers/Microsoft.Kusto/clusters/mycluster\"),\n\t// \t\tEventHubConsumerGroup: to.Ptr(\"$Default\"),\n\t// \t\tEventHubEndpointURI: to.Ptr(\"sb://myeh.servicebus.windows.net/\"),\n\t// \t\tEventHubEntityPath: to.Ptr(\"myeh\"),\n\t// \t\tEventHubNamespaceResourceID: to.Ptr(\"/subscriptions/c493073e-2460-45ba-a403-f3e0df1e9feg/resourceGroups/testrg/providers/Microsoft.EventHub/namespaces/myeh\"),\n\t// \t},\n\t// }\n}", "func cleanup(t *testing.T) {\n\tconn := connectAllZk(t)\n\terr := recursiveDelete(conn, zkPrefix)\n\tif err != nil {\n\t\tt.Fatalf(\"cleanup err=%q\", err)\n\t}\n\tconn.Close()\n}", "func (avisess *AviSession) Delete(uri string, params ...interface{}) error {\n\tvar payload, response interface{}\n\tif len(params) > 0 {\n\t\tpayload = params[0]\n\t\tif len(params) == 2 {\n\t\t\tresponse = params[1]\n\t\t}\n\t}\n\treturn avisess.restRequestInterfaceResponse(\"DELETE\", uri, payload, response)\n}", "func (c *Client) Delete(ctx context.Context, link string) error {\n\n\tauthKey, err := GetAccessTokenFromContext(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Missing token in context\")\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", link, nil)\n\n\tif err != nil {\n\t\tlog.Error(\"Cannot create request:\", err)\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Add(\"authorization\", authKey)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tresp, err := c.httpClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"POST request error:\", err)\n\t\treturn err\n\t}\n\t// this is required to properly empty the buffer for the next call\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tlog.Error(err, \": \", string(body))\n\t}\n\n\treturn err\n}", "func DeleteVPCMocked(t *testing.T, vpcIn *types.Vpc) {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewVPCService(cs)\n\tassert.Nil(err, \"Couldn't load VPC service\")\n\tassert.NotNil(ds, \"VPC service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(vpcIn)\n\tassert.Nil(err, \"VPC test data corrupted\")\n\n\t// call service\n\tcs.On(\"Delete\", fmt.Sprintf(\"/network/vpcs/%s\", vpcIn.ID)).Return(dIn, 200, nil)\n\terr = ds.DeleteVPC(vpcIn.ID)\n\tassert.Nil(err, \"Error deleting VPC\")\n}", "func (d *DeleteServerInput) DeleteServer(con aws.EstablishConnectionInput) ([]ServerResponse, error) {\n\n\t//get the relative sessions before proceeding further\n\tec2, sesserr := con.EstablishConnection()\n\tif sesserr != nil {\n\t\treturn nil, sesserr\n\t}\n\n\tinstanceSearchInput := CommonComputeInput{InstanceIds: d.InstanceIds}\n\tsearchInstance, serverr := instanceSearchInput.SearchInstance(con)\n\n\tif serverr != nil {\n\t\treturn nil, serverr\n\t}\n\n\tif searchInstance != true {\n\t\treturn nil, fmt.Errorf(\"Could not find the entered Instances, please enter valid/existing InstanceIds\")\n\t}\n\tdeleteResult, insTermErr := ec2.DeleteInstance(\n\t\t&aws.DeleteComputeInput{\n\t\t\tInstanceIds: d.InstanceIds,\n\t\t},\n\t)\n\tif insTermErr != nil {\n\t\treturn nil, insTermErr\n\t}\n\n\twaiterr := ec2.WaitTillInstanceTerminated(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: d.InstanceIds,\n\t\t},\n\t)\n\tif waiterr != nil {\n\t\treturn nil, waiterr\n\t}\n\n\tresult, err := ec2.DescribeInstance(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: d.InstanceIds,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeleteResponse := make([]ServerResponse, 0)\n\n\tif d.GetRaw == true {\n\t\tdeleteResponse = append(deleteResponse, ServerResponse{DeleteInstRaw: deleteResult, Cloud: \"Amazon\"})\n\t\treturn deleteResponse, nil\n\t}\n\n\tfor _, reservation := range result.Reservations {\n\t\tfor _, instance := range reservation.Instances {\n\t\t\tdeleteResponse = append(deleteResponse, ServerResponse{InstanceId: *instance.InstanceId, CurrentState: *instance.State.Name})\n\t\t}\n\t}\n\treturn deleteResponse, nil\n}", "func DisassociateTag(rm RM, query QueryBuilder) error {\n\tendpoint := fmt.Sprintf(\"%s?%s\", restTagging, query.Build())\n\n\t_, err := rm.Del(endpoint)\n\treturn err\n}", "func (c *Client) DeleteDirectConnect(request *DeleteDirectConnectRequest) (response *DeleteDirectConnectResponse, err error) {\n if request == nil {\n request = NewDeleteDirectConnectRequest()\n }\n response = NewDeleteDirectConnectResponse()\n err = c.Send(request, response)\n return\n}", "func (s *BaseAspidaListener) ExitConnectionSSH(ctx *ConnectionSSHContext) {}", "func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tif len(args) != 1 {\r\n\t\treturn nil, errors.New(\"Incorrect number of arguments. \")\r\n\t}\r\n\taccount := args[0]\r\n\terr := stub.DelState(account) //remove the key from chaincode state\r\n\tif err != nil {\r\n\t\treturn nil, errors.New(\"Failed to delete account\")\r\n\t}\r\n\r\n\treturn nil, nil\r\n}", "func (t *shimTestCC) delete(stub ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 1 {\n\t\treturn Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tA := args[0]\n\n\t// Delete the key from the state in ledger\n\terr := stub.DelState(A)\n\tif err != nil {\n\t\treturn Error(\"Failed to delete state\")\n\t}\n\n\treturn Success(nil)\n}", "func deleteStack(name string) error {\n\tfmt.Printf(\"DEBUG:: deleting stack %v\\n\", name)\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvc := cloudformation.New(cfg)\n\tdsreq := svc.DeleteStackRequest(&cloudformation.DeleteStackInput{StackName: aws.String(name)})\n\t_, err = dsreq.Send(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func deleteHyperShiftVPC(workingDir string) error {\n\tctx := context.Background()\n\n\ttf, err := terraform.New(workingDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t_ = tf.Uninstall(ctx)\n\t}()\n\n\terr = tf.Init(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"Deleting ROSA HyperShift aws vpc\")\n\n\terr = callAndSetAWSSession(func() error {\n\t\treturn tf.Destroy(\n\t\t\tctx,\n\t\t\ttfexec.Var(fmt.Sprintf(\"aws_region=%s\", viper.GetString(config.AWSRegion))),\n\t\t\ttfexec.Var(fmt.Sprintf(\"cluster_name=%s\", viper.GetString(config.Cluster.Name))),\n\t\t)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"ROSA HyperShift aws vpc deleted!\")\n\n\treturn nil\n}", "func (d *driver) Delete(ctx context.Context, path string) error {\n\treturn d.Bucket.Delete(ctx, path)\n}", "func AWSRemove() {\n\tSetClusterName()\n\tsshUser, osLabel := distSelect()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"reset.yml\", sshUser, osLabel)\n}", "func (s *Service) doDelete(ctx *context.Context, url string) *types.Error {\n\n\tbucket := \"l8ldiytwq83d8ckg\"\n\tsess, err := session.NewSession(&aws.Config{})\n\tif err != nil {\n\t\treturn nil\n\t}\n\tsvc := s3.New(sess)\n\n\t_, errObject := svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(url)})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\terrObject = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{\n\t\tBucket: aws.String(bucket),\n\t\tKey: aws.String(url),\n\t})\n\tif errObject != nil {\n\t\terr := &types.Error{\n\t\t\tPath: \".uploaderService->doDelete()\",\n\t\t\tMessage: errObject.Error(),\n\t\t\tError: errObject,\n\t\t\tType: \"aws-error\",\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *HTTPClient) Delete(q *Query, timeout time.Duration) error {\n if q == nil {\n return fmt.Errorf(\"kairosdb: nil query passed\")\n }\n payload, err := json.Marshal(q)\n if err != nil {\n return fmt.Errorf(\"error unmarshalling query:%v :: %v\", q, err)\n }\n\n glog.Infof(\"deleting datapoints payload: %v\", string(payload))\n reader := ioutil.NopCloser(bytes.NewReader(payload))\n err = c.backend.Call(\"POST\", c.url+\"/api/v1/datapoints/delete\", reader,\n timeout, http.StatusNoContent, nil)\n if err != nil {\n return fmt.Errorf(\"error deleting datapoints for query: %v :: %v\",\n string(payload), err)\n }\n\n glog.Infof(\"datapoints deleted successfully for query: %+v\", q)\n return nil\n}", "func NewDeleteConnectionParams() *DeleteConnectionParams {\n\tvar ()\n\treturn &DeleteConnectionParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (d *DeleteServerInput) DeleteServerFromVpc(con aws.EstablishConnectionInput) ([]ServerResponse, error) {\n\n\t//get the relative sessions before proceeding further\n\tec2, sesserr := con.EstablishConnection()\n\tif sesserr != nil {\n\t\treturn nil, sesserr\n\t}\n\n\tinstanceSearchInput := DescribeInstanceInput{\n\t\tVpcIds: []string{d.VpcId},\n\t}\n\tsearchInstance, serverr := instanceSearchInput.GetServersFromNetwork(con)\n\tif serverr != nil {\n\t\treturn nil, serverr\n\t}\n\n\tinsatanceids := make([]string, 0)\n\tfor _, instanceid := range searchInstance {\n\t\tinsatanceids = append(insatanceids, instanceid.InstanceId)\n\t}\n\n\tresult, servDelErr := ec2.DeleteInstance(\n\t\t&aws.DeleteComputeInput{\n\t\t\tInstanceIds: insatanceids,\n\t\t},\n\t)\n\tif servDelErr != nil {\n\t\treturn nil, servDelErr\n\t}\n\n\tdeleteResponse := make([]ServerResponse, 0)\n\n\tif d.GetRaw == true {\n\t\tdeleteResponse = append(deleteResponse, ServerResponse{DeleteInstRaw: result, Cloud: \"Amazon\"})\n\t\treturn deleteResponse, nil\n\t}\n\n\tfor _, instance := range result.TerminatingInstances {\n\t\tdeleteResponse = append(deleteResponse, ServerResponse{InstanceId: *instance.InstanceId, CurrentState: *instance.CurrentState.Name})\n\t}\n\n\treturn deleteResponse, nil\n}" ]
[ "0.6481638", "0.64309806", "0.6342348", "0.63145113", "0.5944483", "0.5763756", "0.57178444", "0.55930096", "0.5547575", "0.552483", "0.55066556", "0.54640764", "0.54458916", "0.54458576", "0.5346924", "0.5314311", "0.5297005", "0.52524036", "0.5237436", "0.5221654", "0.52190953", "0.51913697", "0.5169679", "0.51311237", "0.5125531", "0.51102036", "0.50756323", "0.5068353", "0.50630546", "0.5054059", "0.5052514", "0.50479347", "0.5041428", "0.50311327", "0.4985072", "0.49716765", "0.49665654", "0.4964768", "0.49468154", "0.4942976", "0.49429238", "0.49425006", "0.49289572", "0.49132553", "0.49119636", "0.49106064", "0.4903901", "0.48945504", "0.4892324", "0.4870461", "0.48613605", "0.48568967", "0.4856762", "0.4848714", "0.4843111", "0.48428467", "0.48364007", "0.48191577", "0.4816486", "0.48066136", "0.4800354", "0.47991675", "0.47900638", "0.47805253", "0.4779058", "0.47756076", "0.47657338", "0.47623435", "0.4761948", "0.4759169", "0.47569883", "0.4755911", "0.47541675", "0.47539034", "0.47537303", "0.47490713", "0.47427124", "0.47416475", "0.47342125", "0.4709819", "0.47092122", "0.47032654", "0.47010744", "0.47008866", "0.46978405", "0.4693917", "0.46903083", "0.46885103", "0.46799314", "0.4677279", "0.46743703", "0.46609992", "0.46589944", "0.465899", "0.46577734", "0.46564135", "0.46540034", "0.46507874", "0.46437615", "0.46398214" ]
0.68518025
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) DeleteAmazonConnectionExecute(r ApiDeleteAmazonConnectionRequest) (*_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.DeleteAmazonConnection") if err != nil { return nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return nil, reportError("xApiVersion is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarHTTPResponse, newErr } newErr.model = v return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarHTTPResponse, newErr } newErr.model = v return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 404 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarHTTPResponse, newErr } newErr.model = v return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarHTTPResponse, newErr } newErr.model = v } return localVarHTTPResponse, newErr } return localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.7777472", "0.7582237", "0.741292", "0.7358592", "0.7292706", "0.72179556", "0.72150666", "0.7154164", "0.7144244", "0.70236844", "0.6968861", "0.69574517", "0.6857601", "0.68203115", "0.6786843", "0.67499226", "0.6732799", "0.6726702", "0.664588", "0.66373837", "0.66341907", "0.66192603", "0.6618354", "0.65951604", "0.6592189", "0.6544029", "0.65052474", "0.6500035", "0.6499713", "0.6493198", "0.6459492", "0.64537424", "0.64339274", "0.64231", "0.6411837", "0.6354237", "0.6342012", "0.6331562", "0.63293886", "0.63235724", "0.63210624", "0.63129383", "0.63012326", "0.62950426", "0.62711006", "0.6269801", "0.62694305", "0.62559414", "0.62376016", "0.61896044", "0.61866677", "0.6157971", "0.61576515", "0.6157038", "0.61556566", "0.6138981", "0.61365765", "0.61309266", "0.61302364", "0.61298376", "0.6119938", "0.61105776", "0.6102657", "0.6093387", "0.609142", "0.6079346", "0.6078881", "0.6075695", "0.6045966", "0.6045463", "0.60427797", "0.6032737", "0.603158", "0.6027389", "0.60167104", "0.60026646", "0.5987349", "0.5974702", "0.5971437", "0.59703684", "0.5965762", "0.59478134", "0.5939073", "0.59338975", "0.59321105", "0.5925759", "0.5913415", "0.59012485", "0.58960927", "0.5890233", "0.5883923", "0.58764994", "0.5875759", "0.58713603", "0.58534265", "0.5852063", "0.5849181", "0.58465594", "0.5846279", "0.58363706", "0.58326805" ]
0.0
-1
/ GetAllAmazonConnections Method for GetAllAmazonConnections
func (a *AmazonConnectionsApiService) GetAllAmazonConnections(ctx _context.Context) ApiGetAllAmazonConnectionsRequest { return ApiGetAllAmazonConnectionsRequest{ ApiService: a, ctx: ctx, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetAllConnection() ([]*ConnectionItem, error) {\n\tvar items []*ConnectionItem\n\terr := dynamodb.ScanAll(connectionTable, &items)\n\treturn items, err\n}", "func (a *AmazonConnectionsApiService) GetAllAmazonConnectionsExecute(r ApiGetAllAmazonConnectionsRequest) (AmazonConnectionsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnectionsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.GetAllAmazonConnections\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (f *IBMPICloudConnectionClient) GetAll(powerinstanceid string, timeout time.Duration) (*models.CloudConnections, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsGetallParamsWithTimeout(timeout).WithCloudInstanceID(powerinstanceid)\n\tresp, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsGetall(params, ibmpisession.NewAuth(f.session, powerinstanceid))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get all cloud connection %s\", err)\n\t}\n\treturn resp.Payload, nil\n}", "func (t *Tracer) GetActiveConnections(_ string) (*network.Connections, error) {\n\treturn nil, ebpf.ErrNotImplemented\n}", "func (h *VPCPeeringConnectionsHandler) List(project, vpcID string) ([]*VPCPeeringConnection, error) {\n\tvpc, err := h.client.VPCs.Get(project, vpcID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vpc.PeeringConnections, nil\n}", "func (cr *ConnectionRegistry) GetAllConnections() (map[string]*Connection, error) {\n\treturn cr.list, nil\n}", "func (m *OrganizationManager) Connections(id string, opts ...RequestOption) (c *OrganizationConnectionList, err error) {\n\terr = m.Request(\"GET\", m.URI(\"organizations\", id, \"enabled_connections\"), &c, applyListDefaults(opts))\n\treturn\n}", "func (obj *Doc) GetConnections(ctx context.Context) ([]*Connection, error) {\n\tresult := &struct {\n\t\tConnections []*Connection `json:\"qConnections\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetConnections\", result)\n\treturn result.Connections, err\n}", "func ListConnections(c *cli.Context) error {\n\tconnectionsList, err := book.Open()\n\tif err != nil {\n\t\tlog.Fatal(\"error while opening the book: \", err)\n\t\treturn err\n\t}\n\n\tprintln(\"List of all SSH connections :\")\n\tfor _, connection := range connections.PrettifyList(connectionsList) {\n\t\tprintln(connection)\n\t}\n\n\treturn nil\n}", "func GetConnections() client.RpcMethod {\n\treq := &client.TemplateRpcMethod{}\n\t_ = json.Unmarshal([]byte(\"{\\\"MethodName\\\":\\\"GetConnections\\\",\\\"Desc\\\":\\\"Returns a list of peers that we are currently connected to\\\",\\\"Method\\\":\\\"POST\\\",\\\"Url\\\":\\\"get_connections\\\",\\\"JsonTemplate\\\":\\\"{}\\\",\\\"ValInfo\\\":null}\"), req)\n\treturn req\n}", "func (client *Client) Connections() (Connections, error) {\n\tvar conns Connections\n\t_, err := client.doSync(\"GET\", \"/v2/interfaces\", nil, nil, nil, &conns)\n\treturn conns, err\n}", "func (a *AmazonConnectionsApiService) GetAmazonConnectionById(ctx _context.Context, amazonConnectionId string) ApiGetAmazonConnectionByIdRequest {\n\treturn ApiGetAmazonConnectionByIdRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (m *GraphBaseServiceClient) Connections()(*icabdee72951e77325f237b36d388a199c87e65f67652b6bb85723aba847d7e83.ConnectionsRequestBuilder) {\n return icabdee72951e77325f237b36d388a199c87e65f67652b6bb85723aba847d7e83.NewConnectionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Connections()(*icabdee72951e77325f237b36d388a199c87e65f67652b6bb85723aba847d7e83.ConnectionsRequestBuilder) {\n return icabdee72951e77325f237b36d388a199c87e65f67652b6bb85723aba847d7e83.NewConnectionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (o GetWorkspacePrivateEndpointConnectionResultOutput) Connections() GetWorkspacePrivateEndpointConnectionConnectionArrayOutput {\n\treturn o.ApplyT(func(v GetWorkspacePrivateEndpointConnectionResult) []GetWorkspacePrivateEndpointConnectionConnection {\n\t\treturn v.Connections\n\t}).(GetWorkspacePrivateEndpointConnectionConnectionArrayOutput)\n}", "func (h *Handler) ListConnections(_ context.Context, orgID *grpc_organization_go.OrganizationId) (*grpc_application_network_go.ConnectionInstanceList, error) {\n\tvErr := entities.ValidOrganizationId(orgID)\n\tif vErr != nil {\n\t\treturn nil, conversions.ToGRPCError(vErr)\n\t}\n\treturn h.Manager.ListConnections(orgID)\n}", "func (a API) Connections(client *http.Client, user_id string, fields Fields, params url.Values) (j map[string]interface{}, err error) {\r\n\treturn a.request(client, \"connections\", map[string]string{\r\n\t\t\"id\": getUserIdString(user_id),\r\n\t\t\"fields\": fields.Encode(),\r\n\t}, params)\r\n}", "func GetAllFederatedConnections(cmd *cobra.Command, args []string) error {\n\n\tclient, err := auth.GetClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\tresp, err := client.SearchService.GetAllFederatedConnections()\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonx.Pprint(cmd, resp)\n\treturn nil\n}", "func (c *Client) GetConnections(parentID string) ([]ConnectionEntity, error) {\n\tlog.Info(\"Inside client.go, in GetConnections FUNCTION\")\n\tvar entity ConnectionsEntity\n\tif err := c.getDeepConnections(parentID, &entity); err != nil {\n\t\treturn nil, err\n\t}\n\treturn entity.Connections, nil\n\n}", "func (o *Output) GetConnections() map[Connection]bool {\n\t// get connections\n\to.Lock()\n\tconnections := o.Connections\n\to.Unlock()\n\treturn connections\n}", "func (client *NginxClient) GetConnections() (*Connections, error) {\n\tvar cons Connections\n\terr := client.get(\"connections\", &cons)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get connections: %w\", err)\n\t}\n\treturn &cons, nil\n}", "func (c *DaemonClient) GetConnections() (ConnectionResponse, error) {\n\tvar cr ConnectionResponse\n\tif err := call(c.endpoint, \"get_connections\", nil, &cr); err != nil {\n\t\treturn cr, err\n\t}\n\treturn cr, nil\n}", "func (r *RPCClientNode) Connections() (cs []string, err error) {\n\terr = r.r.c.Call(\"node.Connections\", struct{}{}, &cs)\n\treturn\n}", "func (obj *Doc) GetConnectionsRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tConnections json.RawMessage `json:\"qConnections\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetConnections\", result)\n\treturn result.Connections, err\n}", "func (na *NetAdapter) Connections() []*NetConnection {\n\tna.connectionsLock.RLock()\n\tdefer na.connectionsLock.RUnlock()\n\n\tnetConnections := make([]*NetConnection, 0, len(na.connections))\n\n\tfor netConnection := range na.connections {\n\t\tnetConnections = append(netConnections, netConnection)\n\t}\n\n\treturn netConnections\n}", "func (n *Node) Connections() []*MessageConnection {\n conns := make([]*MessageConnection, len(n.connections))\n i := 0\n for _, conn := range n.connections {\n conns[i] = conn\n i++\n }\n return conns\n}", "func (obj *identity) Connections() Connections {\n\treturn obj.conns\n}", "func (obj *conns) All() []Connection {\n\treturn obj.list\n}", "func (m *VirtualEndpoint) GetOnPremisesConnections()([]CloudPcOnPremisesConnectionable) {\n val, err := m.GetBackingStore().Get(\"onPremisesConnections\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcOnPremisesConnectionable)\n }\n return nil\n}", "func (ep *Endpoint) ActiveConnections() int {\n\treturn ep.activeConnections\n}", "func (a *AmazonConnectionsApiService) GetAmazonConnectionByIdExecute(r ApiGetAmazonConnectionByIdRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.GetAmazonConnectionById\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (gw *Gateway) GetConnections(f func(c Connection) bool) ([]Connection, error) {\n\tvar conns []Connection\n\tvar err error\n\tgw.strand(\"GetConnections\", func() {\n\t\tconns, err = gw.getConnections(f)\n\t})\n\treturn conns, err\n}", "func Connections(inetFamily uint8) ([]Conn, error) {\n\treturn ConnectionsSize(0, inetFamily)\n}", "func ActionConnections() carapace.Action {\n\treturn carapace.ActionCallback(func(c carapace.Context) carapace.Action {\n\t\treturn carapace.ActionExecCommand(\"nmcli\", \"--terse\", \"connection\", \"show\")(func(output []byte) carapace.Action {\n\t\t\tlines := strings.Split(string(output), \"\\n\")\n\t\t\tvals := make([]string, (len(lines)-1)*2)\n\t\t\tfor index, line := range lines[:len(lines)-1] {\n\t\t\t\tparts := strings.Split(line, \":\")\n\t\t\t\tvals[index*2] = parts[0]\n\t\t\t\tvals[index*2+1] = parts[2] + \" \" + parts[1]\n\t\t\t}\n\t\t\treturn carapace.ActionValuesDescribed(vals...)\n\t\t})\n\t}).Tag(\"network connections\")\n}", "func toVPNGatewayConnections(v interface{}) (connections, error) {\n\tif v == nil {\n\t\treturn connections{}, nil\n\t}\n\n\tvpnGatewayConnections, ok := v.(connections)\n\tif !ok {\n\t\treturn connections{}, microerror.Maskf(wrongTypeError, \"expected '%T', got '%T'\", connections{}, v)\n\t}\n\n\treturn vpnGatewayConnections, nil\n}", "func (h *ConnectionPoolsHandler) List(ctx context.Context, project, serviceName string) ([]*ConnectionPool, error) {\n\t// There's no API for listing connection pool entries. Need to get them from\n\t// service info instead\n\tservice, err := h.client.Services.Get(ctx, project, serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service.ConnectionPools, nil\n}", "func (r *Connection) Get(c *yarf.Context) error {\n\ttx, err := r.Beginx()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Commit() // read-only tx\n\n\tcompat := c.Request.URL.Query().Get(\"closedcompat\") != \"false\"\n\n\tif c.Param(\"from\") != \"\" && c.Param(\"to\") != \"\" {\n\t\tconnection, err := types.GetConnection(tx, c.Param(\"from\"), c.Param(\"to\"), compat)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tac := &apiConnection{}\n\t\tdeepcopier.Copy(*connection).To(ac)\n\t\tdata := apiConnectionWrapper{\n\t\t\tapiConnection: *ac,\n\t\t\tFromID: connection.From.ID,\n\t\t\tToID: connection.To.ID,\n\t\t}\n\n\t\tRenderData(c, data, \"s-maxage=10\")\n\t} else {\n\t\tconnections, err := types.GetConnections(tx, compat)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tapiconnections := make([]apiConnectionWrapper, len(connections))\n\t\tfor i := range connections {\n\t\t\tac := &apiConnection{}\n\t\t\tdeepcopier.Copy(*connections[i]).To(ac)\n\t\t\tapiconnections[i] = apiConnectionWrapper{\n\t\t\t\tapiConnection: *ac,\n\t\t\t\tFromID: connections[i].From.ID,\n\t\t\t\tToID: connections[i].To.ID,\n\t\t\t}\n\t\t}\n\t\tRenderData(c, apiconnections, \"s-maxage=10\")\n\t}\n\treturn nil\n}", "func (f *IBMPICloudConnectionClient) Get(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsGetParams) (*models.CloudConnection, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsGetParams().WithCloudInstanceID(pclouddef.CloudInstanceID).WithCloudConnectionID(pclouddef.CloudConnectionID)\n\tresp, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsGet(params, ibmpisession.NewAuth(f.session, pclouddef.CloudInstanceID))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get cloud connection %s\", err)\n\t}\n\treturn resp.Payload, nil\n}", "func awsConnect(i *AwsInfo) *s3.Bucket {\n\tAWSAuth := aws.Auth{\n\t\tAccessKey: i.AccessKey,\n\t\tSecretKey: i.SecretKey,\n\t}\n\tregion := aws.USEast\n\tconnection := s3.New(AWSAuth, region)\n\n\treturn connection.Bucket(i.Bucket)\n}", "func (a *Admin) Connections() IAdminConnections {\n\treturn a.cnx\n}", "func (g *Graph) GetConnections(id, label string) []string {\n\treturn g.Connections[id+\":\"+label]\n}", "func (c *icdService) Connections() Connections {\n\treturn newConnectionAPI(c.Client)\n}", "func (o AppGatewayOutput) AllocatedConnections() AllocatedConnectionResponseArrayOutput {\n\treturn o.ApplyT(func(v *AppGateway) AllocatedConnectionResponseArrayOutput { return v.AllocatedConnections }).(AllocatedConnectionResponseArrayOutput)\n}", "func (cs *CachingAuthClient) GetTunnelConnections(clusterName string) (conns []services.TunnelConnection, err error) {\n\terr = cs.try(func() error {\n\t\tconns, err = cs.ap.GetTunnelConnections(clusterName)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tif trace.IsConnectionProblem(err) {\n\t\t\treturn cs.presence.GetTunnelConnections(clusterName)\n\t\t}\n\t\treturn conns, err\n\t}\n\tif err := cs.presence.DeleteTunnelConnections(clusterName); err != nil {\n\t\tif !trace.IsNotFound(err) {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\tfor _, conn := range conns {\n\t\tcs.setTTL(conn)\n\t\tif err := cs.presence.UpsertTunnelConnection(conn); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\treturn conns, err\n}", "func (a *Client) GetAPI24Connections(params *GetAPI24ConnectionsParams) (*GetApi24ConnectionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAPI24ConnectionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetAPI24Connections\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/2.4/connections\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetAPI24ConnectionsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetApi24ConnectionsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetAPI24Connections: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (cs *CachingAuthClient) GetAllTunnelConnections() (conns []services.TunnelConnection, err error) {\n\terr = cs.try(func() error {\n\t\tconns, err = cs.ap.GetAllTunnelConnections()\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tif trace.IsConnectionProblem(err) {\n\t\t\treturn cs.presence.GetAllTunnelConnections()\n\t\t}\n\t\treturn conns, err\n\t}\n\tif err := cs.presence.DeleteAllTunnelConnections(); err != nil {\n\t\tif !trace.IsNotFound(err) {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\tfor _, conn := range conns {\n\t\tcs.setTTL(conn)\n\t\tif err := cs.presence.UpsertTunnelConnection(conn); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\treturn conns, err\n}", "func (app *App) Amazon() *amazon.Client {\n\tclient := app.AmazonClients[currentClient]\n\tcurrentClient++\n\tapp.Log.Printf(\"Using Amazon Client %d of %d\", currentClient, len(app.AmazonClients))\n\tif currentClient == len(app.AmazonClients) {\n\t\tcurrentClient = 0\n\t}\n\treturn client\n}", "func ConnectionsSize(bufferSize int, inetFamily uint8) ([]Conn, error) {\n\tvar conns []Conn\n\tqueryAllConnections(bufferSize, func(c Conn) {\n\t\tconns = append(conns, c)\n\t}, inetFamily)\n\treturn conns, nil\n}", "func (r GetConnectionsRequest) Send(ctx context.Context) (*GetConnectionsResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &GetConnectionsResponse{\n\t\tGetConnectionsOutput: r.Request.Data.(*GetConnectionsOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (cp *ConnPool) GetConns() (map[string]*Conn, error) {\n\treturn cp.conns, nil\n}", "func (client ProcessesClient) ListConnectionsResponder(resp *http.Response) (result ConnectionCollection, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (r *RPCClientNode) ConnectionsOfFeed(\n\tpk cipher.PubKey, // :\n) (\n\tcs []string, // :\n\terr error, // :\n) {\n\n\terr = r.r.c.Call(\"node.ConnectionsOfFeed\", pk, &cs)\n\treturn\n}", "func (prof *Profile) Connections() (*Connections, error) {\n\traw, err := prof.ln.SearchPeople(\n\t\t\"\",\n\t\t&golinkedin.PeopleSearchFilter{\n\t\t\tNetwork: []string{golinkedin.Rank1, golinkedin.Rank2, golinkedin.Rank3},\n\t\t\tConnectionOf: prof.ID,\n\t\t\tResultType: golinkedin.ResultPeople,\n\t\t},\n\t\t&golinkedin.QueryContext{\n\t\t\tSpellCorrectionEnabled: true,\n\t\t},\n\t\tgolinkedin.OriginMemberProfileCannedSearch,\n\t)\n\n\tif err != nil {\n\t\treturn nil, parseErrMsg(err.Error())\n\t}\n\n\tminiProfs := make([]Profile, 0)\n\tfor _, elm := range raw.Elements {\n\t\tif elm.Type == golinkedin.TypeSearchHits {\n\t\t\tfor _, innerElm := range elm.Elements {\n\t\t\t\tminiProfs = append(miniProfs, *composeMiniProfile(innerElm.Image.Attributes[0].MiniProfile))\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tconns := &Connections{\n\t\tProfiles: miniProfs,\n\t\tStart: raw.Paging.Start,\n\t\tCount: raw.Paging.Count,\n\t\tTotal: raw.Paging.Total,\n\t\tpnode: raw,\n\t}\n\n\treturn conns, nil\n}", "func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) {\n\tfor {\n\t\tvar currentPool = 0\n\t\tpools := b.getConnPools(false /* not already locked */)\n\t\tif len(pools) == 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"No connection pool found\")\n\t\t} else if len(pools) > 1 { // choose a random connection\n\t\t\tcurrentPool = rand.Intn(len(pools))\n\t\t} // if only one pool, currentPool defaults to 0, i.e., the only pool\n\n\t\t// get the pool\n\t\tpool := pools[currentPool]\n\t\tconn, err := pool.Get()\n\t\tif err != errClosedPool {\n\t\t\treturn conn, pool, err\n\t\t}\n\n\t\t// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...\n\t}\n}", "func (fmd *FakeMysqlDaemon) GetAllPrivsConnection(ctx context.Context) (*dbconnpool.DBConnection, error) {\n\treturn dbconnpool.NewDBConnection(ctx, fmd.db.ConnParams())\n}", "func (a *AmazonConnectionsApiService) CreateAmazonConnection(ctx _context.Context) ApiCreateAmazonConnectionRequest {\n\treturn ApiCreateAmazonConnectionRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (p *Process) Connections() ([]net.ConnectionStat, error) {\n\treturn p.ConnectionsWithContext(context.Background())\n}", "func (gw *Gateway) GetTrustConnections() []string {\n\tvar conn []string\n\tgw.strand(\"GetTrustConnections\", func() {\n\t\tconn = gw.d.pex.Trusted().ToAddrs()\n\t})\n\treturn conn\n}", "func getCurrentConnections(source string, timestamp time.Time) ([]TcpConnection, error) {\n\tdata, err := ioutil.ReadFile(source)\n\tif err != nil {\n\t\treturn []TcpConnection{}, err\n\t}\n\n\tconnectionsRaw := string(data)\n\ttcpConnections := parseListOfConnections(connectionsRaw, timestamp)\n\n\treturn tcpConnections, nil\n}", "func (gb *gcpBalancer) getConnectionPoolSize() int {\n\tgb.mu.Lock()\n\tdefer gb.mu.Unlock()\n\treturn len(gb.scRefs)\n}", "func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) {\n\tfor {\n\t\tvbm := b.VBServerMap()\n\t\tif len(vbm.VBucketMap) < int(vb) {\n\t\t\treturn nil, nil, fmt.Errorf(\"go-couchbase: vbmap smaller than vbucket list: %v vs. %v\",\n\t\t\t\tvb, vbm.VBucketMap)\n\t\t}\n\t\tmasterId := vbm.VBucketMap[vb][0]\n\t\tif masterId < 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"go-couchbase: No master for vbucket %d\", vb)\n\t\t}\n\t\tpool := b.getConnPool(masterId)\n\t\tconn, err := pool.Get()\n\t\tif err != errClosedPool {\n\t\t\treturn conn, pool, err\n\t\t}\n\t\t// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...\n\t}\n}", "func (m *OrganizationManager) Connection(id string, connectionID string, opts ...RequestOption) (c *OrganizationConnection, err error) {\n\terr = m.Request(\"GET\", m.URI(\"organizations\", id, \"enabled_connections\", connectionID), &c, opts...)\n\treturn\n}", "func Connections(s *parapet.Server) {\n\t_connections.init()\n\n\ts.ConnState = _connections.connState\n}", "func (q *quicTracer) getConnectionsInfo() (conns []connInfo) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tfor _, tracer := range q.tracers {\n\t\tconns = append(conns, connInfo{\n\t\t\tid: tracer.id,\n\t\t\tpackets: tracer.packets,\n\t\t})\n\t}\n\n\treturn conns\n}", "func (a API) GetConnectionCount(cmd *None) (e error) {\n\tRPCHandlers[\"getconnectioncount\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (cp *singleConnectionPool) URLs() []*url.URL { return []*url.URL{cp.connection.URL} }", "func (store *MongoStore) GetConnectionIDs(ctx context.Context) ([]string, error) {\n\treturn store.readConnections(ctx)\n}", "func (a *AmazonConnectionsApiService) CreateAmazonConnectionExecute(r ApiCreateAmazonConnectionRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.CreateAmazonConnection\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\tif r.amazonConnectionSpec == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"amazonConnectionSpec is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\t// body params\n\tlocalVarPostBody = r.amazonConnectionSpec\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *VPCPeeringConnectionsHandler) Get(\n\tproject string,\n\tvpcID string,\n\tpeerCloudAccount string,\n\tpeerVPC string,\n) (*VPCPeeringConnection, error) {\n\t// There's no API call for getting individual peering connection. Get the VPC\n\t// info and filter from there\n\tvpc, err := h.client.VPCs.Get(project, vpcID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pc := range vpc.PeeringConnections {\n\t\tif pc.PeerCloudAccount == peerCloudAccount && pc.PeerVPC == peerVPC {\n\t\t\treturn pc, nil\n\t\t}\n\t}\n\n\terr = Error{Message: \"Peering connection not found\", Status: 404}\n\treturn nil, err\n}", "func (client *WANCommonInterfaceConfig1) GetMaximumActiveConnections() (NewMaximumActiveConnections uint16, err error) {\n\treturn client.GetMaximumActiveConnectionsCtx(context.Background())\n}", "func (m *GraphBaseServiceClient) ConnectionsById(id string)(*i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.ExternalConnectionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"externalConnection%2Did\"] = id\n }\n return i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.NewExternalConnectionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) ConnectionsById(id string)(*i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.ExternalConnectionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"externalConnection%2Did\"] = id\n }\n return i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.NewExternalConnectionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func getConnection(t testing.TB, ch *Channel, direction int) *ConnectionRuntimeState {\n\tstate := ch.IntrospectState(nil)\n\n\tfor _, peer := range state.RootPeers {\n\t\tvar connections []ConnectionRuntimeState\n\t\tif direction == inbound {\n\t\t\tconnections = peer.InboundConnections\n\t\t} else {\n\t\t\tconnections = peer.OutboundConnections\n\t\t}\n\n\t\tassert.True(t, len(connections) <= 1, \"Too many connections found: %+v\", connections)\n\t\tif len(connections) == 1 {\n\t\t\treturn &connections[0]\n\t\t}\n\t}\n\n\tassert.FailNow(t, \"No connections found\")\n\treturn nil\n}", "func (c Client) GetAll() (GetAllConnectorsResponse, error) {\n\tresp := GetAllConnectorsResponse{}\n\tvar connectors []string\n\n\tstatusCode, err := c.Request(http.MethodGet, \"connectors\", nil, &connectors)\n\tif err != nil {\n\t\treturn GetAllConnectorsResponse{}, err\n\t}\n\n\tresp.Code = statusCode\n\tresp.Connectors = connectors\n\n\treturn resp, nil\n}", "func (c *Catalog) ConnectMultipleTags(service string, tags []string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error) {\n\treturn c.service(service, tags, q, true)\n}", "func (gw *Gateway) GetDefaultConnections() []string {\n\tvar conns []string\n\tgw.strand(\"GetDefaultConnections\", func() {\n\t\tconns = make([]string, len(gw.d.Config.DefaultConnections))\n\t\tcopy(conns[:], gw.d.Config.DefaultConnections[:])\n\t})\n\treturn conns\n}", "func NewAllConnectionsOK() *AllConnectionsOK {\n return &AllConnectionsOK{\n }\n}", "func NewConnections(size int) *Connections {\n\tc := new(Connections)\n\tc.slice = make([]Connection, 0, size)\n\treturn c\n}", "func ListBuckets(w http.ResponseWriter, r *http.Request) *appError {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n response, _ := s3Request(s3, \"\", \"GET\", \"/\", make(map[string][]string), \"\")\n listBucketsResp := &ListBucketsResp{}\n xml.NewDecoder(strings.NewReader(response.Body)).Decode(listBucketsResp)\n buckets := []string{}\n for _, bucket := range listBucketsResp.Buckets {\n buckets = append(buckets, bucket.Name)\n }\n rendering.JSON(w, http.StatusOK, buckets)\n\n return nil\n}", "func ListBuckets(w http.ResponseWriter, r *http.Request) *appError {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n response, _ := s3Request(s3, \"\", \"GET\", \"/\", make(map[string][]string), \"\")\n listBucketsResp := &ListBucketsResp{}\n xml.NewDecoder(strings.NewReader(response.Body)).Decode(listBucketsResp)\n buckets := []string{}\n for _, bucket := range listBucketsResp.Buckets {\n buckets = append(buckets, bucket.Name)\n }\n rendering.JSON(w, http.StatusOK, buckets)\n\n return nil\n}", "func (r *VpcEndpointConnectionNotification) ConnectionEvents() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"connectionEvents\"])\n}", "func (t *Tracer) getConnections(active []network.ConnectionStats) ([]network.ConnectionStats, uint64, error) {\n\tmp, err := t.getMap(bytecode.ConnMap)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving the bpf %s map: %s\", bytecode.ConnMap, err)\n\t}\n\n\ttcpMp, err := t.getMap(bytecode.TcpStatsMap)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving the bpf %s map: %s\", bytecode.TcpStatsMap, err)\n\t}\n\n\tportMp, err := t.getMap(bytecode.PortBindingsMap)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving the bpf %s map: %s\", bytecode.PortBindingsMap, err)\n\t}\n\n\tudpPortMp, err := t.getMap(bytecode.UdpPortBindingsMap)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving the bpf %s map: %s\", bytecode.UdpPortBindingsMap, err)\n\t}\n\n\tlatestTime, ok, err := t.getLatestTimestamp()\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving latest timestamp: %s\", err)\n\t}\n\n\tif !ok { // if no timestamps have been captured, there can be no packets\n\t\treturn nil, 0, nil\n\t}\n\n\tclosedPortBindings, err := t.populatePortMapping(portMp, t.portMapping)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error populating port mapping: %s\", err)\n\t}\n\n\tclosedUDPPortBindings, err := t.populatePortMapping(udpPortMp, t.udpPortMapping)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error populating UDP port mapping: %s\", err)\n\t}\n\n\t// Iterate through all key-value pairs in map\n\tkey, stats := &ConnTuple{}, &ConnStatsWithTimestamp{}\n\tseen := make(map[ConnTuple]struct{})\n\tvar expired []*ConnTuple\n\tentries := mp.IterateFrom(unsafe.Pointer(&ConnTuple{}))\n\tfor entries.Next(unsafe.Pointer(key), unsafe.Pointer(stats)) {\n\t\tif stats.isExpired(latestTime, t.timeoutForConn(key)) {\n\t\t\texpired = append(expired, key.copy())\n\t\t\tif key.isTCP() {\n\t\t\t\tatomic.AddInt64(&t.expiredTCPConns, 1)\n\t\t\t}\n\t\t\tatomic.AddInt64(&t.closedConns, 1)\n\t\t} else {\n\t\t\tconn := connStats(key, stats, t.getTCPStats(tcpMp, key, seen))\n\t\t\tconn.Direction = t.determineConnectionDirection(&conn)\n\n\t\t\tif t.shouldSkipConnection(&conn) {\n\t\t\t\tatomic.AddInt64(&t.skippedConns, 1)\n\t\t\t} else {\n\t\t\t\t// lookup conntrack in for active\n\t\t\t\tconn.IPTranslation = t.conntracker.GetTranslationForConn(conn)\n\t\t\t\tactive = append(active, conn)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := entries.Err(); err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"unable to iterate connection map: %s\", err)\n\t}\n\n\t// Remove expired entries\n\tt.removeEntries(mp, tcpMp, expired)\n\n\t// check for expired clients in the state\n\tt.state.RemoveExpiredClients(time.Now())\n\n\tfor _, key := range closedPortBindings {\n\t\tt.portMapping.RemoveMapping(key)\n\t\t_ = portMp.Delete(unsafe.Pointer(&key))\n\t}\n\n\tfor _, key := range closedUDPPortBindings {\n\t\tt.udpPortMapping.RemoveMapping(key)\n\t\t_ = udpPortMp.Delete(unsafe.Pointer(&key))\n\t}\n\n\t// Get the latest time a second time because it could have changed while we were reading the eBPF map\n\tlatestTime, _, err = t.getLatestTimestamp()\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error retrieving latest timestamp: %s\", err)\n\t}\n\n\treturn active, latestTime, nil\n}", "func (b *redisBackend) Connections() int64 { return atomic.LoadInt64(&b.connections) }", "func (mp *MongoPool) GetOpenConnections() []*mongo.Client {\n\tvar conns []*mongo.Client\n\tfor _, conn := range mp.pool {\n\t\terr := conn.Ping(mp.getContextTimeOut(), readpref.Primary())\n\t\tif err == nil {\n\t\t\tconns = append(conns, conn)\n\t\t}\n\t}\n\treturn conns\n}", "func (agr *apiGatewayResource) GetAllByNamespace(ctx context.Context,\n\tgetAPIGatewayOptions *platform.GetAPIGatewaysOptions,\n\texportFunction bool) (map[string]restful.Attributes, error) {\n\tresponse := map[string]restful.Attributes{}\n\n\tapiGateways, err := agr.getPlatform().GetAPIGateways(ctx, getAPIGatewayOptions)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to get api gateways\")\n\t}\n\n\tfor _, apiGateway := range apiGateways {\n\t\tif exportFunction {\n\t\t\tresponse[apiGateway.GetConfig().Meta.Name] = agr.export(ctx, apiGateway)\n\t\t} else {\n\n\t\t\t// create a map of attributes keyed by the api-gateway id (name)\n\t\t\tresponse[apiGateway.GetConfig().Meta.Name] = agr.apiGatewayToAttributes(apiGateway)\n\t\t}\n\t}\n\n\treturn response, nil\n}", "func (a *AmazonConnectionsApiService) BrowseCloudNetworks(ctx _context.Context, amazonConnectionId string) ApiBrowseCloudNetworksRequest {\n\treturn ApiBrowseCloudNetworksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tamazonConnectionId: amazonConnectionId,\n\t}\n}", "func (al *AccessLayer) GetStationsAndConnections() ([]*m.Station, error) {\n\tquery := `\n\t\tSELECT DISTINCT\n\t\t\ts.stop_name, s2.stop_name\n\t\tFROM stops s\n\t\tINNER JOIN stop_times st\n\t\t\tON st.stop_id = s.stop_id\n\t\tINNER JOIN trips t\n\t\t\tON t.trip_id = st.trip_id\n\t\tINNER JOIN routes r\n\t\t\tON r.route_id = t.route_id\n\t\tINNER JOIN (\n\t\t\tSELECT DISTINCT\n\t\t\t\ts.stop_name,\n\t\t\t\tr.route_short_name,\n\t\t\t\tr.route_id,\n\t\t\t\tst.arrival_time,\n\t\t\t\tt.trip_id\n\t\t\tFROM stops s\n\t\t\tINNER JOIN stop_times st\n\t\t\t\tON st.stop_id = s.stop_id\n\t\t\tINNER JOIN trips t\n\t\t\t\tON t.trip_id = st.trip_id\n\t\t\tINNER JOIN routes r\n\t\t\t\tON r.route_id = t.route_id\n\t\t) s2\n\t\tON r.route_id = s2.route_id\n\t\t AND s.stop_name != s2.stop_name\n\t\t AND t.trip_id = s2.trip_id\n\t\t AND st.arrival_time < s2.arrival_time\n\t`\n\trows, err := al.AL.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnSet := make(map[string]set.Interface)\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar stop, connection string\n\t\tif err := rows.Scan(&stop, &connection); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif conns, ok := connSet[stop]; ok {\n\t\t\tconns.Add(connection)\n\t\t} else {\n\t\t\ts := set.New(set.ThreadSafe)\n\t\t\ts.Add(connection)\n\t\t\tconnSet[stop] = s\n\n\t\t}\n\t}\n\n\tconnections := []*m.Station{}\n\tfor stop, conns := range connSet {\n\t\tconnList := []*m.Station{}\n\t\tconns.Each(func(item interface{}) bool {\n\t\t\tconnList = append(connList, &m.Station{Name: item.(string)})\n\t\t\treturn true\n\t\t})\n\t\tconnections = append(connections, &m.Station{\n\t\t\tName: stop,\n\t\t\tConnections: connList,\n\t\t})\n\t}\n\n\treturn connections, nil\n}", "func (c *authenticatedConnection) Endpoints() []string {\n\treturn c.conn.Endpoints()\n}", "func (c *Client) GetTotalConnections() int {\n\treturn len(c.connections)\n}", "func queryAllConnections(bufferSize int, cb func(Conn), inetFamily uint8) error {\n\ts, lsa, err := connectNetfilter(bufferSize, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer syscall.Close(s)\n\n\tmsg := ConntrackListReq{\n\t\tHeader: syscall.NlMsghdr{\n\t\t\tLen: syscall.NLMSG_HDRLEN + sizeofGenmsg,\n\t\t\tType: (NFNL_SUBSYS_CTNETLINK << 8) | uint16(IpctnlMsgCtGet),\n\t\t\tFlags: syscall.NLM_F_REQUEST | syscall.NLM_F_DUMP,\n\t\t\tPid: 0,\n\t\t\tSeq: 0,\n\t\t},\n\t\tBody: unix.Nfgenmsg{\n\t\t\tNfgen_family: inetFamily,\n\t\t\tVersion: NFNETLINK_V0,\n\t\t\tRes_id: 0,\n\t\t},\n\t}\n\twb := msg.toWireFormat()\n\t// fmt.Printf(\"msg bytes: %q\\n\", wb)\n\tif err := syscall.Sendto(s, wb, 0, lsa); err != nil {\n\t\treturn err\n\t}\n\n\treturn readMsgs(s, cb)\n}", "func (i *ServerInfo) TotalConnections() int64 {\n\treturn i.connections.Value()\n}", "func AWSGetClusters(accessKeyId, secretAccessKey, region string) (string, error) {\n\tvar clusters []*eks.Cluster\n\tvar names []*string\n\tvar nextToken *string\n\n\tcred := credentials.NewStaticCredentials(accessKeyId, secretAccessKey, \"\")\n\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(region), Credentials: cred})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\teksClient := eks.New(sess)\n\n\tfor {\n\t\tc, err := eksClient.ListClusters(&eks.ListClustersInput{NextToken: nextToken})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tnames = append(names, c.Clusters...)\n\n\t\tif c.NextToken == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tnextToken = c.NextToken\n\t}\n\n\tfor _, name := range names {\n\t\tcluster, err := eksClient.DescribeCluster(&eks.DescribeClusterInput{Name: name})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif *cluster.Cluster.Status == eks.ClusterStatusActive {\n\t\t\tclusters = append(clusters, cluster.Cluster)\n\t\t}\n\t}\n\n\tif clusters != nil {\n\t\tb, err := json.Marshal(clusters)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn string(b), nil\n\t}\n\n\treturn \"\", nil\n}", "func (c *Client) GetAWSCredsAndClients() error {\n\tvar (\n\t\tsess *session.Session\n\t\tidentity *sts.GetCallerIdentityOutput\n\t\terr error\n\t)\n\n\tif sess, err = session.NewSession(); err != nil {\n\t\treturn err\n\t}\n\n\tsvc := sts.New(sess)\n\n\tif identity, err = svc.GetCallerIdentity(&sts.GetCallerIdentityInput{}); err != nil {\n\t\treturn err\n\t}\n\n\tarn := aws.StringValue(identity.Arn)\n\tlog.Infof(\"[KUBEDOG] Credentials: %v\", arn)\n\n\tc.ASClient = autoscaling.New(sess)\n\n\treturn nil\n}", "func (xmem *XmemNozzle) initializeConnection() (err error) {\n\txmem.Logger().Debugf(\"xmem.config= %v\", xmem.config.connectStr)\n\txmem.Logger().Debugf(\"poolName=%v\", xmem.getPoolName(xmem.config.connectStr))\n\tpool, err := base.ConnPoolMgr().GetOrCreatePool(xmem.getPoolName(xmem.config.connectStr), xmem.config.connectStr, xmem.config.bucketName, xmem.config.password, base.DefaultConnectionSize)\n\tif err == nil {\n\t\txmem.memClient, err = pool.Get()\n\t}\n\treturn err\n}", "func (c *Client) UserConnections() ([]discord.Connection, error) {\n\tvar conn []discord.Connection\n\treturn conn, c.RequestJSON(&conn, \"GET\", EndpointMe+\"/connections\")\n}", "func (s *serverMetrics) getConnectionGauge() *prometheus.GaugeVec {\n\treturn s.connections\n}", "func ExampleWebAppsClient_GetPrivateEndpointConnectionSlot() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armappservice.NewWebAppsClient(\"34adfa4f-cedf-4dc0-ba29-b6d1a69ab345\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.GetPrivateEndpointConnectionSlot(ctx,\n\t\t\"rg\",\n\t\t\"testSite\",\n\t\t\"connection\",\n\t\t\"stage\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (p *BoxPeer) Conns() *sync.Map {\n\treturn p.conns\n}", "func ExampleWebAppsClient_GetPrivateEndpointConnection() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armappservice.NewWebAppsClient(\"34adfa4f-cedf-4dc0-ba29-b6d1a69ab345\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.GetPrivateEndpointConnection(ctx,\n\t\t\"rg\",\n\t\t\"testSite\",\n\t\t\"connection\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func getBrokerUrls() (map[int]config.HostPort, error) {\n\tres := make(map[int]config.HostPort)\n\tbrokers, err := zookeeper.Brokers()\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tfor _, id := range brokers {\n\t\tbroker, err := zookeeper.Broker(id)\n\t\tif err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres[id] = config.HostPort{Host: broker.Host, Port: broker.Port}\n\t}\n\treturn res, nil\n}" ]
[ "0.62138623", "0.6150556", "0.61153036", "0.57789856", "0.5767368", "0.5758743", "0.5661916", "0.5637961", "0.5596926", "0.5580691", "0.5553659", "0.55218357", "0.54997754", "0.54997754", "0.5407078", "0.5388597", "0.537643", "0.53553075", "0.52937514", "0.5272092", "0.52701104", "0.52117956", "0.5210844", "0.52099377", "0.52059215", "0.5166071", "0.51408553", "0.5138402", "0.51215893", "0.50812936", "0.50552285", "0.504386", "0.5033697", "0.5023677", "0.5019258", "0.5002187", "0.49786183", "0.49680948", "0.49553385", "0.49503854", "0.49356923", "0.4926857", "0.4911559", "0.48873898", "0.48843464", "0.48825023", "0.48704854", "0.4858283", "0.48521024", "0.48459992", "0.4845493", "0.48451948", "0.48206213", "0.48194566", "0.47925687", "0.47912672", "0.47889635", "0.47840482", "0.47583783", "0.47414678", "0.4739878", "0.47386375", "0.4729995", "0.47182205", "0.47112647", "0.47054872", "0.47050014", "0.47004613", "0.4681309", "0.4677028", "0.4676213", "0.4676213", "0.465616", "0.46512544", "0.4649691", "0.46469465", "0.4630759", "0.46299508", "0.46270043", "0.46270043", "0.46219245", "0.46140796", "0.4597356", "0.4592064", "0.45872155", "0.45836073", "0.4568832", "0.4550542", "0.4541429", "0.45385876", "0.45328534", "0.4521342", "0.45149994", "0.44997224", "0.4497696", "0.44968438", "0.4488376", "0.44850904", "0.44784683", "0.44774035" ]
0.7852334
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) GetAllAmazonConnectionsExecute(r ApiGetAllAmazonConnectionsRequest) (AmazonConnectionsPage, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue AmazonConnectionsPage ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.GetAllAmazonConnections") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
/ GetAmazonConnectionById Method for GetAmazonConnectionById
func (a *AmazonConnectionsApiService) GetAmazonConnectionById(ctx _context.Context, amazonConnectionId string) ApiGetAmazonConnectionByIdRequest { return ApiGetAmazonConnectionByIdRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) GetAmazonConnectionByIdExecute(r ApiGetAmazonConnectionByIdRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.GetAmazonConnectionById\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func GetConnectionByID(ac *atmi.ATMICtx, connid int64) *ExCon {\n\n\t//If it is compiled we will lookup by hash.\n\n\ttstamp := connid >> 24\n\tid := connid & 0xffffff\n\n\tac.TpLogInfo(\"Compiled id: %d, tstamp: %d, simple id: %d\",\n\t\tconnid, tstamp, id)\n\n\tif tstamp > 0 {\n\t\tac.TpLogInfo(\"Looks like compiled connection id - lookup by hash\")\n\n\t\tMConnMutex.Lock()\n\t\tret := MConnectionsComp[connid]\n\t\tMConnMutex.Unlock()\n\n\t\tif ret == nil {\n\t\t\tac.TpLogError(\"Connection by id %d not found\", connid)\n\t\t\treturn nil\n\t\t}\n\n\t\tMarkConnAsBusy(ac, ret)\n\n\t\treturn ret\n\t} else {\n\t\tac.TpLogInfo(\"Search by simple connection id\")\n\n\t\tMConnMutex.Lock()\n\t\tret := MConnectionsSimple[connid]\n\t\tMConnMutex.Unlock()\n\n\t\tif ret == nil {\n\t\t\tac.TpLogError(\"Connection by id %d not found\", connid)\n\t\t}\n\n\t\tMarkConnAsBusy(ac, ret)\n\n\t\treturn ret\n\t}\n\n\t//If it is simple, then we will iterate over the connections\n\t//Should never happen\n\t//return nil\n\n}", "func (m *GraphBaseServiceClient) ConnectionsById(id string)(*i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.ExternalConnectionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"externalConnection%2Did\"] = id\n }\n return i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.NewExternalConnectionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) ConnectionsById(id string)(*i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.ExternalConnectionItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"externalConnection%2Did\"] = id\n }\n return i728b903f252feeed28263ff4e0da95a1d0f7c831116db07abb00de41db959892.NewExternalConnectionItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func getConnectionId(source map[string]interface{}) string {\n\tvalue := \"temp\"\n\tif id, ok := source[\"id\"]; ok {\n\t\tvalue = id.(string);\n\t} else if id, ok := source[\"ccid\"]; ok {\n\t\tvalue = id.(string);\n\t}\n\treturn value\n}", "func (r *PrivateVirtualInterface) ConnectionId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"connectionId\"])\n}", "func (o ConnectionIamBindingOutput) ConnectionId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ConnectionIamBinding) pulumi.StringOutput { return v.ConnectionId }).(pulumi.StringOutput)\n}", "func (o GetVpcEndpointConnectionsConnectionOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointConnectionsConnection) string { return v.Id }).(pulumi.StringOutput)\n}", "func (m *OrganizationManager) Connection(id string, connectionID string, opts ...RequestOption) (c *OrganizationConnection, err error) {\n\terr = m.Request(\"GET\", m.URI(\"organizations\", id, \"enabled_connections\", connectionID), &c, opts...)\n\treturn\n}", "func (c Connector) Get(name string) (*Connection, error) {\n\tconnection, ok := c[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"connection name %s not found\", name)\n\t}\n\treturn connection, nil\n}", "func (f *IBMPICloudConnectionClient) Get(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsGetParams) (*models.CloudConnection, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsGetParams().WithCloudInstanceID(pclouddef.CloudInstanceID).WithCloudConnectionID(pclouddef.CloudConnectionID)\n\tresp, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsGet(params, ibmpisession.NewAuth(f.session, pclouddef.CloudInstanceID))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get cloud connection %s\", err)\n\t}\n\treturn resp.Payload, nil\n}", "func (c *Connection) Id() ConnectionId {\n\treturn c.serverConnId\n}", "func (m *AmazonResourceEvidence) GetAmazonResourceId()(*string) {\n val, err := m.GetBackingStore().Get(\"amazonResourceId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func NewConnectionID(connectionString string, adabasID *ID) (connection *Connection, err error) {\n\tonce.Do(onceBody)\n\tparts := strings.Split(connectionString, \";\")\n\tif parts[0] != \"acj\" && parts[0] != \"ada\" {\n\t\treturn nil, adatypes.NewGenericError(51)\n\t}\n\tvar adabasToData *Adabas\n\tvar adabasToMap *Adabas\n\tvar mapName string\n\tvar adabasMap *Map\n\n\tvar repositoryParameter [][]string\n\tvar repository *Repository\n\tadatypes.Central.Log.Debugf(\"New connection to %s\", connectionString)\n\tfor _, p := range parts {\n\t\tadatypes.Central.Log.Debugf(\"Work on %s\", p)\n\t\tswitch {\n\t\tcase p == \"acj\" || p == \"ada\":\n\t\tcase strings.HasPrefix(p, \"target=\"):\n\t\t\ttarget := strings.Split(parts[1], \"=\")\n\t\t\tadatypes.Central.Log.Debugf(\"Connection to target : %s\", target[1])\n\t\t\turl, err := NewURL(target[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tadabasToData = adabasID.getAdabas(url)\n\t\tcase strings.HasPrefix(p, \"map\"):\n\t\t\tif strings.Contains(p, \"=\") {\n\t\t\t\tmaps := strings.Split(parts[1], \"=\")\n\t\t\t\tadatypes.Central.Log.Debugf(\"Connection to map : %v\", maps)\n\t\t\t\tmapName = maps[1]\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"inmap\"):\n\t\t\tif strings.Contains(p, \"=\") {\n\t\t\t\tmaps := strings.Split(parts[1], \"=\")\n\t\t\t\tadatypes.Central.Log.Debugf(\"Connection to map : %v\", maps)\n\t\t\t\t// mapName = inmapMapName\n\t\t\t\tadabasMap = NewAdabasMap(inmapMapName)\n\t\t\t\tref := strings.Split(maps[1], \",\")\n\t\t\t\turl, err := NewURL(ref[0])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tadabasMap.Data = &DatabaseURL{URL: *url}\n\t\t\t\tfnr := 0\n\t\t\t\tif len(ref) > 1 {\n\t\t\t\t\tfnr, err = strconv.Atoi(ref[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif fnr < 0 || fnr > 32000 {\n\t\t\t\t\treturn nil, adatypes.NewGenericError(116, fnr)\n\t\t\t\t}\n\t\t\t\tadabasMap.Data.Fnr = Fnr(fnr)\n\t\t\t\tadatypes.Central.Log.Debugf(\"inmap %s,%d\", url, fnr)\n\t\t\t\tadabasToData = adabasID.getAdabas(url)\n\t\t\t\t// NewAdabas(url, adabasID)\n\t\t\t\t// if err != nil {\n\t\t\t\t// \treturn nil, err\n\t\t\t\t// }\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"config=\"):\n\t\t\te := strings.Index(p, \"]\")\n\t\t\ta := strings.Index(p, \"[\") + 1\n\t\t\tconfig := p[a:e]\n\t\t\tre := regexp.MustCompile(`(?m)([^,]*),([[:digit:]]*)\\|?`)\n\t\t\trr := re.FindAllStringSubmatch(config, 10)\n\t\t\tfor _, r1 := range rr {\n\t\t\t\tvar r = []string{r1[1], r1[2]}\n\t\t\t\trepositoryParameter = append(repositoryParameter, r)\n\t\t\t}\n\t\tcase strings.HasPrefix(p, \"auth=\"):\n\t\t\tx := strings.Index(p, \",\")\n\t\t\tif x != -1 {\n\t\t\t\tx++\n\t\t\t\terr := parseAuth(adabasID, p[x:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, adatypes.NewGenericError(84, p)\n\t\t}\n\t}\n\n\tif len(repositoryParameter) > 0 {\n\t\tfor _, r := range repositoryParameter {\n\t\t\tadatypes.Central.Log.Debugf(\"Add repository search of dbid=%s fnr=%s\", r[0], r[1])\n\t\t\tfnr, serr := strconv.Atoi(r[1])\n\t\t\tif serr != nil {\n\t\t\t\treturn nil, serr\n\t\t\t}\n\t\t\tif fnr < 0 || fnr > 32000 {\n\t\t\t\treturn nil, adatypes.NewGenericError(116, fnr)\n\t\t\t}\n\t\t\turl, err := NewURL(r[0])\n\t\t\t//NewAdabas(r[0], adabasID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tadabasToMap = adabasID.getAdabas(url)\n\t\t\tadatypes.Central.Log.Debugf(\"Created adabas reference\")\n\t\t\trepository = NewMapRepository(adabasToMap.URL, Fnr(fnr))\n\t\t\tadatypes.Central.Log.Debugf(\"Created repository\")\n\t\t}\n\t} else {\n\t\t// TODO check id\n\t\tif adabasToData == nil {\n\t\t\tadabasToData, _ = NewAdabas(1, adabasID)\n\t\t}\n\t\tadabasToMap = adabasToData\n\t}\n\n\tconnection = &Connection{adabasToData: adabasToData, ID: adabasID,\n\t\tadabasToMap: adabasToMap, adabasMap: adabasMap, repository: repository}\n\tif mapName != \"\" {\n\t\terr = connection.searchRepository(adabasID, repository, mapName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tadatypes.Central.Log.Debugf(\"Ready created connection handle %s\", connection.String())\n\treturn\n}", "func (r *RPCIngressGateway) getConn(connID uint16) (net.Conn, error) {\n\tconnIfc, ok := r.cm.Get(connID)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no conn with key %d\", connID)\n\t}\n\n\treturn idmanager.AssertConn(connIfc)\n}", "func (a *DeploymentsApiService) ApiDeploymentsIdConnectionInfoGet(ctx context.Context, id string) ApiApiDeploymentsIdConnectionInfoGetRequest {\n\treturn ApiApiDeploymentsIdConnectionInfoGetRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func (r *Connection) Get(c *yarf.Context) error {\n\ttx, err := r.Beginx()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Commit() // read-only tx\n\n\tcompat := c.Request.URL.Query().Get(\"closedcompat\") != \"false\"\n\n\tif c.Param(\"from\") != \"\" && c.Param(\"to\") != \"\" {\n\t\tconnection, err := types.GetConnection(tx, c.Param(\"from\"), c.Param(\"to\"), compat)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tac := &apiConnection{}\n\t\tdeepcopier.Copy(*connection).To(ac)\n\t\tdata := apiConnectionWrapper{\n\t\t\tapiConnection: *ac,\n\t\t\tFromID: connection.From.ID,\n\t\t\tToID: connection.To.ID,\n\t\t}\n\n\t\tRenderData(c, data, \"s-maxage=10\")\n\t} else {\n\t\tconnections, err := types.GetConnections(tx, compat)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tapiconnections := make([]apiConnectionWrapper, len(connections))\n\t\tfor i := range connections {\n\t\t\tac := &apiConnection{}\n\t\t\tdeepcopier.Copy(*connections[i]).To(ac)\n\t\t\tapiconnections[i] = apiConnectionWrapper{\n\t\t\t\tapiConnection: *ac,\n\t\t\t\tFromID: connections[i].From.ID,\n\t\t\t\tToID: connections[i].To.ID,\n\t\t\t}\n\t\t}\n\t\tRenderData(c, apiconnections, \"s-maxage=10\")\n\t}\n\treturn nil\n}", "func conn(ctx context.Context) *jsonrpc2.Conn { return ctx.Value(connKey{}).(*jsonrpc2.Conn) }", "func (r *ExternalConnectionRequest) Get(ctx context.Context) (resObj *ExternalConnection, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) {\n\tfor {\n\t\tvbm := b.VBServerMap()\n\t\tif len(vbm.VBucketMap) < int(vb) {\n\t\t\treturn nil, nil, fmt.Errorf(\"go-couchbase: vbmap smaller than vbucket list: %v vs. %v\",\n\t\t\t\tvb, vbm.VBucketMap)\n\t\t}\n\t\tmasterId := vbm.VBucketMap[vb][0]\n\t\tif masterId < 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"go-couchbase: No master for vbucket %d\", vb)\n\t\t}\n\t\tpool := b.getConnPool(masterId)\n\t\tconn, err := pool.Get()\n\t\tif err != errClosedPool {\n\t\t\treturn conn, pool, err\n\t\t}\n\t\t// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...\n\t}\n}", "func (o GetVbrPconnAssociationsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVbrPconnAssociationsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (c *CardScanClient) Get(ctx context.Context, id int) (*CardScan, error) {\n\treturn c.Query().Where(cardscan.ID(id)).Only(ctx)\n}", "func (u *User) Connection(connID uint64) *Connection {\n\tconnection, ok := u.connMap.GetEx(connID)\n\tif !ok {\n\t\tconnection = emptyConnection()\n\t}\n\treturn connection\n}", "func GetConnection(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ConnectionState, opts ...pulumi.ResourceOption) (*Connection, error) {\n\tvar resource Connection\n\terr := ctx.ReadResource(\"gcp:bigquery/connection:Connection\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (ci *ConnectionInfo) GetID() (id string) {\n\tci.RLock()\n\tid = ci.id\n\tci.RUnlock()\n\treturn\n}", "func (h *ConnectionPoolsHandler) Get(ctx context.Context, project, serviceName, poolName string) (*ConnectionPool, error) {\n\t// There's no API for getting individual connection pool entry. List instead and filter from there\n\tpools, err := h.List(ctx, project, serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pool := range pools {\n\t\tif pool.PoolName == poolName {\n\t\t\treturn pool, nil\n\t\t}\n\t}\n\n\terr = Error{Message: fmt.Sprintf(\"Connection pool with name %v not found\", poolName), Status: 404}\n\treturn nil, err\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func (cs ConnectionSlice) Get(ii int) interface{} {\n\treturn cs[ii]\n}", "func (sdk *SDKSteps) GetConnection(from, to string) (*didexClient.Connection, error) {\n\tconnections, err := sdk.context.DIDExchangeClients[from].QueryConnections(&didexClient.QueryConnectionsParams{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s failed to fetch their connections : %w\", from, err)\n\t}\n\n\tfor _, c := range connections {\n\t\tif c.TheirLabel == to {\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"no connection %s -> %s\", from, to)\n}", "func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) {\n\tfor {\n\t\tvar currentPool = 0\n\t\tpools := b.getConnPools(false /* not already locked */)\n\t\tif len(pools) == 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"No connection pool found\")\n\t\t} else if len(pools) > 1 { // choose a random connection\n\t\t\tcurrentPool = rand.Intn(len(pools))\n\t\t} // if only one pool, currentPool defaults to 0, i.e., the only pool\n\n\t\t// get the pool\n\t\tpool := pools[currentPool]\n\t\tconn, err := pool.Get()\n\t\tif err != errClosedPool {\n\t\t\treturn conn, pool, err\n\t\t}\n\n\t\t// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...\n\t}\n}", "func (conn *Connection) ID() string {\n\treturn conn.id\n}", "func GetHiveConn() (conn *HiveConnection, err error) {\n //configMu.Lock()\n //keyspaceConfig, ok := configMap[keyspace]\n //if !ok {\n // configMu.Unlock()\n // return nil, errors.New(\"Must define keyspaces before you can get connection\")\n //}\n //configMu.Unlock()\n\n return getConnFromPool()\n}", "func (db *DB) Get(_ context.Context, id string) (*databroker.Record, error) {\n\tc := db.pool.Get()\n\tdefer c.Close()\n\n\tb, err := redis.Bytes(c.Do(\"HGET\", db.recordType, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db.toPbRecord(b)\n}", "func (c *TagClient) Get(ctx context.Context, id int) (*Tag, error) {\n\treturn c.Query().Where(tag.ID(id)).Only(ctx)\n}", "func GetConnectionWithKey(key string) (SQLConnector, error) {\n\n\tpool.mu.Lock()\n\tdefer pool.mu.Unlock()\n\n\tif _, ok := pool.connections[key]; !ok {\n\t\treturn nil, NewInvalidConnectionKeyError(fmt.Sprintf(\"Invalid connection key %s\", key))\n\t}\n\n\t<-pool.ok[key]\n\n\treturn pool.connections[key].getConnection(), nil\n}", "func (app *App) Amazon() *amazon.Client {\n\tclient := app.AmazonClients[currentClient]\n\tcurrentClient++\n\tapp.Log.Printf(\"Using Amazon Client %d of %d\", currentClient, len(app.AmazonClients))\n\tif currentClient == len(app.AmazonClients) {\n\t\tcurrentClient = 0\n\t}\n\treturn client\n}", "func (c *MockConnectionsLookup) GetConnectionRecord(id string) (*connection.Record, error) {\n\tswitch {\n\tcase c.ConnRecordErr != nil:\n\t\treturn nil, c.ConnRecordErr\n\tcase c.ConnRecord != nil:\n\t\treturn c.ConnRecord, nil\n\t}\n\n\treturn nil, errors.New(\"invalid test setup - need either connRecord or error\")\n}", "func getAWSAccountID(ia string) string {\n\treturn strings.Split(ia, \":\")[1]\n}", "func (db *DB) Get(ctx context.Context, id string) (rec *databroker.Record, err error) {\n\tc := db.pool.Get()\n\t_, span := trace.StartSpan(ctx, \"databroker.redis.Get\")\n\tdefer span.End()\n\tdefer recordOperation(ctx, time.Now(), \"get\", err)\n\tdefer c.Close()\n\n\tb, err := redis.Bytes(c.Do(\"HGET\", db.recordType, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db.toPbRecord(b)\n}", "func (o GetWorkspacePrivateEndpointConnectionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetWorkspacePrivateEndpointConnectionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (a *AmazonConnectionsApiService) GetAllAmazonConnections(ctx _context.Context) ApiGetAllAmazonConnectionsRequest {\n\treturn ApiGetAllAmazonConnectionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (h *VPCPeeringConnectionsHandler) Get(\n\tproject string,\n\tvpcID string,\n\tpeerCloudAccount string,\n\tpeerVPC string,\n) (*VPCPeeringConnection, error) {\n\t// There's no API call for getting individual peering connection. Get the VPC\n\t// info and filter from there\n\tvpc, err := h.client.VPCs.Get(project, vpcID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pc := range vpc.PeeringConnections {\n\t\tif pc.PeerCloudAccount == peerCloudAccount && pc.PeerVPC == peerVPC {\n\t\t\treturn pc, nil\n\t\t}\n\t}\n\n\terr = Error{Message: \"Peering connection not found\", Status: 404}\n\treturn nil, err\n}", "func (f *IBMPICloudConnectionClient) Delete(id, cloudInstanceID string) (models.Object, *models.JobReference, error) {\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsDeleteParamsWithTimeout(helpers.PIDeleteTimeOut).WithCloudInstanceID(cloudInstanceID).WithCloudConnectionID(id)\n\trespOk, respAccepted, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsDelete(params, ibmpisession.NewAuth(f.session, cloudInstanceID))\n\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(errors.DeleteCloudConnectionOperationFailed, id, err)\n\t}\n\tif respOk != nil {\n\t\treturn respOk.Payload, nil, nil\n\t}\n\tif respAccepted != nil {\n\t\treturn nil, respAccepted.Payload, nil\n\t}\n\treturn nil, nil, nil\n}", "func getConnection(agentConfig configReader.SnmpAgent) (connection, error) {\n\tif conn, ok := snmpConnections[agentConfig.Address]; ok {\n\t\treturn conn, nil\n\t}\n\thandler, err := snmp_.newHandler(agentConfig)\n\tif err != nil {\n\t\treturn connection{}, err\n\t}\n\tsnmpConnections[agentConfig.Address] = connection{handler: handler, mtx: &sync.Mutex{}}\n\treturn snmpConnections[agentConfig.Address], nil\n}", "func (p *pool) Get(connectionString string) (*RestClient, error) {\n\tkey, err := makeKey(connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c, ok := p.clients[key]; ok {\n\t\treturn c, nil\n\t}\n\n\tc, err := NewRestClient(connectionString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := p.defaults.apply(c); err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.clients[key] = c\n\treturn c, nil\n}", "func (m *ApiConnectorsIdentityApiConnectorItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ApiConnectorsIdentityApiConnectorItemRequestBuilderGetRequestConfiguration)(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.IdentityApiConnectorable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.requestAdapter.Send(ctx, requestInfo, iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.CreateIdentityApiConnectorFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.IdentityApiConnectorable), nil\n}", "func (d *APA102Driver) Connection() gobot.Connection { return d.connection.(gobot.Connection) }", "func (conn *Connection) GetByID(id interface{}, i interface{}) error {\n\treturn conn.collection.FindId(id).One(i)\n}", "func (stc *ScatterConn) getConnection(keyspace, shard string) (*ShardConn, error) {\n\tstc.connsMu.Lock()\n\tdefer stc.connsMu.Unlock()\n\n\tkey := fmt.Sprintf(\"%s.%s.%s\", keyspace, stc.tabletType, shard)\n\tsdc, ok := stc.shardConns[key]\n\tif !ok {\n\t\tsdc = NewShardConn(stc.balancerMap, keyspace, shard, stc.tabletType, stc.retryDelay, stc.retryCount)\n\t\tstc.shardConns[key] = sdc\n\t}\n\tif stc.transactionId != 0 {\n\t\tif txid := sdc.TransactionId(); txid != 0 {\n\t\t\tif txid != stc.transactionIds[sdc] {\n\t\t\t\t// This error will cause the transaction to abort.\n\t\t\t\treturn nil, sdc.WrapError(fmt.Errorf(\"not_in_tx: connection is in a different transaction\"))\n\t\t\t}\n\t\t\treturn sdc, nil\n\t\t}\n\t\tif err := sdc.Begin(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstc.transactionIds[sdc] = sdc.TransactionId()\n\t\tstc.commitOrder = append(stc.commitOrder, sdc)\n\t\treturn sdc, nil\n\t}\n\t// This check is a failsafe. Should never happen.\n\tif sdc.TransactionId() != 0 {\n\t\tlog.Warningf(\"Unexpected: connection %#v is in transaction\", sdc)\n\t\tsdc.Rollback()\n\t}\n\treturn sdc, nil\n}", "func (m *AmazonResourceEvidence) GetAmazonAccountId()(*string) {\n val, err := m.GetBackingStore().Get(\"amazonAccountId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (a *AmazonConnectionsApiService) DeleteAmazonConnectionExecute(r ApiDeleteAmazonConnectionRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.DeleteAmazonConnection\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c VpnCredential) GetID() string { return c.ID }", "func (o AwsVpcPeeringConnectionOutput) AwsVpcPeeringConnectionId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsVpcPeeringConnectionId }).(pulumi.StringOutput)\n}", "func (vtc *VTConn) getConnection(keyspace, shard string) (*ShardConn, error) {\n\tvtc.connsMu.Lock()\n\tdefer vtc.connsMu.Unlock()\n\n\tkey := fmt.Sprintf(\"%s.%s.%s\", keyspace, vtc.tabletType, shard)\n\tsdc, ok := vtc.shardConns[key]\n\tif !ok {\n\t\tsdc = NewShardConn(vtc.balancerMap, vtc.tabletProtocol, keyspace, shard, vtc.tabletType, vtc.retryDelay, vtc.retryCount)\n\t\tvtc.shardConns[key] = sdc\n\t}\n\tif vtc.transactionId != 0 {\n\t\tif txid := sdc.TransactionId(); txid != 0 {\n\t\t\tif txid != vtc.transactionIds[sdc] {\n\t\t\t\t// This error will cause the transaction to abort.\n\t\t\t\treturn nil, sdc.WrapError(fmt.Errorf(\"not_in_tx: connection is in a different transaction\"))\n\t\t\t}\n\t\t\treturn sdc, nil\n\t\t}\n\t\tif err := sdc.Begin(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvtc.transactionIds[sdc] = sdc.TransactionId()\n\t\tvtc.commitOrder = append(vtc.commitOrder, sdc)\n\t\treturn sdc, nil\n\t}\n\t// This check is a failsafe. Should never happen.\n\tif sdc.TransactionId() != 0 {\n\t\tlog.Warningf(\"Unexpected: connection %#v is in transaction\", sdc)\n\t\tsdc.Rollback()\n\t}\n\treturn sdc, nil\n}", "func (c *MockClient) GetConnection(connectionID string) (*didexchange.Connection, error) {\n\tif c.GetConnectionErr != nil {\n\t\treturn nil, c.GetConnectionErr\n\t}\n\n\treturn &didexchange.Connection{Record: &connection.Record{ConnectionID: connectionID}}, nil\n}", "func GetConn(name string, batchNum int64) (con *Connection) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tps, ok := poolMaps[name]\n\tif !ok {\n\t\treturn\n\t}\n\tcon = ps[batchNum%int64(len(ps))]\n\treturn\n}", "func (client *WANCommonInterfaceConfig1) GetActiveConnection(NewActiveConnectionIndex uint16) (NewActiveConnDeviceContainer string, NewActiveConnectionServiceID string, err error) {\n\treturn client.GetActiveConnectionCtx(context.Background(),\n\t\tNewActiveConnectionIndex,\n\t)\n}", "func GetClient(id string) *ConnectedClient {\n client, exists := currentClients[id]\n\n if (exists) {\n return client\n }\n\n return nil\n}", "func (a *AmazonConnectionsApiService) CreateAmazonConnectionExecute(r ApiCreateAmazonConnectionRequest) (AmazonConnection, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnection\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.CreateAmazonConnection\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\tif r.amazonConnectionSpec == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"amazonConnectionSpec is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\t// body params\n\tlocalVarPostBody = r.amazonConnectionSpec\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (impl *IPv4Pool) GetConnection() *gorm.DB {\n\treturn base.GetConnection()\n}", "func (bc *BoltClient) Get(byname string) ([]byte, error) {\n\t// acc := account.Account{}\n\tvar id []byte\n\terr := bc.boltDB.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bc.BucketName))\n\t\t// accountBytes := b.Get([]byte(byname))\n\t\t// accountBytes := b.Get([]byte(byname))\n\t\tid = b.Get([]byte(byname))\n\t\t// err := json.Unmarshal(accountBytes, &acc)\n\t\t// if err != nil {\n\t\t// return errors.New(\"Error when unmarshal db []bytes to acc struct\")\n\t\t// }\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\t// return account.Account{}, err\n\t\treturn nil, err\n\t}\n\t// return acc, nil\n\treturn id, nil\n}", "func awsConnect(i *AwsInfo) *s3.Bucket {\n\tAWSAuth := aws.Auth{\n\t\tAccessKey: i.AccessKey,\n\t\tSecretKey: i.SecretKey,\n\t}\n\tregion := aws.USEast\n\tconnection := s3.New(AWSAuth, region)\n\n\treturn connection.Bucket(i.Bucket)\n}", "func (s *compassConnectionLister) Get(name string) (*v1alpha1.CompassConnection, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"compassconnection\"), name)\n\t}\n\treturn obj.(*v1alpha1.CompassConnection), nil\n}", "func (c *IPClient) Get(ctx context.Context, id uuid.UUID) (*IP, error) {\n\treturn c.Query().Where(ip.ID(id)).Only(ctx)\n}", "func GetCurrencyID(hostURL string, hostPort int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\treturn makePostRequest(hostURL, hostPort, \"getcurrencyid\", params)\n}", "func (b *backend) clientIAM(ctx context.Context, s logical.Storage, region, accountID string) (*iam.IAM, error) {\n\tstsRole, err := b.stsRoleForAccount(ctx, s, accountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.configMutex.RLock()\n\tif b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil {\n\t\tdefer b.configMutex.RUnlock()\n\t\t// If the client object was already created, return it\n\t\treturn b.IAMClientsMap[region][stsRole], nil\n\t}\n\n\t// Release the read lock and acquire the write lock\n\tb.configMutex.RUnlock()\n\tb.configMutex.Lock()\n\tdefer b.configMutex.Unlock()\n\n\t// If the client gets created while switching the locks, return it\n\tif b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil {\n\t\treturn b.IAMClientsMap[region][stsRole], nil\n\t}\n\n\t// Create an AWS config object using a chain of providers\n\tvar awsConfig *aws.Config\n\tawsConfig, err = b.getClientConfig(ctx, s, region, stsRole, accountID, \"iam\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif awsConfig == nil {\n\t\treturn nil, fmt.Errorf(\"could not retrieve valid assumed credentials\")\n\t}\n\n\t// Create a new IAM client object, cache it and return the same\n\tclient := iam.New(session.New(awsConfig))\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"could not obtain iam client\")\n\t}\n\tif _, ok := b.IAMClientsMap[region]; !ok {\n\t\tb.IAMClientsMap[region] = map[string]*iam.IAM{stsRole: client}\n\t} else {\n\t\tb.IAMClientsMap[region][stsRole] = client\n\t}\n\treturn b.IAMClientsMap[region][stsRole], nil\n}", "func (c *IAM) getAWSConfigurator(ctx context.Context, database types.Database) (*awsClient, error) {\n\tidentity, err := c.getAWSIdentity(ctx, database)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tpolicyName, err := c.getPolicyName()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn newAWS(ctx, awsConfig{\n\t\tclients: c.cfg.Clients,\n\t\tpolicyName: policyName,\n\t\tidentity: identity,\n\t\tdatabase: database,\n\t})\n}", "func (c *CardClient) Get(ctx context.Context, id int) (*Card, error) {\n\treturn c.Query().Where(card.ID(id)).Only(ctx)\n}", "func GetConnection(url string) (*amqp.Connection, error) {\n\trlock.Lock()\n\tdefer rlock.Unlock()\n\n\tif c, ok := connections[url]; ok {\n\t\treturn c, nil\n\t}\n\n\treturn dial(url)\n}", "func (o *Organization) Get(id int64) error {\n\tdb, err := sqlx.Connect(settings.Settings.Database.DriverName, settings.Settings.GetDbConn())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\terr = db.Get(&o, \"SELECT * FROM organization WHERE id=$1\", id)\n\tif err == sql.ErrNoRows {\n\t\treturn ErrOrganizationNotFound\n\t} else if err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *ComplaintClient) Get(ctx context.Context, id int) (*Complaint, error) {\n\treturn c.Query().Where(complaint.ID(id)).Only(ctx)\n}", "func (a *AmazonConnectionsApiService) GetAllAmazonConnectionsExecute(r ApiGetAllAmazonConnectionsRequest) (AmazonConnectionsPage, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AmazonConnectionsPage\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.GetAllAmazonConnections\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Registry) GetConnection(s server.Server, ip string, port string) {\n\ts.NewConnection(ip, port)\n}", "func (bcm *BasicConnectionManager) GetConnection(connStr string) (*sql.DB, error) {\n\tif len(connStr) == 0 {\n\t\treturn nil, fmt.Errorf(\"the connStr parameter cannot be empty\")\n\t}\n\n\t// Check if a connection already exists before lock it\n\tconn, ok := bcm.connectionPool[connStr]\n\tif ok {\n\t\t// Reuse it if already exists\n\t\treturn conn, nil\n\t}\n\n\t// Now try to lock it for double check\n\tbcm.mutex.Lock()\n\tdefer bcm.mutex.Unlock() // Release the lock after function returns\n\n\t// Check again if the connection already exists in the pool\n\tconn, ok = bcm.connectionPool[connStr]\n\tif ok {\n\t\t// Reuse it if already exists\n\t\treturn conn, nil\n\t}\n\n\t// Create a new one\n\tnewConn, err := bcm.openConnection(connStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add the new connection to the pool\n\tbcm.connectionPool[connStr] = newConn\n\treturn newConn, nil\n}", "func (n *Server) Get(ctx context.Context, id string, timeout time.Duration) (SessionInteraction, error) {\n\treturn n.connServer.Get(ctx, id, timeout)\n}", "func (r *Redis) Conn(ctx context.Context) Conn {\n\treturn r.pool.Get(ctx)\n}", "func GetId() string {\n\treturn _broker.brokerId\n}", "func (ci ConnectionInfo) AsConnectionInfo() (*ConnectionInfo, bool) {\n\treturn &ci, true\n}", "func (p *Persister) GetConnection(ctx context.Context) *pop.Connection {\n\tvar c = ctx.Value(transactionKey)\n\tif c != nil {\n\t\tif conn, ok := c.(*pop.Connection); ok {\n\t\t\treturn conn\n\t\t}\n\t}\n\n\treturn p.c\n}", "func (c *OperativerecordClient) Get(ctx context.Context, id int) (*Operativerecord, error) {\n\treturn c.Query().Where(operativerecord.ID(id)).Only(ctx)\n}", "func (c *MsgConnection) ID() string {\n\treturn c.id\n}", "func (sc *SmartContract) GetObjectByKey(stub shim.ChaincodeStubInterface, id string) interface{} {\n\tvar outputObject interface{}\n\trecordBytes, err := stub.GetState(id)\n\tif len(recordBytes) > 0 && err == nil {\n\t\tjson.Unmarshal(recordBytes, &outputObject)\n\t\treturn outputObject\n\t}\n\treturn nil\n}", "func (m *ConnManager) Get(k interface{}) (v interface{}, ok bool) {\n\treturn m.connections.Load(k)\n}", "func AmznIDHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\treqID := p.ByName(\"id\")\n\turl := \"http://www.amazon.de/gp/product/\" + reqID\n\t// Make request to Amazon.com to traverse/parse\n\tamznID, err := ExtractInfo(url)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"invalid ID: %s\\nerror: %v\\n\", reqID, err)\n\t}\n\n\tmarshalJSON(w, amznID)\n}", "func (c *Connection) ID() string {\n\treturn fmt.Sprintf(\"[%s@%d_%d]\", c.url, c.id, c.cc)\n}", "func getConsumber(c *cli.Context) error {\n\tid := c.String(\"id\")\n\tusername := c.String(\"username\")\n\n\tvar requestURL string\n\tif id != \"\" {\n\t\trequestURL = fmt.Sprintf(\"%s/%s\", CONSUMER_RESOURCE_OBJECT, id)\n\t} else if username != \"\" {\n\t\trequestURL = fmt.Sprintf(\"%s/%s\", CONSUMER_RESOURCE_OBJECT, username)\n\t} else {\n\t\treturn fmt.Errorf(\"username and id invalid.\")\n\t}\n\n\tctx, cannel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cannel()\n\n\tserverResponse, err := client.GatewayClient.Get(ctx, requestURL, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := ioutil.ReadAll(serverResponse.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttools.IndentFromBody(body)\n\n\treturn nil\n}", "func (sm S3Manager) AWSSessionAccountID(sess *session.Session) (acID string, err error) {\n\tsvc := sts.New(sess)\n\tresult, err := svc.GetCallerIdentity(&sts.GetCallerIdentityInput{})\n\tif err != nil {\n\t\tfmt.Printf(\"Error requesting AWS caller identity: %v\", err.Error())\n\t\treturn\n\t}\n\tacID = *result.Account\n\treturn\n}", "func (r *ConnectionTypesService) Get(profileId int64, id int64) *ConnectionTypesGetCall {\n\tc := &ConnectionTypesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.id = id\n\treturn c\n}", "func (r *Room) GetConn(id string) (*connection.Connection, error) {\n\tr.connlock.Lock()\n\tdefer r.connlock.Unlock()\n\tconn, ok := r.connections[id]\n\n\tif !ok {\n\t\treturn &connection.Connection{}, errors.New(\"Connection doesn't exist\")\n\t}\n\treturn conn, nil\n}", "func GetProductByID(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\n\tfmt.Println(\"Before Len\")\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments.Expected 1 argument\")\n\t}\n\n\tfmt.Println(\"After Len\")\n\n\tquery := `{\n\t\t\t\t\"selector\": {\n\t\t\t\t \"product_id\": {\n\t\t\t\t\t \"$eq\": \"` + args[0] + `\"\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t }`\n\n\tfmt.Println(\"Queeryy =>>>> \\n\" + query)\n\n\t//resultsIterator, err := stub.GetQueryResult(\"{\\\"selector\\\":{\\\"prod_type\\\":\\\"products\\\",\\\"_id\\\":{\\\"$eq\\\": \\\"1\\\"}}}\")\n\n\tresultsIterator, err := stub.GetQueryResult(query)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error fetching reuslts\")\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tfmt.Println(\"After results\")\n\t// counter := 0\n\t//var resultKV\n\tfor resultsIterator.HasNext() {\n\t\tfmt.Println(\"Inside hasnext\")\n\t\t// Get the next element\n\t\tqueryResponse, err := resultsIterator.Next()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Err=\" + err.Error())\n\t\t\treturn shim.Success([]byte(\"Error in parse: \" + err.Error()))\n\t\t}\n\n\t\t// Increment the counter\n\t\t// counter++\n\t\tkey := queryResponse.GetKey()\n\t\tvalue := string(queryResponse.GetValue())\n\n\t\t// Print the receieved result on the console\n\t\tfmt.Printf(\"Result# %s %s \\n\\n\", key, value)\n\t\tb, je := json.Marshal(value)\n\t\tif je != nil {\n\t\t\treturn shim.Error(je.Error())\n\t\t}\n\n\t\treturn shim.Success(b)\n\t}\n\n\t// Close the iterator\n\tresultsIterator.Close()\n\treturn shim.Success(nil)\n\n\t//\treturn shim.Error(\"Could not find any doctors.\")\n\n}", "func (o *UpdateVpnConnectionRequest) GetVpnConnectionIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.VpnConnectionId, true\n}", "func (o RepositoryAssociationRepositoryBitbucketOutput) ConnectionArn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RepositoryAssociationRepositoryBitbucket) string { return v.ConnectionArn }).(pulumi.StringOutput)\n}", "func (s *Storer) Get(ctx context.Context, id string) (accounts.Account, error) {\n\tquery := getSQL(ctx, id)\n\tqueryStr, err := query.PostgreSQLString()\n\tif err != nil {\n\t\treturn accounts.Account{}, err\n\t}\n\trows, err := s.db.Query(queryStr, query.Args()...) //nolint:sqlclosecheck // the closeRows helper isn't picked up\n\tif err != nil {\n\t\treturn accounts.Account{}, err\n\t}\n\tdefer closeRows(ctx, rows)\n\tvar account Account\n\tfor rows.Next() {\n\t\terr = pan.Unmarshal(rows, &account)\n\t\tif err != nil {\n\t\t\treturn accounts.Account{}, err\n\t\t}\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn accounts.Account{}, err\n\t}\n\tif account.ID == \"\" {\n\t\treturn accounts.Account{}, accounts.ErrAccountNotFound\n\t}\n\treturn fromPostgres(account), nil\n}", "func Get(ctx context.Context) (redis.Conn, error) {\n\tif p := GetPool(ctx); p != nil {\n\t\treturn p.GetContext(ctx)\n\t}\n\treturn nil, ErrNotConfigured\n}", "func GetBucketByAuthID(context *gin.Context) {\n\tresponseCode := constant.INVALID_PARAMS\n\tauthID, authErr := strconv.Atoi(context.Query(\"auth_id\"))\n\toffset := context.GetInt(\"offset\")\n\tif authErr != nil{\n\t\t//log.Println(authErr)\n\t\tutils.AppLogger.Info(authErr.Error(), zap.String(\"service\", \"GetBucketByAuthID()\"))\n\t\tcontext.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\"code\": responseCode,\n\t\t\t\"data\": make(map[string]string),\n\t\t\t\"msg\": constant.GetMessage(responseCode),\n\t\t})\n\t\treturn\n\t}\n\n\tvalidCheck := validation.Validation{}\n\tvalidCheck.Required(authID, \"auth_id\").Message(\"Must have auth id\")\n\tvalidCheck.Min(authID, 1, \"auth_id\").Message(\"Auth id should be positive\")\n\tvalidCheck.Min(offset, 0, \"page_offset\").Message(\"Page offset must be >= 0\")\n\n\tdata := make(map[string]interface{})\n\tif !validCheck.HasErrors() {\n\t\tif buckets, err := models.GetBucketByAuthID(uint(authID), offset); err != nil {\n\t\t\tresponseCode = constant.INTERNAL_SERVER_ERROR\n\t\t} else {\n\t\t\tresponseCode = constant.BUCKET_GET_SUCCESS\n\t\t\tdata[\"buckets\"] = buckets\n\t\t}\n\t} else {\n\t\tfor _, err := range validCheck.Errors {\n\t\t\t//log.Println(err.Message)\n\t\t\tutils.AppLogger.Info(err.Message, zap.String(\"service\", \"GetBucketByAuthID()\"))\n\t\t}\n\t}\n\n\tcontext.JSON(http.StatusOK, gin.H{\n\t\t\"code\": responseCode,\n\t\t\"data\": data,\n\t\t\"msg\": constant.GetMessage(responseCode),\n\t})\n}", "func (c *MemcachedManager) Get(id string) (ami.AMI, error) {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\titem, err := c.client.Get(id)\n\tif err != nil && err == memcache.ErrCacheMiss {\n\t\treturn ami.AMI{}, nil\n\t}\n\tif err != nil {\n\t\treturn ami.AMI{}, err\n\t}\n\n\tvar ami ami.AMI\n\n\tif err = c.unmarshal(item.Value, &ami); err != nil {\n\t\treturn ami, err\n\t}\n\n\treturn ami, nil\n}", "func (d DB) Get(id string) (*job.Job, error) {\n\ttemplate := `select to_jsonb(j.job) from (select * from %[1]s where job ->> 'id' = $1) as j;`\n\tquery := fmt.Sprintf(template, TABLE_NAME)\n\tvar r sql.NullString\n\terr := d.conn.QueryRow(query, id).Scan(&r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &job.Job{}\n\tif r.Valid {\n\t\terr = json.Unmarshal([]byte(r.String), &result)\n\t}\n\treturn result, err\n}", "func (c *JobClient) Get(ctx context.Context, id int) (*Job, error) {\n\treturn c.Query().Where(job.ID(id)).Only(ctx)\n}", "func (k *OpenshiftMappingService) GetById(_ context.Context, id string, result *domain.Mapping) error {\n\tconst op = \"OpenshiftMappingService.GetById\"\n\tkey := strings.ToLower(id)\n\tlog.Tracef(\"%s: %s\", op, key)\n\n\tk.mutex.RLock()\n\tvalue, ok := k.hosts[key]\n\tk.mutex.RUnlock()\n\n\tif !ok {\n\t\treturn domain.E(op, domain.ErrNotFound)\n\t}\n\t*result = value\n\treturn nil\n}" ]
[ "0.6895958", "0.58019644", "0.56753916", "0.56753916", "0.5634601", "0.54739267", "0.54434943", "0.54106134", "0.53281975", "0.5274735", "0.52611226", "0.5155134", "0.5115679", "0.5115659", "0.51154965", "0.51111996", "0.5055611", "0.5032297", "0.5030163", "0.50126463", "0.49747694", "0.49712875", "0.496781", "0.496406", "0.49550045", "0.49458662", "0.4896603", "0.4896603", "0.48708743", "0.4859749", "0.485611", "0.48511747", "0.48379952", "0.48346275", "0.48305914", "0.48261565", "0.4800461", "0.48001215", "0.47905195", "0.47825357", "0.47809228", "0.47769922", "0.4768831", "0.47644287", "0.4763612", "0.4760918", "0.47458524", "0.4727885", "0.47259036", "0.47245896", "0.47097602", "0.47026604", "0.46989647", "0.46986988", "0.4697372", "0.4693552", "0.4684978", "0.467101", "0.46521056", "0.46509105", "0.464581", "0.4643535", "0.46201637", "0.46099693", "0.45920628", "0.45900485", "0.4587385", "0.45807666", "0.45782694", "0.45754045", "0.4573267", "0.45693624", "0.45514947", "0.4530278", "0.45274767", "0.4522146", "0.45192912", "0.45192543", "0.45113686", "0.45062816", "0.45025167", "0.44965166", "0.44959936", "0.44956943", "0.4494822", "0.4494714", "0.44898623", "0.4475825", "0.44756207", "0.4475143", "0.44724306", "0.44588792", "0.44569498", "0.4453919", "0.44505146", "0.4449291", "0.44474417", "0.44381395", "0.44340137", "0.44305542" ]
0.7611321
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) GetAmazonConnectionByIdExecute(r ApiGetAmazonConnectionByIdRequest) (AmazonConnection, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue AmazonConnection ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.GetAmazonConnectionById") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 404 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.7777472", "0.7582237", "0.741292", "0.7358592", "0.7292706", "0.72179556", "0.72150666", "0.7154164", "0.7144244", "0.70236844", "0.6968861", "0.69574517", "0.6857601", "0.68203115", "0.6786843", "0.67499226", "0.6732799", "0.6726702", "0.664588", "0.66373837", "0.66341907", "0.66192603", "0.6618354", "0.65951604", "0.6592189", "0.6544029", "0.65052474", "0.6500035", "0.6499713", "0.6493198", "0.6459492", "0.64537424", "0.64339274", "0.64231", "0.6411837", "0.6354237", "0.6342012", "0.6331562", "0.63293886", "0.63235724", "0.63210624", "0.63129383", "0.63012326", "0.62950426", "0.62711006", "0.6269801", "0.62694305", "0.62559414", "0.62376016", "0.61896044", "0.61866677", "0.6157971", "0.61576515", "0.6157038", "0.61556566", "0.6138981", "0.61365765", "0.61309266", "0.61302364", "0.61298376", "0.6119938", "0.61105776", "0.6102657", "0.6093387", "0.609142", "0.6079346", "0.6078881", "0.6075695", "0.6045966", "0.6045463", "0.60427797", "0.6032737", "0.603158", "0.6027389", "0.60167104", "0.60026646", "0.5987349", "0.5974702", "0.5971437", "0.59703684", "0.5965762", "0.59478134", "0.5939073", "0.59338975", "0.59321105", "0.5925759", "0.5913415", "0.59012485", "0.58960927", "0.5890233", "0.5883923", "0.58764994", "0.5875759", "0.58713603", "0.58534265", "0.5852063", "0.5849181", "0.58465594", "0.5846279", "0.58363706", "0.58326805" ]
0.0
-1
/ ValidateS3Endpoint Method for ValidateS3Endpoint
func (a *AmazonConnectionsApiService) ValidateS3Endpoint(ctx _context.Context, amazonConnectionId string) ApiValidateS3EndpointRequest { return ApiValidateS3EndpointRequest{ ApiService: a, ctx: ctx, amazonConnectionId: amazonConnectionId, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *AmazonConnectionsApiService) ValidateS3EndpointExecute(r ApiValidateS3EndpointRequest) (CloudSubnetS3EndpointValidationResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue CloudSubnetS3EndpointValidationResult\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"AmazonConnectionsApiService.ValidateS3Endpoint\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/amazonConnections/{amazonConnectionId}/validateS3endpoint\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"amazonConnectionId\"+\"}\", _neturl.PathEscape(parameterToString(r.amazonConnectionId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.subnetId == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"subnetId is required and must be specified\")\n\t}\n\tif r.xApiVersion == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"xApiVersion is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"subnetId\", parameterToString(*r.subnetId, \"\"))\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tlocalVarHeaderParams[\"x-api-version\"] = parameterToString(*r.xApiVersion, \"\")\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Bearer\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func validateEndpointRequestResource(req *request.Request, resource arn.Resource) error {\n\tresReq := s3shared.ResourceRequest{Request: req, Resource: resource}\n\n\tif len(resReq.Request.ClientInfo.PartitionID) != 0 && resReq.IsCrossPartition() {\n\t\treturn s3shared.NewClientPartitionMismatchError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\tif !resReq.AllowCrossRegion() && resReq.IsCrossRegion() {\n\t\treturn s3shared.NewClientRegionMismatchError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\t// Accelerate not supported\n\tif aws.BoolValue(req.Config.S3UseAccelerate) {\n\t\treturn s3shared.NewClientConfiguredForAccelerateError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\treturn nil\n}", "func validateNsStoreS3Compatible(nsStore *nbv1.NamespaceStore) error {\n\ts3Compatible := nsStore.Spec.S3Compatible\n\n\tif s3Compatible == nil {\n\t\treturn nil\n\t}\n\n\terr := validateSignatureVersion(s3Compatible.SignatureVersion, nsStore.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validateEndPoint(&s3Compatible.Endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ep *Endpoint_DEPRECATED) IsS3() bool {\n\treturn ep.AWSAccessKeyID != \"\"\n}", "func s3BucketNameValidation(val interface{}) error {\n\tconst minS3Length = 3\n\tconst maxS3Length = 63\n\ts, ok := val.(string)\n\tif !ok {\n\t\treturn errValueNotAString\n\t}\n\tif len(s) < minS3Length || len(s) > maxS3Length {\n\t\treturn errS3ValueBadSize\n\t}\n\n\t// check for correct character set\n\tnameMatch := s3RegExp.FindStringSubmatch(s)\n\tif len(nameMatch) == 0 {\n\t\treturn errValueBadFormatWithPeriod\n\t}\n\n\t// Check for bad punctuation (no consecutive dashes or dots)\n\tformatMatch := punctuationRegExp.FindStringSubmatch(s)\n\tif len(formatMatch) != 0 {\n\t\treturn errS3ValueBadFormat\n\t}\n\n\tdashMatch := trailingPunctRegExp.FindStringSubmatch(s)\n\tif len(dashMatch) != 0 {\n\t\treturn errS3ValueTrailingDash\n\t}\n\n\tipMatch := ipAddressRegexp.FindStringSubmatch(s)\n\tif len(ipMatch) != 0 {\n\t\treturn errS3ValueBadFormat\n\t}\n\n\treturn nil\n}", "func (service *S3Service) Endpoint() string {\n return service.endpoint;\n}", "func (ep *Endpoint_DEPRECATED) Validate() error {\n\tif ep.IsSFTP() {\n\t\tif ep.SFTPPort == \"\" {\n\t\t\treturn errors.New(\"must specify sftp port\")\n\t\t} else if ep.SFTPUsername == \"\" {\n\t\t\treturn errors.New(\"must specify sftp username\")\n\t\t} else if ep.SFTPPassword == \"\" {\n\t\t\treturn errors.New(\"must specify sftp password\")\n\t\t} else if ep.SFTPDirectory == \"\" {\n\t\t\treturn errors.New(\"must specify sftp directory\")\n\t\t}\n\t} else if ep.IsS3() {\n\t\tif ep.AWSSecretAccessKey == \"\" {\n\t\t\treturn errors.New(\"must specify aws secret access key\")\n\t\t} else if ep.S3Bucket == \"\" {\n\t\t\treturn errors.New(\"must specify s3 bucket\")\n\t\t} else if ep.S3SSEAlgorithm != \"\" && !contains(validSSEAlgorithms, ep.S3SSEAlgorithm) {\n\t\t\treturn fmt.Errorf(\"no such SSE algorithm: %s\", ep.S3SSEAlgorithm)\n\t\t}\n\t\t//TODO: something about global canned acl and region?\n\t} else {\n\t\treturn errors.New(\"can't tell what sort of Endpoint this is\")\n\t}\n\n\t// Fall through on success.\n\treturn nil\n}", "func ParseAmazonS3URL(log log.T, s3URL *url.URL) (output AmazonS3URL) {\n\toutput = AmazonS3URL{\n\t\tIsValidS3URI: false,\n\t\tIsPathStyle: false,\n\t\tBucket: \"\",\n\t\tKey: \"\",\n\t\tRegion: \"\",\n\t}\n\n\toutput, err := parseBucketAndRegionFromHost(s3URL.Host, vpceUrlRegex, vpceUrlPatternBucketIdx, vpceUrlPatternRegionIdx)\n\tif err != nil {\n\t\toutput, err = parseBucketAndRegionFromHost(s3URL.Host, nonVpceUrlRegex, nonVpceUrlPatternBucketIdx, nonVpceUrlPatternRegionIdx)\n\t\tif err != nil {\n\t\t\toutput.IsValidS3URI = false\n\t\t\treturn\n\t\t}\n\t}\n\n\toutput.IsPathStyle = output.Bucket == \"\"\n\n\tpath := s3URL.Path\n\n\tif output.IsPathStyle {\n\t\t// no bucket name in the authority, parse it from the path\n\t\toutput.IsPathStyle = true\n\n\t\t// grab the encoded path so we don't run afoul of '/'s in the bucket name\n\t\tif path == \"/\" || path == \"\" {\n\t\t} else {\n\t\t\tpath = path[1:]\n\t\t\tindex := strings.Index(path, \"/\")\n\t\t\tif index == -1 {\n\t\t\t\t// https://s3.amazonaws.com/bucket\n\t\t\t\toutput.Bucket = path\n\t\t\t\toutput.Key = \"\"\n\t\t\t} else if index == (len(path) - 1) {\n\t\t\t\t// https://s3.amazonaws.com/bucket/\n\t\t\t\toutput.Bucket = strings.TrimRight(path, \"/\")\n\t\t\t\toutput.Key = \"\"\n\t\t\t} else {\n\t\t\t\t// https://s3.amazonaws.com/bucket/key\n\t\t\t\toutput.Bucket = path[:index]\n\t\t\t\toutput.Key = path[index+1:]\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// bucket name in the host, path is the object key\n\t\tif path == \"/\" || path == \"\" {\n\t\t\toutput.Key = \"\"\n\t\t} else {\n\t\t\toutput.Key = path[1:]\n\t\t}\n\t}\n\n\tif strings.EqualFold(output.Region, \"external-1\") {\n\t\toutput.Region = \"us-east-1\"\n\t} else if output.Region == \"\" {\n\t\t// s3 bucket URL in us-east-1 doesn't include region\n\t\toutput.Region = \"us-east-1\"\n\t}\n\n\treturn\n}", "func validate_s3(s3Client *s3.S3, bucket string, prefix string, inputMap map[string]bool) (int, map[string]bool) {\n\tvar continuationToken *string\n\tvar input *s3.ListObjectsV2Input\n\ts3RecordCounter := 0\n\ts3ObjectCounter := 0\n\n\t// Returns all the objects from a S3 bucket with the given prefix.\n\t// This approach utilizes NextContinuationToken to pull all the objects from the S3 bucket.\n\tfor {\n\t\tinput = &s3.ListObjectsV2Input{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tContinuationToken: continuationToken,\n\t\t\tPrefix: aws.String(prefix),\n\t\t}\n\n\t\tresponse, err := s3Client.ListObjectsV2(input)\n\t\tif err != nil {\n\t\t\texitErrorf(\"[TEST FAILURE] Error occured to get the objects from bucket: %q., %v\", bucket, err)\n\t\t}\n\n\t\tfor _, content := range response.Contents {\n\t\t\tinput := &s3.GetObjectInput{\n\t\t\t\tBucket: aws.String(bucket),\n\t\t\t\tKey: content.Key,\n\t\t\t}\n\t\t\tobj := getS3Object(s3Client, input)\n\t\t\ts3ObjectCounter++\n\n\t\t\tdataByte, err := ioutil.ReadAll(obj.Body)\n\t\t\tif err != nil {\n\t\t\t\texitErrorf(\"[TEST FAILURE] Error to parse GetObject response. %v\", err)\n\t\t\t}\n\n\t\t\tdata := strings.Split(string(dataByte), \"\\n\")\n\n\t\t\tfor _, d := range data {\n\t\t\t\tif d == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar message Message\n\n\t\t\t\tdecodeError := json.Unmarshal([]byte(d), &message)\n\t\t\t\tif decodeError != nil {\n\t\t\t\t\tfmt.Println(\"[TEST ERROR] Malform log entry. Unmarshal Error:\", decodeError)\n\t\t\t\t\tfmt.Println(\" Malform entry: %s\", d)\n\t\t\t\t\t// Skip malform log entries (count them as lost logs)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// First 8 char is the unique record ID\n\t\t\t\trecordId := message.Log[:8]\n\t\t\t\ts3RecordCounter += 1\n\t\t\t\tif _, ok := inputMap[recordId]; ok {\n\t\t\t\t\t// Setting true to indicate that this record was found in the destination\n\t\t\t\t\tinputMap[recordId] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !aws.BoolValue(response.IsTruncated) {\n\t\t\tbreak\n\t\t}\n\t\tcontinuationToken = response.NextContinuationToken\n\t}\n\n\tfmt.Println(\"total_s3_obj, \", s3ObjectCounter)\n\n\treturn s3RecordCounter, inputMap\n}", "func (s3pc *S3PutCommand) validateParams() error {\n\tif s3pc.AwsKey == \"\" {\n\t\treturn errors.New(\"aws_key cannot be blank\")\n\t}\n\tif s3pc.AwsSecret == \"\" {\n\t\treturn errors.New(\"aws_secret cannot be blank\")\n\t}\n\tif s3pc.LocalFile == \"\" && len(s3pc.LocalFilesIncludeFilter) == 0 {\n\t\treturn errors.New(\"local_file and local_files_include_filter cannot both be blank\")\n\t}\n\tif s3pc.LocalFile != \"\" && len(s3pc.LocalFilesIncludeFilter) != 0 {\n\t\treturn errors.New(\"local_file and local_files_include_filter cannot both be specified\")\n\t}\n\tif s3pc.Optional && len(s3pc.LocalFilesIncludeFilter) != 0 {\n\t\treturn errors.New(\"cannot use optional upload with local_files_include_filter\")\n\t}\n\tif s3pc.RemoteFile == \"\" {\n\t\treturn errors.New(\"remote_file cannot be blank\")\n\t}\n\tif s3pc.ContentType == \"\" {\n\t\treturn errors.New(\"content_type cannot be blank\")\n\t}\n\tif !util.SliceContains(artifact.ValidVisibilities, s3pc.Visibility) {\n\t\treturn errors.Errorf(\"invalid visibility setting: %v\", s3pc.Visibility)\n\t}\n\n\t// make sure the bucket is valid\n\tif err := validateS3BucketName(s3pc.Bucket); err != nil {\n\t\treturn errors.Wrapf(err, \"%v is an invalid bucket name\", s3pc.Bucket)\n\t}\n\n\t// make sure the s3 permissions are valid\n\tif !validS3Permissions(s3pc.Permissions) {\n\t\treturn errors.Errorf(\"permissions '%v' are not valid\", s3pc.Permissions)\n\t}\n\n\treturn nil\n}", "func (s3ce *S3ConfigExecutor) Validate(config *gateways.ConfigContext) error {\n\tartifact, err := parseConfig(config.Data.Config)\n\tif err != nil {\n\t\treturn gateways.ErrConfigParseFailed\n\t}\n\tif artifact == nil {\n\t\treturn gateways.ErrEmptyConfig\n\t}\n\tif artifact.S3EventConfig == nil {\n\t\treturn fmt.Errorf(\"%+v, s3 bucket configuration can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.AccessKey == nil {\n\t\treturn fmt.Errorf(\"%+v, access key can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.SecretKey == nil {\n\t\treturn fmt.Errorf(\"%+v, secret key can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Endpoint == \"\" {\n\t\treturn fmt.Errorf(\"%+v, endpoint url can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Bucket == \"\" {\n\t\treturn fmt.Errorf(\"%+v, bucket name can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Event != \"\" && minio.NotificationEventType(artifact.S3EventConfig.Event) == \"\" {\n\t\treturn fmt.Errorf(\"%+v, unknown event %s\", gateways.ErrInvalidConfig, artifact.S3EventConfig.Event)\n\t}\n\treturn nil\n}", "func validateOutpostEndpoint(req *request.Request, resource arn.Resource) error {\n\tif err := validateEndpointRequestResource(req, resource); err != nil {\n\t\treturn err\n\t}\n\n\t// DualStack not supported\n\tif isUseDualStackEndpoint(req) {\n\t\treturn s3shared.NewClientConfiguredForDualStackError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\treturn nil\n}", "func TestS3BucketDoesNotExist(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\n\tq := make(url.Values)\n\texpect := map[string]string{\n\t\t\"AWS_S3_ENDPOINT\": cloudimpl.AWSEndpointParam,\n\t\t\"AWS_S3_ENDPOINT_KEY\": cloudimpl.AWSAccessKeyParam,\n\t\t\"AWS_S3_ENDPOINT_REGION\": cloudimpl.S3RegionParam,\n\t\t\"AWS_S3_ENDPOINT_SECRET\": cloudimpl.AWSSecretParam,\n\t}\n\tfor env, param := range expect {\n\t\tv := os.Getenv(env)\n\t\tif v == \"\" {\n\t\t\tskip.IgnoreLintf(t, \"%s env var must be set\", env)\n\t\t}\n\t\tq.Add(param, v)\n\t}\n\n\tbucket := \"invalid-bucket\"\n\tu := url.URL{\n\t\tScheme: \"s3\",\n\t\tHost: bucket,\n\t\tPath: \"backup-test\",\n\t\tRawQuery: q.Encode(),\n\t}\n\n\tctx := context.Background()\n\tuser := security.RootUserName()\n\n\tconf, err := cloudimpl.ExternalStorageConfFromURI(u.String(), user)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Setup a sink for the given args.\n\tclientFactory := blobs.TestBlobServiceClient(testSettings.ExternalIODir)\n\ts, err := cloudimpl.MakeExternalStorage(ctx, conf, base.ExternalIODirConfig{}, testSettings,\n\t\tclientFactory, nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer s.Close()\n\n\tif readConf := s.Conf(); readConf != conf {\n\t\tt.Fatalf(\"conf does not roundtrip: started with %+v, got back %+v\", conf, readConf)\n\t}\n\n\t_, err = s.ReadFile(ctx, \"\")\n\trequire.Error(t, err, \"\")\n\trequire.True(t, errors.Is(err, cloudimpl.ErrFileDoesNotExist))\n}", "func (m *endpoint) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateConnectionString(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func isValidLocationConstraint(r *http.Request) (s3Error APIErrorCode) {\n\tserverRegion := serverConfig.GetRegion()\n\t// If the request has no body with content-length set to 0,\n\t// we do not have to validate location constraint. Bucket will\n\t// be created at default region.\n\tif r.ContentLength == 0 {\n\t\treturn ErrNone\n\t}\n\tlocationConstraint := createBucketLocationConfiguration{}\n\tif err := xmlDecoder(r.Body, &locationConstraint, r.ContentLength); err != nil {\n\t\tif err == io.EOF && r.ContentLength == -1 {\n\t\t\t// EOF is a valid condition here when ContentLength is -1.\n\t\t\treturn ErrNone\n\t\t}\n\t\terrorIf(err, \"Unable to xml decode location constraint\")\n\t\t// Treat all other failures as XML parsing errors.\n\t\treturn ErrMalformedXML\n\t} // Successfully decoded, proceed to verify the region.\n\n\t// Once region has been obtained we proceed to verify it.\n\tincomingRegion := locationConstraint.Location\n\tif incomingRegion == \"\" {\n\t\t// Location constraint is empty for region \"us-east-1\",\n\t\t// in accordance with protocol.\n\t\tincomingRegion = \"us-east-1\"\n\t}\n\t// Return errInvalidRegion if location constraint does not match\n\t// with configured region.\n\ts3Error = ErrNone\n\tif serverRegion != incomingRegion {\n\t\ts3Error = ErrInvalidRegion\n\t}\n\treturn s3Error\n}", "func S3UrlFormatter(awsSession *session.Session, s3Bucket, s3KeyPrefix string, enableCloudFront bool) (func(string) string, error) {\n\tif awsSession == nil {\n\t\treturn nil, errors.New(\"aws session cannot be nil\")\n\t}\n\n\tif s3Bucket == \"\" {\n\t\treturn nil, errors.New(\"aws s3 bucket cannot be empty\")\n\t}\n\n\tvar (\n\t\tbaseS3Url string\n\t\tbaseS3Origin string\n\t)\n\tif enableCloudFront {\n\t\tdist, err := CloudFrontDistribution(awsSession, s3Bucket)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Format the domain as an HTTPS url, \"dzuyel7n94hma.cloudfront.net\"\n\t\tbaseS3Url = fmt.Sprintf(\"https://%s/\", *dist.DomainName)\n\n\t\t// The origin used for the cloudfront needs to be striped from the path\n\t\t// provided, the URL shouldn't have one, but \"/public\"\n\t\tbaseS3Origin = *dist.Origins.Items[0].OriginPath\n\t} else {\n\t\t// The static files are upload to a specific prefix, so need to ensure\n\t\t// the path reference includes this prefix\n\t\ts3Path := filepath.Join(s3Bucket, s3KeyPrefix)\n\n\t\tif *awsSession.Config.Region == \"us-east-1\" {\n\t\t\t// US East (N.Virginia) region endpoint, http://s3.amazonaws.com/bucket or\n\t\t\t// http://s3-external-1.amazonaws.com/bucket/\n\t\t\tbaseS3Url = fmt.Sprintf(\"https://s3.amazonaws.com/%s/\", s3Path)\n\t\t} else {\n\t\t\t// Region-specific endpoint, http://s3-aws-region.amazonaws.com/bucket\n\t\t\tbaseS3Url = fmt.Sprintf(\"https://s3-%s.amazonaws.com/%s/\", *awsSession.Config.Region, s3Path)\n\t\t}\n\n\t\tbaseS3Origin = s3KeyPrefix\n\t}\n\n\tf := func(p string) string {\n\t\treturn S3Url(baseS3Url, baseS3Origin, p)\n\t}\n\n\treturn f, nil\n}", "func IsVirtualHostableS3Bucket(input string, allowSubDomains bool) bool {\n\t// input should not be formatted as an IP address\n\t// NOTE: this will technically trip up on IPv6 hosts with zone IDs, but\n\t// validation further down will catch that anyway (it's guaranteed to have\n\t// unfriendly characters % and : if that's the case)\n\tif net.ParseIP(input) != nil {\n\t\treturn false\n\t}\n\n\tvar labels []string\n\tif allowSubDomains {\n\t\tlabels = strings.Split(input, \".\")\n\t} else {\n\t\tlabels = []string{input}\n\t}\n\n\tfor _, label := range labels {\n\t\t// validate special length constraints\n\t\tif l := len(label); l < 3 || l > 63 {\n\t\t\treturn false\n\t\t}\n\n\t\t// Validate no capital letters\n\t\tfor _, r := range label {\n\t\t\tif r >= 'A' && r <= 'Z' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\t// Validate valid host label\n\t\tif !smithyhttp.ValidHostLabel(label) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func S3Url(baseS3Url, baseS3Origin, p string) string {\n\t// If its already a URL, then don't format it\n\tif strings.HasPrefix(p, \"http\") {\n\t\treturn p\n\t}\n\n\t// Drop the beginning forward slash\n\tp = strings.TrimLeft(p, \"/\")\n\n\t// In the case of cloudfront, the base URL may not match S3,\n\t// removing the origin from the path provided\n\t// ie. The s3 bucket + path of\n\t//\t\tgitw-corp-web.s3.amazonaws.com/public\n\t// \t\tmaps to dzuyel7n94hma.cloudfront.net\n\t// where the path prefix of '/public' needs to be dropped.\n\torg := strings.Trim(baseS3Origin, \"/\")\n\tif org != \"\" {\n\t\tp = strings.Replace(p, org+\"/\", \"\", 1)\n\t}\n\n\t// Parse out the querystring from the path\n\tvar pathQueryStr string\n\tif strings.Contains(p, \"?\") {\n\t\tpts := strings.Split(p, \"?\")\n\t\tp = pts[0]\n\t\tif len(pts) > 1 {\n\t\t\tpathQueryStr = pts[1]\n\t\t}\n\t}\n\n\tu, err := url.Parse(baseS3Url)\n\tif err != nil {\n\t\treturn \"?\"\n\t}\n\tldir := filepath.Base(u.Path)\n\n\tif strings.HasPrefix(p, ldir) {\n\t\tp = strings.Replace(p, ldir+\"/\", \"\", 1)\n\t}\n\n\tu.Path = filepath.Join(u.Path, p)\n\tu.RawQuery = pathQueryStr\n\n\treturn u.String()\n}", "func validateEndpoint(endpoint string) ([]string, error) {\n\tendpointSet := make(map[string]struct{})\n\tendpoints := make([]string, 0)\n\tfor _, endpoint := range strings.Split(endpoint, \",\") {\n\t\ttrimEndpoint := strings.Trim(endpoint, \" \")\n\t\tif _, err := url.ParseRequestURI(trimEndpoint); err != nil {\n\t\t\treturn nil, errors.New(\"URL \\\"\" + trimEndpoint + \"\\\" is not a valid endpoint\")\n\t\t}\n\t\t// check if map contains this key to identify duplicate URLs\n\t\tif _, hasKey := endpointSet[trimEndpoint]; hasKey {\n\t\t\treturn nil, errors.New(\"URL \\\"\" + trimEndpoint + \"\\\" is a duplicate endpoint\")\n\t\t}\n\t\tendpointSet[trimEndpoint] = struct{}{}\n\t\tendpoints = append(endpoints, trimEndpoint)\n\t}\n\treturn endpoints, nil\n}", "func validateSignatureVersion(signature nbv1.S3SignatureVersion, nsStoreName string) error {\n\tif signature != \"\" &&\n\t\tsignature != nbv1.S3SignatureVersionV2 &&\n\t\tsignature != nbv1.S3SignatureVersionV4 {\n\t\treturn util.NewPersistentError(\"InvalidSignatureVersion\",\n\t\t\tfmt.Sprintf(\"Invalid s3 signature version %q for namespace store %q\",\n\t\t\t\tsignature, nsStoreName))\n\t}\n\treturn nil\n}", "func (m *S3PresignedPost) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFields(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *S3PresignedPostFields) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBucket(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func parseS3URI(uri string) (bucket, key string, err error) {\n\tparsed := strings.SplitN(strings.TrimPrefix(uri, s3URIPrefix), \"/\", 2)\n\tbucket = parsed[0]\n\tif bucket == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"cannot parse S3 URI %s into bucket name and key\", uri)\n\t}\n\tif len(parsed) == 2 {\n\t\tkey = parsed[1]\n\t}\n\treturn\n}", "func getS3(r *http.Request) (S3, error) {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return S3{}, err\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: \"\",\n }\n return s3, nil\n}", "func (bc *BucketConfig) fixEndpoint() {\n\tif u, err := url.Parse(bc.Endpoint); err == nil {\n\t\tbc.Endpoint = u.Host\n\t\tif strings.ToLower(u.Scheme) == \"https\" {\n\t\t\tbc.Secure = true\n\t\t}\n\t}\n}", "func S3URL(path string) string {\n\tregion, bucket, key := s3parse(path)\n\n\tif region == \"\" {\n\t\tregion = s3region // fallback to default region\n\t}\n\tif region == \"\" {\n\t\ts3log(\"S3URL: could not find region: [%s]\", path)\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"https://s3-%s.amazonaws.com/%s/%s\", region, bucket, key)\n}", "func checkHaveSsse3() bool", "func validateAdapterEndpoint(endpoint string, adapterName string, errs []error) []error {\n\tif endpoint == \"\" {\n\t\treturn append(errs, fmt.Errorf(\"There's no default endpoint available for %s. Calls to this bidder/exchange will fail. \"+\n\t\t\t\"Please set adapters.%s.endpoint in your app config\", adapterName, adapterName))\n\t}\n\n\t// Create endpoint template\n\tendpointTemplate, err := template.New(\"endpointTemplate\").Parse(endpoint)\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Invalid endpoint template: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Resolve macros (if any) in the endpoint URL\n\tresolvedEndpoint, err := macros.ResolveMacros(*endpointTemplate, macros.EndpointTemplateParams{\n\t\tHost: dummyHost,\n\t\tPublisherID: dummyPublisherID,\n\t\tAccountID: dummyAccountID,\n\t})\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"Unable to resolve endpoint: %s for adapter: %s. %v\", endpoint, adapterName, err))\n\t}\n\t// Validate the resolved endpoint\n\t//\n\t// Validating using both IsURL and IsRequestURL because IsURL allows relative paths\n\t// whereas IsRequestURL requires absolute path but fails to check other valid URL\n\t// format constraints.\n\t//\n\t// For example: IsURL will allow \"abcd.com\" but IsRequestURL won't\n\t// IsRequestURL will allow \"http://http://abcd.com\" but IsURL won't\n\tif !validator.IsURL(resolvedEndpoint) || !validator.IsRequestURL(resolvedEndpoint) {\n\t\terrs = append(errs, fmt.Errorf(\"The endpoint: %s for %s is not a valid URL\", resolvedEndpoint, adapterName))\n\t}\n\treturn errs\n}", "func (output AmazonS3URL) IsBucketAndKeyPresent() bool {\n\treturn output.IsValidS3URI && output.Bucket != \"\" && output.Key != \"\" && output.Region != \"\"\n}", "func TestS3(t *testing.T) {\n\tif *s3url == \"\" {\n\t\tt.Skip(\"Skipping s3 integration test, test_s3_url flag empty.\")\n\t\treturn\n\t}\n\n\tif !strings.HasPrefix(*s3url, \"s3://\") {\n\t\tt.Errorf(\"test_s3_url requires 's3://' prefix\")\n\t\treturn\n\t}\n\n\tctx := context.Background()\n\n\tb, err := rblob.OpenBucket(ctx, \"\", *s3url)\n\trequire.NoError(t, err)\n\n\tsc, err := b.Stream(ctx, *s3after)\n\trequire.NoError(t, err)\n\n\tfor {\n\t\te, err := sc.Recv()\n\t\trequire.NoError(t, err)\n\n\t\tfmt.Println(e.ID)\n\t\tfmt.Printf(\"%s\\n\\n\", e.MetaData)\n\t}\n}", "func setupS3(ctx context.Context, s3 *s3Config, forETL bool) (res fileservice.FileService, readPath string, err error) {\n\treturn setupFileservice(ctx, &pathConfig{\n\t\tisS3: true,\n\t\tforETL: forETL,\n\t\ts3Config: *s3,\n\t})\n}", "func ConfigureS3Bucket(_ context.Context, cm resource.Claim, cs resource.Class, mg resource.Managed) error {\n\tbucketClaim, cmok := cm.(*storagev1alpha1.Bucket)\n\tif !cmok {\n\t\treturn errors.Errorf(\"expected resource claim %s to be %s\", cm.GetName(), storagev1alpha1.BucketGroupVersionKind)\n\t}\n\n\ts3BucketClass, csok := cs.(*cloudscaleStoragev1alpha1.S3BucketClass)\n\tif !csok {\n\t\treturn errors.Errorf(\"expected resource class %s to be %s\", cs.GetName(), cloudscaleStoragev1alpha1.S3BucketClassGroupVersionKind)\n\t}\n\n\ts3Bucket, mgok := mg.(*cloudscaleStoragev1alpha1.S3Bucket)\n\tif !mgok {\n\t\treturn errors.Errorf(\"expected managed resource %s to be %s\", mg.GetName(), cloudscaleStoragev1alpha1.S3BucketGroupVersionKind)\n\t}\n\n\tspec := &cloudscaleStoragev1alpha1.S3BucketSpec{\n\t\tResourceSpec: runtimev1alpha1.ResourceSpec{\n\t\t\tReclaimPolicy: runtimev1alpha1.ReclaimRetain,\n\t\t},\n\t\tForProvider: s3BucketClass.SpecTemplate.ForProvider,\n\t}\n\n\tif s3BucketClass.SpecTemplate.ReclaimPolicy != \"\" {\n\t\tspec.ResourceSpec.ReclaimPolicy = s3BucketClass.SpecTemplate.ReclaimPolicy\n\t}\n\n\tif bucketClaim.Spec.PredefinedACL != nil {\n\t\tspec.ForProvider.CannedACL = translateACL(bucketClaim.Spec.PredefinedACL)\n\t}\n\n\tspec.WriteConnectionSecretToReference = &runtimev1alpha1.SecretReference{\n\t\tNamespace: s3BucketClass.SpecTemplate.WriteConnectionSecretsToNamespace,\n\t\tName: string(cm.GetUID()),\n\t}\n\tspec.ProviderReference = s3BucketClass.SpecTemplate.ProviderReference\n\n\ts3Bucket.Spec = *spec\n\n\treturn nil\n}", "func s3Service(bucketName string) (*s3.S3, error) {\n\tsvc := s3.New(session.New(), &aws.Config{})\n\tif bucketName == \"\" {\n\t\treturn svc, nil\n\t}\n\n\t//If bucket has a LocationConstraint, use config to access through that region specifically\n\tresult, err := svc.GetBucketLocation(&s3.GetBucketLocationInput{Bucket: &bucketName})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.LocationConstraint != nil {\n\t\tsvc = s3.New(session.New(), &aws.Config{Region: result.LocationConstraint})\n\t}\n\n\treturn svc, nil\n}", "func parseHTTPURI(url string) (bucket, key string, err error) {\n\tparsedURL := strings.SplitN(strings.TrimPrefix(url, \"https://\"), \"/\", 2)\n\n\t// go through the host backwards and find the first piece that\n\t// starts with 's3' - the rest of the host (to the left of 's3')\n\t// is the bucket name. this is to support both URL host formats:\n\t// <bucket>.s3-<region>.amazonaws.com and <bucket>.s3.<region>.amazonaws.com\n\tsplit := strings.Split(parsedURL[0], \".\")\n\tbucketEndIdx := len(split) - 1\n\tfor ; bucketEndIdx > 0; bucketEndIdx-- {\n\t\tif strings.HasPrefix(split[bucketEndIdx], \"s3\") {\n\t\t\tbreak\n\t\t}\n\t}\n\tbucket = strings.Join(split[:bucketEndIdx], \".\")\n\tif bucket == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"cannot parse S3 URL %s into bucket name and key\", url)\n\t}\n\tif len(parsedURL) == 2 {\n\t\tkey = parsedURL[1]\n\t}\n\treturn\n}", "func TestEndpointCase3(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"ap-northeast-2\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.ap-northeast-2.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (p *Parser) validateEndpoint(endpoint string) (string, error) {\n\t// We need the endpoint to begin with a forward slash '/'\n\t// Note: Not sure if we want to add a leading slash if the slash is missing\n\tif len(endpoint) == 0 {\n\t\treturn DefaultEndpoint, nil\n\t}\n\n\tif string(endpoint[0]) != \"/\" {\n\t\treturn endpoint, fmt.Errorf(\"provided endpoint must begin witha '/'. Found: %v.\", endpoint[0])\n\t}\n\n\treturn endpoint, nil\n}", "func testPutBucketPolicyHandler(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,\n\tcredentials auth.Credentials, t *testing.T) {\n\n\tbucketName1 := fmt.Sprintf(\"%s-1\", bucketName)\n\tif err := obj.MakeBucketWithLocation(context.Background(), bucketName1, \"\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// template for constructing HTTP request body for PUT bucket policy.\n\tbucketPolicyTemplate := `{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::%s\"]},{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::%s/this*\"]}]}`\n\n\t// test cases with sample input and expected output.\n\ttestCases := []struct {\n\t\tbucketName string\n\t\t// bucket policy to be set,\n\t\t// set as request body.\n\t\tbucketPolicyReader io.ReadSeeker\n\t\t// length in bytes of the bucket policy being set.\n\t\tpolicyLen int\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected Response.\n\t\texpectedRespStatus int\n\t}{\n\t\t// Test case - 1.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNoContent,\n\t\t},\n\t\t// Test case - 2.\n\t\t// Setting the content length to be more than max allowed size.\n\t\t// Expecting StatusBadRequest (400).\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: maxAccessPolicySize + 1,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 3.\n\t\t// Case with content-length of the HTTP request set to 0.\n\t\t// Expecting the HTTP response status to be StatusLengthRequired (411).\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: 0,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusLengthRequired,\n\t\t},\n\t\t// Test case - 4.\n\t\t// setting the readSeeker to `nil`, bucket policy parser will fail.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: nil,\n\n\t\t\tpolicyLen: 10,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 5.\n\t\t// setting the keys to be empty.\n\t\t// Expecting statusForbidden.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: nil,\n\n\t\t\tpolicyLen: 10,\n\t\t\taccessKey: \"\",\n\t\t\tsecretKey: \"\",\n\t\t\texpectedRespStatus: http.StatusForbidden,\n\t\t},\n\t\t// Test case - 6.\n\t\t// setting an invalid bucket policy.\n\t\t// the bucket policy parser will fail.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(\"dummy-policy\")),\n\n\t\t\tpolicyLen: len([]byte(\"dummy-policy\")),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 7.\n\t\t// Different bucket name used in the HTTP request and the policy string.\n\t\t// checkBucketPolicyResources should fail.\n\t\t{\n\t\t\tbucketName: bucketName1,\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t\t// Test case - 8.\n\t\t// non-existent bucket is used.\n\t\t// writing BucketPolicy should fail.\n\t\t// should result is 500 InternalServerError.\n\t\t{\n\t\t\tbucketName: \"non-existent-bucket\",\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, \"non-existent-bucket\", \"non-existent-bucket\"))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNotFound,\n\t\t},\n\t\t// Test case - 9.\n\t\t// invalid bucket name is used.\n\t\t// writing BucketPolicy should fail.\n\t\t// should result is 400 StatusBadRequest.\n\t\t{\n\t\t\tbucketName: \".invalid-bucket\",\n\t\t\tbucketPolicyReader: bytes.NewReader([]byte(fmt.Sprintf(bucketPolicyTemplate, \".invalid-bucket\", \".invalid-bucket\"))),\n\n\t\t\tpolicyLen: len(fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)),\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t}\n\n\t// Iterating over the test cases, calling the function under test and asserting the response.\n\tfor i, testCase := range testCases {\n\t\t// obtain the put bucket policy request body.\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", testCase.bucketName),\n\t\t\tint64(testCase.policyLen), testCase.bucketPolicyReader, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\tif recV4.Code != testCase.expectedRespStatus {\n\t\t\tt.Errorf(\"Test %d: %s: Expected the response status to be `%d`, but instead found `%d`\", i+1, instanceType, testCase.expectedRespStatus, recV4.Code)\n\t\t}\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"PUT\", getPutPolicyURL(\"\", testCase.bucketName),\n\t\t\tint64(testCase.policyLen), testCase.bucketPolicyReader, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: %s: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, instanceType, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic ofthe handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\tif recV2.Code != testCase.expectedRespStatus {\n\t\t\tt.Errorf(\"Test %d: %s: Expected the response status to be `%d`, but instead found `%d`\", i+1, instanceType, testCase.expectedRespStatus, recV2.Code)\n\t\t}\n\t}\n\n\t// Test for Anonymous/unsigned http request.\n\t// Bucket policy related functions doesn't support anonymous requests, setting policies shouldn't make a difference.\n\tbucketPolicyStr := fmt.Sprintf(bucketPolicyTemplate, bucketName, bucketName)\n\t// create unsigned HTTP request for PutBucketPolicyHandler.\n\tanonReq, err := newTestRequest(\"PUT\", getPutPolicyURL(\"\", bucketName),\n\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)))\n\n\tif err != nil {\n\t\tt.Fatalf(\"Minio %s: Failed to create an anonymous request for bucket \\\"%s\\\": <ERROR> %v\",\n\t\t\tinstanceType, bucketName, err)\n\t}\n\n\t// ExecObjectLayerAPIAnonTest - Calls the HTTP API handler using the anonymous request, validates the ErrAccessDeniedResponse,\n\t// sets the bucket policy using the policy statement generated from `getWriteOnlyObjectStatement` so that the\n\t// unsigned request goes through and its validated again.\n\tExecObjectLayerAPIAnonTest(t, obj, \"PutBucketPolicyHandler\", bucketName, \"\", instanceType, apiRouter, anonReq, getWriteOnlyObjectStatement)\n\n\t// HTTP request for testing when `objectLayer` is set to `nil`.\n\t// There is no need to use an existing bucket and valid input for creating the request\n\t// since the `objectLayer==nil` check is performed before any other checks inside the handlers.\n\t// The only aim is to generate an HTTP request in a way that the relevant/registered end point is evoked/called.\n\tnilBucket := \"dummy-bucket\"\n\n\tnilReq, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", nilBucket),\n\t\t0, nil, \"\", \"\")\n\n\tif err != nil {\n\t\tt.Errorf(\"Minio %s: Failed to create HTTP request for testing the response when object Layer is set to `nil`.\", instanceType)\n\t}\n\t// execute the object layer set to `nil` test.\n\t// `ExecObjectLayerAPINilTest` manages the operation.\n\tExecObjectLayerAPINilTest(t, nilBucket, \"\", instanceType, apiRouter, nilReq)\n\n}", "func checkS3BucketPolicy(input PredictionInput) Forecast {\n\n\tforecast := makeForecast(input.typeName, input.logicalId)\n\n\tspin(input.typeName, input.logicalId, \"bucket policy\")\n\n\tif input.stackExists {\n\t\t_, err := cfn.GetStackResource(input.stackName, input.logicalId)\n\n\t\t// Do we need this?\n\n\t\tif err != nil {\n\t\t\t// Likely the resource has been added after the stack was created\n\t\t\tconfig.Debugf(\"Unable to get stack resource %v: %v\", input.logicalId, err)\n\t\t}\n\t}\n\n\t// Go back to the template to get the referenced bucket\n\n\t// Check the policy for invalid principals\n\t_, props := s11n.GetMapValue(input.resource, \"Properties\")\n\tif props != nil {\n\t\t_, policyDocument := s11n.GetMapValue(props, \"PolicyDocument\")\n\t\tif policyDocument != nil {\n\t\t\tres, err := iam.CheckPolicyDocument(policyDocument)\n\n\t\t\tif err != nil {\n\t\t\t\tforecast.Add(false, fmt.Sprintf(\"Unable to check policy document: %v\", err))\n\t\t\t}\n\n\t\t\tif !res {\n\t\t\t\tLineNumber = policyDocument.Line\n\t\t\t\tforecast.Add(false, \"Invalid principal in policy document\")\n\t\t\t} else {\n\t\t\t\tforecast.Add(true, \"Principal is valid\")\n\t\t\t}\n\t\t}\n\t}\n\n\tspinner.Pop()\n\n\treturn forecast\n}", "func (p *s3URLPartsExtension) searchObjectPrefixAndPatternFromS3URL() (prefix, pattern string, isWildcardSearch bool) {\n\t// If the objectKey is empty, it means the url provided is of a bucket,\n\t// then all object inside buckets needs to be included, so prefix is \"\" and pattern is set to *, isWildcardSearch false\n\tif p.ObjectKey == \"\" {\n\t\tpattern = \"*\"\n\t\treturn\n\t}\n\t// Check for wildcard\n\twildCardIndex := gCopyUtil.firstIndexOfWildCard(p.ObjectKey)\n\t// If no wildcard exits and url represents a virtual directory or a object, search everything in the virtual directory\n\t// or specifically the object.\n\tif wildCardIndex < 0 {\n\t\t// prefix is the path of virtual directory after the bucket, pattern is *, isWildcardSearch false\n\t\t// Example 1: https://<bucket-name>/vd-1/, prefix = /vd-1/\n\t\t// Example 2: https://<bucket-name>/vd-1/vd-2/, prefix = /vd-1/vd-2/\n\t\t// Example 3: https://<bucket-name>/vd-1/abc, prefix = /vd1/abc\n\t\tprefix = p.ObjectKey\n\t\tpattern = \"*\"\n\t\treturn\n\t}\n\n\t// Is wildcard search\n\tisWildcardSearch = true\n\t// wildcard exists prefix will be the content of object key till the wildcard index\n\t// Example: https://<bucket-name>/vd-1/vd-2/abc*\n\t// prefix = /vd-1/vd-2/abc, pattern = /vd-1/vd-2/abc*, isWildcardSearch true\n\tprefix = p.ObjectKey[:wildCardIndex]\n\tpattern = p.ObjectKey\n\n\treturn\n}", "func (e *Endpoint) Validate() error {\n\tif e.Type == \"\" {\n\t\treturn errors.New(\"endpoint type must be specified\")\n\t}\n\n\tif e.Transport == \"\" {\n\t\treturn errors.New(\"endpoint transport must be specified\")\n\t}\n\n\treturn nil\n}", "func (e EndpointResource) Validate() error {\n\treturn validator.New().Struct(e)\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var bucket NewBucket\n err = decoder.Decode(&bucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n\n // Add the necessary headers for Metadata Search and Access During Outage\n createBucketHeaders := map[string][]string{}\n createBucketHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n createBucketHeaders[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n createBucketHeaders[\"x-emc-metadata-search\"] = []string{\"ObjectName,x-amz-meta-image-width;Integer,x-amz-meta-image-height;Integer,x-amz-meta-gps-latitude;Decimal,x-amz-meta-gps-longitude;Decimal\"}\n\n createBucketResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/\", createBucketHeaders, \"\")\n\n // Enable CORS after the bucket creation to allow the web browser to send requests directly to ECS\n if createBucketResponse.Code == 200 {\n enableBucketCorsHeaders := map[string][]string{}\n enableBucketCorsHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n corsConfiguration := `\n <CORSConfiguration>\n <CORSRule>\n <AllowedOrigin>*</AllowedOrigin>\n <AllowedHeader>*</AllowedHeader>\n <ExposeHeader>x-amz-meta-image-width</ExposeHeader>\n <ExposeHeader>x-amz-meta-image-height</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-latitude</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-longitude</ExposeHeader>\n <AllowedMethod>HEAD</AllowedMethod>\n <AllowedMethod>GET</AllowedMethod>\n <AllowedMethod>PUT</AllowedMethod>\n <AllowedMethod>POST</AllowedMethod>\n <AllowedMethod>DELETE</AllowedMethod>\n </CORSRule>\n </CORSConfiguration>\n `\n enableBucketCorsResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/?cors\", enableBucketCorsHeaders, corsConfiguration)\n if enableBucketCorsResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, struct {\n CorsConfiguration string `json:\"cors_configuration\"`\n Bucket string `json:\"bucket\"`\n } {\n CorsConfiguration: corsConfiguration,\n Bucket: bucket.Name,\n })\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket created, but CORS can't be enabled\"}\n }\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket can't be created\"}\n }\n return nil\n}", "func main() {\n // Initialize a session in us-west-2 that the SDK will use to load\n // credentials from the shared credentials file ~/.aws/credentials.\n sess, err := session.NewSession(&aws.Config{\n Region: aws.String(\"us-east-1\")},\n )\n\n // Create S3 service client\n svc := s3.New(sess)\n\n req, _ := svc.GetObjectRequest(&s3.GetObjectInput{\n Bucket: aws.String(\"myBucket\"),\n Key: aws.String(\"myKey\"),\n })\n urlStr, err := req.Presign(15 * time.Minute)\n\n if err != nil {\n log.Println(\"Failed to sign request\", err)\n }\n\n log.Println(\"The URL is\", urlStr)\n}", "func (e Endpoint) Validate() error {\n\tswitch {\n\tcase e.PeerID == \"\":\n\t\treturn errors.New(\"endpoint has no peer ID\")\n\tcase e.Protocol == \"\":\n\t\treturn errors.New(\"endpoint has no protocol\")\n\tcase e.Port > 0 && len(e.IP) == 0:\n\t\treturn fmt.Errorf(\"endpoint has port %v but no IP\", e.Port)\n\tdefault:\n\t\treturn nil\n\t}\n}", "func fileSizeOnS3Svc(ctx *context, file string, svc *s3.S3) (int, error) {\n\tvar result int\n\tinput := &s3.HeadObjectInput{\n\t\tBucket: aws.String(ctx.bucket),\n\t\tKey: aws.String(file),\n\t}\n\toutput, err := svc.HeadObject(input)\n\tawsOutput(output.GoString())\n\tif err != nil {\n\t\treturn result, handle(\"Error in HeadObject request.\", err)\n\t}\n\tif output.ContentLength != nil {\n\t\tresult = int(*output.ContentLength)\n\t}\n\treturn result, err\n}", "func S3(access, secret, bucket, region, content, prefix string) (Storage, error) {\n\treturn s3.New(access, secret, bucket, region, content, prefix)\n}", "func Test_BucketPolicySample_1(t *testing.T) {\n\tsc := NewS3()\n\terr := sc.PutObject(TEST_BUCKET, TEST_KEY, TEST_VALUE)\n\tif err != nil {\n\t\tt.Fatal(\"PutObject err:\", err)\n\t}\n\n\t//Anonymous to get\n\turl := \"http://\" + *sc.Client.Config.Endpoint + string(os.PathSeparator) + TEST_BUCKET + string(os.PathSeparator) + TEST_KEY\n\tstatusCode, _, err := HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be AccessDenied\n\tif statusCode != http.StatusForbidden {\n\t\tt.Fatal(\"StatusCode should be AccessDenied(403), but the code is:\", statusCode)\n\t}\n\n\terr = sc.PutBucketPolicy(TEST_BUCKET, GetObjectPolicy_1)\n\tif err != nil {\n\t\tt.Fatal(\"PutBucketPolicy err:\", err)\n\t}\n\n\tpolicy, err := sc.GetBucketPolicy(TEST_BUCKET)\n\tif err != nil {\n\t\tt.Fatal(\"GetBucketPolicy err:\", err)\n\t}\n\tt.Log(\"Bucket policy:\", Format(policy))\n\n\t// After set policy\n\tstatusCode, data, err := HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be STATUS_OK\n\tif statusCode != http.StatusOK {\n\t\tt.Fatal(\"StatusCode should be STATUS_OK(200), but the code is:\", statusCode)\n\t}\n\tt.Log(\"Get object value:\", string(data))\n\n\terr = sc.DeleteBucketPolicy(TEST_BUCKET)\n\tif err != nil {\n\t\tt.Fatal(\"DeleteBucketPolicy err:\", err)\n\t}\n\n\t//After delete policy\n\tstatusCode, _, err = HTTPRequestToGetObject(url)\n\tif err != nil {\n\t\tt.Fatal(\"GetObject err:\", err)\n\t}\n\t//StatusCode should be AccessDenied\n\tif statusCode != http.StatusForbidden {\n\t\tt.Fatal(\"StatusCode should be AccessDenied(403), but the code is:\", statusCode)\n\t}\n\n\terr = sc.DeleteObject(TEST_BUCKET, TEST_KEY)\n\tif err != nil {\n\t\tt.Fatal(\"DeleteObject err:\", err)\n\t}\n}", "func NewS3(ctx context.Context, config *config.Control) (*S3, error) {\n\tif config.EtcdS3BucketName == \"\" {\n\t\treturn nil, errors.New(\"s3 bucket name was not set\")\n\t}\n\ttr := http.DefaultTransport\n\n\tswitch {\n\tcase config.EtcdS3EndpointCA != \"\":\n\t\ttrCA, err := setTransportCA(tr, config.EtcdS3EndpointCA, config.EtcdS3SkipSSLVerify)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttr = trCA\n\tcase config.EtcdS3 && config.EtcdS3SkipSSLVerify:\n\t\ttr.(*http.Transport).TLSClientConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: config.EtcdS3SkipSSLVerify,\n\t\t}\n\t}\n\n\tvar creds *credentials.Credentials\n\tif len(config.EtcdS3AccessKey) == 0 && len(config.EtcdS3SecretKey) == 0 {\n\t\tcreds = credentials.NewIAM(\"\") // for running on ec2 instance\n\t} else {\n\t\tcreds = credentials.NewStaticV4(config.EtcdS3AccessKey, config.EtcdS3SecretKey, \"\")\n\t}\n\n\topt := minio.Options{\n\t\tCreds: creds,\n\t\tSecure: !config.EtcdS3Insecure,\n\t\tRegion: config.EtcdS3Region,\n\t\tTransport: tr,\n\t\tBucketLookup: bucketLookupType(config.EtcdS3Endpoint),\n\t}\n\tc, err := minio.New(config.EtcdS3Endpoint, &opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Checking if S3 bucket %s exists\", config.EtcdS3BucketName)\n\n\tctx, cancel := context.WithTimeout(ctx, config.EtcdS3Timeout)\n\tdefer cancel()\n\n\texists, err := c.BucketExists(ctx, config.EtcdS3BucketName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"bucket: %s does not exist\", config.EtcdS3BucketName)\n\t}\n\tlogrus.Infof(\"S3 bucket %s exists\", config.EtcdS3BucketName)\n\n\treturn &S3{\n\t\tconfig: config,\n\t\tclient: c,\n\t}, nil\n}", "func TestIsValidLocationContraint(t *testing.T) {\n\t// generates the input request with XML bucket configuration set to the request body.\n\tcreateExpectedRequest := func(req *http.Request, location string) (*http.Request, error) {\n\t\tcreateBucketConfig := createBucketLocationConfiguration{}\n\t\tcreateBucketConfig.Location = location\n\t\tvar createBucketConfigBytes []byte\n\t\tcreateBucketConfigBytes, e := xml.Marshal(createBucketConfig)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tcreateBucketConfigBuffer := bytes.NewBuffer(createBucketConfigBytes)\n\t\treq.Body = ioutil.NopCloser(createBucketConfigBuffer)\n\t\treturn req, nil\n\t}\n\n\ttestCases := []struct {\n\t\tlocationForInputRequest string\n\t\tserverConfigRegion string\n\t\texpectedCode APIErrorCode\n\t}{\n\t\t// Test case - 1.\n\t\t{\"us-east-1\", \"us-east-1\", ErrNone},\n\t\t// Test case - 2.\n\t\t// In case of empty request body ErrNone is returned.\n\t\t{\"\", \"us-east-1\", ErrNone},\n\t\t// Test case - 3.\n\t\t{\"eu-central-1\", \"us-east-1\", ErrInvalidRegion},\n\t}\n\tfor i, testCase := range testCases {\n\t\tinputRequest, e := createExpectedRequest(&http.Request{}, testCase.locationForInputRequest)\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to Marshal bucket configuration\", i+1)\n\t\t}\n\t\tactualCode := isValidLocationContraint(inputRequest.Body, testCase.serverConfigRegion)\n\t\tif testCase.expectedCode != actualCode {\n\t\t\tt.Errorf(\"Test %d: Expected the APIErrCode to be %d, but instead found %d\", i+1, testCase.expectedCode, actualCode)\n\t\t}\n\t}\n}", "func PreSignS3(c *gin.Context) {\n\tfileName := c.Query(\"file-name\")\n\tif fileName == \"\" {\n\t\tc.JSON(http.StatusBadRequest, []string{\"Invalid file-name\"})\n\t\treturn\n\t}\n\tfileName = fileName + \"-\" + uuid.NewV4().String()\n\n\tcontentType := c.Query(\"content-type\")\n\tif contentType == \"\" {\n\t\tc.JSON(http.StatusBadRequest, []string{\"Invalid content-type\"})\n\t\treturn\n\t}\n\text, err := mime.ExtensionsByType(contentType)\n\tif err != nil {\n\t\tlog.Printf(\"unknown mimetype err :%v\", err)\n\t\tc.JSON(http.StatusBadRequest, []string{\"Invalid content-type\"})\n\t\treturn\n\t}\n\tlog.Printf(\"ext: %v\", ext)\n\tfileName = fileName + ext[0]\n\t//id := uuid.NewV4().String()\n\treq, _ := svc.PutObjectRequest(&s3.PutObjectInput{\n\t\tBucket: aws.String(bucketName),\n\t\tKey: aws.String(fileName),\n\t\tContentType: aws.String(contentType),\n\t\tACL: aws.String(\"public-read\"),\n\t})\n\tsignedURL, headers, err := req.PresignRequest(1 * time.Minute)\n\tif err != nil {\n\t\tlog.Printf(\"error: %v\", err)\n\t\tc.JSON(http.StatusInternalServerError, []string{\"error\"})\n\t\treturn\n\t}\n\tm := make(map[string]interface{})\n\theads := make(map[string]string)\n\tfor k, values := range headers {\n\t\tfor _, value := range values {\n\t\t\theads[k] = value\n\t\t}\n\t}\n\tm[\"headers\"] = heads\n\tlog.Printf(\"url: %v\", signedURL)\n\turl := \"https://\" + bucketName + \".s3.amazonaws.com/\" + fileName\n\n\tm[\"signedRequest\"] = signedURL\n\tm[\"url\"] = url\n\tc.JSON(http.StatusOK, m)\n}", "func TestTerraformAwsS3Example(t *testing.T) {\n\tt.Parallel()\n\n\tconst (\n\t\tawsRegion = \"eu-west-1\"\n\t\texpectedBucketName = \"paloth-test-bucket.\"\n\t\texpectedStatus = \"Enabled\"\n\t)\n\n\t// Construct the terraform options with default retryable errors to handle the most common retryable errors in\n\t// terraform testing.\n\tterraformOptions := terraform.WithDefaultRetryableErrors(t, &terraform.Options{\n\t\tTerraformDir: \"../..\",\n\t})\n\n\tdefer terraform.Destroy(t, terraformOptions)\n\n\tterraform.InitAndApply(t, terraformOptions)\n\n\tbucketID := terraform.Output(t, terraformOptions, \"bucket_name\")\n\n\tassert.Equal(t, expectedBucketName, bucketID)\n\n\tactualStatus := aws.GetS3BucketVersioning(t, awsRegion, bucketID)\n\n\tassert.Equal(t, expectedStatus, actualStatus)\n}", "func uploadToS3(data urlbox.ShotData) (s3Link string) {\n\tif data.URL != \"\" && data.Width > 0 && data.Height > 0 {\n\t\tawsSecret := os.Getenv(\"SNAPMAKER_AWS_ACCESS_SECRET\")\n\t\tawsKey := os.Getenv(\"SNAPMAKER_AWS_ACCESS_KEY\")\n\n\t\tif awsSecret == \"\" || awsKey == \"\" {\n\t\t\tlog.Fatal(\"[!]invalid AWS credentials\")\n\t\t}\n\t\tauth, _ := aws.GetAuth(awsKey, awsSecret)\n\t\tclient := s3.New(auth, aws.USEast)\n\n\t\tsnapBucket := client.Bucket(BUCKETNAME)\n\n\t\tfileName := urlbox.GetFileName(data)\n\t\tbytes, filetype := getFile(fileName)\n\t\tsnapBucket.Put(fileName, bytes, filetype, s3.PublicRead)\n\t\ts3Link = snapBucket.URL(fileName)\n\t\tos.Remove(fileName)\n\t}\n\treturn\n}", "func (s3 *S3Resource) getS3BucketURLString() (Url *url.URL, err error) {\n\tendpoint, err := s3util.GetS3Endpoint(s3.context, s3.s3Object.Region)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbucketURL := \"https://\" + endpoint + \"/\" + s3.s3Object.Bucket\n\treturn url.Parse(bucketURL)\n}", "func ConfigureS3Bucket(_ context.Context, cm resource.Claim, cs resource.Class, mg resource.Managed) error {\n\tb, cmok := cm.(*storagev1alpha1.Bucket)\n\tif !cmok {\n\t\treturn errors.Errorf(\"expected resource claim %s to be %s\", cm.GetName(), storagev1alpha1.BucketGroupVersionKind)\n\t}\n\n\trs, csok := cs.(*v1alpha3.S3BucketClass)\n\tif !csok {\n\t\treturn errors.Errorf(\"expected resource class %s to be %s\", cs.GetName(), v1alpha3.S3BucketClassGroupVersionKind)\n\t}\n\n\ts3b, mgok := mg.(*v1alpha3.S3Bucket)\n\tif !mgok {\n\t\treturn errors.Errorf(\"expected managed resource %s to be %s\", mg.GetName(), v1alpha3.S3BucketGroupVersionKind)\n\t}\n\n\tspec := &v1alpha3.S3BucketSpec{\n\t\tResourceSpec: runtimev1alpha1.ResourceSpec{\n\t\t\tReclaimPolicy: runtimev1alpha1.ReclaimRetain,\n\t\t},\n\t\tS3BucketParameters: rs.SpecTemplate.S3BucketParameters,\n\t}\n\n\tif b.Spec.PredefinedACL != nil {\n\t\tspec.CannedACL = translateACL(b.Spec.PredefinedACL)\n\t}\n\n\tif b.Spec.LocalPermission != nil {\n\t\tspec.LocalPermission = b.Spec.LocalPermission\n\t}\n\n\tspec.WriteConnectionSecretToReference = &runtimev1alpha1.SecretReference{\n\t\tNamespace: rs.SpecTemplate.WriteConnectionSecretsToNamespace,\n\t\tName: string(cm.GetUID()),\n\t}\n\tspec.ProviderReference = rs.SpecTemplate.ProviderReference.DeepCopy()\n\tspec.ReclaimPolicy = rs.SpecTemplate.ReclaimPolicy\n\n\ts3b.Spec = *spec\n\n\treturn nil\n}", "func validateEndPoint(endPointPointer *string) error {\n\tendPoint := *endPointPointer\n\n\tif endPoint == \"\" {\n\t\tendPoint = defaultEndPointURI\n\t}\n\n\tmatch, err := regexp.MatchString(`^\\w+://`, endPoint)\n\tif err != nil {\n\t\treturn util.NewPersistentError(\"InvalidEndpoint\",\n\t\t\tfmt.Sprintf(\"Invalid endpoint url %q: %v\", endPoint, err))\n\t}\n\tif !match {\n\t\tendPoint = \"https://\" + endPoint\n\t}\n\tu, err := url.Parse(endPoint)\n\tif err != nil {\n\t\treturn util.NewPersistentError(\"InvalidEndpoint\",\n\t\t\tfmt.Sprintf(\"Invalid endpoint url %q: %v\", endPoint, err))\n\t}\n\tif u.Scheme == \"\" {\n\t\tu.Scheme = \"https\"\n\t}\n\n\t*endPointPointer = u.String()\n\n\treturn nil\n}", "func ValidateSignature(ctx context.Context, req *http.Request, v ClientStorage) error {\n\tpreq, err := newProviderRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = v.ValidateNonce(ctx, preq.clientKey, preq.nonce, preq.timestamp, req); err != nil {\n\t\treturn err\n\t}\n\tsigner, invalidClient := v.GetSigner(ctx, preq.clientKey, preq.signatureMethod, req)\n\n\t// Check signature even if client is invalid to prevent timing attacks.\n\tinvalidSignature := preq.checkSignature(signer)\n\tif invalidClient != nil {\n\t\treturn invalidClient\n\t}\n\treturn invalidSignature\n}", "func PresignedUploadURL(w http.ResponseWriter, r *http.Request) {\n\tvar fileUrl FileUrl\n\tvar bucket string\n\n\tvar key = r.URL.Query().Get(\"key\")\n\n\tif len(r.URL.Query().Get(\"bucket\")) > 0 {\n\t\tbucket = r.URL.Query().Get(\"bucket\")\n\t} else {\n\t\tbucket = os.Getenv(\"AWS_S3_DEFAULT_BUCKET\")\n\t}\n\n\turlStr, err := storagecloud.GetPresignedUploadURL(bucket, key)\n\tfileUrl.Url = urlStr\n\tfileUrl.Method = \"PUT\"\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfileUrlJson, err := json.Marshal(fileUrl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(fileUrlJson)\n}", "func NewS3Service(accessKey string, secretKey string) (*S3Service,error) {\n return &S3Service{DEFAULT_S3_ENDPOINT, accessKey, secretKey, &http.Client{}}, nil\n}", "func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {\n\tpath := c.hostURL.Path\n\t// Convert any virtual host styled requests.\n\t//\n\t// For the time being this check is introduced for S3,\n\t// If you have custom virtual styled hosts please.\n\t// List them below.\n\tif c.virtualStyle {\n\t\tvar bucket string\n\t\thostIndex := strings.Index(c.hostURL.Host, \"s3\")\n\t\tif hostIndex == -1 {\n\t\t\thostIndex = strings.Index(c.hostURL.Host, \"storage.googleapis\")\n\t\t}\n\t\tif hostIndex > 0 {\n\t\t\tbucket = c.hostURL.Host[:hostIndex-1]\n\t\t\tpath = string(c.hostURL.Separator) + bucket + c.hostURL.Path\n\t\t}\n\t}\n\tsplits := strings.SplitN(path, string(c.hostURL.Separator), 3)\n\tswitch len(splits) {\n\tcase 0, 1:\n\t\tbucketName = \"\"\n\t\tobjectName = \"\"\n\tcase 2:\n\t\tbucketName = splits[1]\n\t\tobjectName = \"\"\n\tcase 3:\n\t\tbucketName = splits[1]\n\t\tobjectName = splits[2]\n\t}\n\treturn bucketName, objectName\n}", "func (m *ServiceEndpointRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataSourceDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResultTransformationDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateServiceEndpointDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func deleteFileFromS3(s3Endpoint string, awsAccessKeyID string, awsSecretAccessKey string, useSsl bool, awsRegion string, s3Location string, s3BucketName string) error {\n\t// Create an instance of the Minio Client\n minioClient, err := minio.New(s3Endpoint, awsAccessKeyID, awsSecretAccessKey, useSsl)\n if err != nil {\n return err\n }\n\n\t// Delete the file from S3\n\terr = minioClient.RemoveObject(s3BucketName, s3Location)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func parseURI(uri string) (bucket, key string, err error) {\n\tif !strings.HasPrefix(uri, \"s3://\") {\n\t\treturn \"\", \"\", fmt.Errorf(\"uri %s protocol is not s3\", uri)\n\t}\n\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn \"\", \"\", errors.Wrapf(err, \"parse uri %s\", uri)\n\t}\n\n\tbucket, key = u.Host, strings.TrimPrefix(u.Path, \"/\")\n\treturn bucket, key, nil\n}", "func (bv *BaseVSphere) Validate() error {\n\tif err := bv.Base.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif bv.Username == \"\" {\n\t\treturn ErrNoUsername\n\t}\n\n\tif bv.Password == \"\" {\n\t\treturn ErrNoPassword\n\t}\n\n\tif bv.Endpoint == \"\" {\n\t\treturn ErrNoEndpoint\n\t}\n\n\t// Validate the URL to the API endpoint and set the username and password info\n\tendpoint, err := url.Parse(bv.Endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tendpoint.User = url.UserPassword(bv.Username, bv.Password)\n\tbv.url = endpoint\n\n\treturn nil\n}", "func S3(cfg *config.Config) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"enable_home\": false,\n\t\t\"region\": cfg.Drivers.S3.Region,\n\t\t\"access_key\": cfg.Drivers.S3.AccessKey,\n\t\t\"secret_key\": cfg.Drivers.S3.SecretKey,\n\t\t\"endpoint\": cfg.Drivers.S3.Endpoint,\n\t\t\"bucket\": cfg.Drivers.S3.Bucket,\n\t\t\"prefix\": cfg.Drivers.S3.Root,\n\t}\n}", "func S3Path(path string) bool {\n\treturn s3path(path)\n}", "func (s *ParsingURLSuite) TestFileURLPartsWithIPEndpointStyle(c *chk.C) {\n\tp := s.testFileURLPartsWithIPEndpointStyle(c, \"https://105.232.1.23:80/accountname\")\n\tc.Assert(p.Host, chk.Equals, \"105.232.1.23:80\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"http://105.232.1.23/accountname\")\n\tc.Assert(p.Host, chk.Equals, \"105.232.1.23\")\n\tc.Assert(p.Scheme, chk.Equals, \"http\")\n\tc.Assert(p.ShareName, chk.Equals, \"\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://255.255.255.255/accountname/sharename\")\n\tc.Assert(p.Host, chk.Equals, \"255.255.255.255\")\n\tc.Assert(p.Scheme, chk.Equals, \"https\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://255.255.255.255/accountname/sharename\")\n\tc.Assert(p.Host, chk.Equals, \"255.255.255.255\")\n\tc.Assert(p.Scheme, chk.Equals, \"https\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://255.255.255.255:4392/accountname/sharename/directory/\")\n\tc.Assert(p.Host, chk.Equals, \"255.255.255.255:4392\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://255.255.255.255:4392/accountname/sharename/file\")\n\tc.Assert(p.Host, chk.Equals, \"255.255.255.255:4392\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"file\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://255.255.255.255:4392/accountname/sharename/directory/file\")\n\tc.Assert(p.Host, chk.Equals, \"255.255.255.255:4392\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/file\")\n\n\t// IPv6 case.\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://[1080:0:0:0:8:800:200C:417A]:1234/accountname/sharename/directory/file\")\n\tc.Assert(p.Host, chk.Equals, \"[1080:0:0:0:8:800:200C:417A]:1234\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/file\")\n}", "func validateBucket(bucket *userdb.Bucket) error {\n\tmaskedAccessKey := maskAccessKey(bucket.AWSSecretAccessKey)\n\tlog.Printf(\"Validating Bucket: %s/%s, AccessKeyID: %s, SecretAccessKey: %s\", bucket.Bucketname, bucket.ReportPath, bucket.AWSAccessKeyID, maskedAccessKey)\n\tregion, err := billingbucket.GetBucketRegion(bucket.Bucketname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbucket.Region = region\n\tbillbuck, err := billingbucket.NewAWSBillingBucket(bucket.AWSAccessKeyID, bucket.AWSSecretAccessKey, bucket.Bucketname, bucket.Region, bucket.ReportPath)\n\tif err != nil {\n\t\tlog.Printf(\"Could not create billing bucket: %s\", err)\n\t\treturn err\n\t}\n\tdirContents, err := billbuck.ListDir(bucket.ReportPath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to list billing bucket: %s\", err)\n\t\treturn err\n\t}\n\tif len(dirContents) == 0 {\n\t\treturn errors.Errorf(errors.CodeBadRequest, \"Bucket report path %s/%s empty or does not exist\", bucket.Bucketname, bucket.ReportPath)\n\t}\n\treturn nil\n}", "func TestEndpointCase51(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn:aws:s3:us-west-2:123456789012:stream/testStream\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: The ARN was not for the Kinesis service, found: s3.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func (output AmazonS3URL) String() string {\n\treturn fmt.Sprintf(\"{Region: %s; Bucket: %s; Key: %s; IsValidS3URI: %v; IsPathStyle: %v}\",\n\t\toutput.Region, output.Bucket, output.Key, output.IsValidS3URI, output.IsPathStyle)\n}", "func s3parse(path string) (string, string, string) {\n\ts := strings.Split(path, \":\")\n\tif len(s) < 6 {\n\t\treturn \"\", \"\", \"\"\n\t}\n\tregion := s[3]\n\tfile := s[5]\n\tslash := strings.IndexByte(file, '/')\n\tif slash < 1 {\n\t\treturn \"\", \"\", \"\"\n\t}\n\tbucket := file[:slash]\n\tkey := file[slash+1:]\n\treturn region, bucket, key\n}", "func isBucketVirtualStyle(host string) bool {\n\ts3Virtual, _ := filepath.Match(\"*.s3*.amazonaws.com\", host)\n\tgoogleVirtual, _ := filepath.Match(\"*.storage.googleapis.com\", host)\n\treturn s3Virtual || googleVirtual\n}", "func validateBucketSSEConfig(r io.Reader) (*bucketsse.BucketSSEConfig, error) {\n\tencConfig, err := bucketsse.ParseBucketSSEConfig(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(encConfig.Rules) == 1 && encConfig.Rules[0].DefaultEncryptionAction.Algorithm == bucketsse.AES256 {\n\t\treturn encConfig, nil\n\t}\n\treturn nil, errors.New(\"Unsupported bucket encryption configuration\")\n}", "func UpdateEndpoint(stack *middleware.Stack, options UpdateEndpointOptions) error {\n\t// enable dual stack support\n\treturn stack.Serialize.Insert(&s3shared.EnableDualstack{\n\t\tUseDualstack: options.UseDualstack,\n\t\tServiceID: \"s3-control\",\n\t}, \"OperationSerializer\", middleware.After)\n}", "func Check() error {\n\tfmt.Println(\"Checking S3...\")\n\tchecks := []CheckFn{\n\t\tCheckPublicAccessBlockingEnabled,\n\t}\n\n\tfor _, check := range checks {\n\t\terr := check()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *ParsingURLSuite) TestFileURLPartsWithDomainHostname(c *chk.C) {\n\tp := s.testFileURLPartsWithIPEndpointStyle(c, \"https://accountName.blob.core.windows.net\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.ShareName, chk.Equals, \"\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"http://accountName.blob.core.windows.net/sharename\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.Scheme, chk.Equals, \"http\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"https://accountName.blob.core.windows.net/sharename/directory/\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.Scheme, chk.Equals, \"https\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"http://accountName.blob.core.windows.net/sharename/file\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"file\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"http://accountName.blob.core.windows.net/sharename/directory/file.txt\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/file.txt\")\n\n\tp = s.testFileURLPartsWithIPEndpointStyle(c, \"http://accountName.blob.core.windows.net/sharename/directory/d2/d3/d4/\")\n\tc.Assert(p.Host, chk.Equals, \"accountName.blob.core.windows.net\")\n\tc.Assert(p.ShareName, chk.Equals, \"sharename\")\n\tc.Assert(p.DirectoryOrFilePath, chk.Equals, \"directory/d2/d3/d4/\")\n}", "func (m EndpointMetadata) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := validate.Required(\"\", \"body\", EndpointMetadata(m)); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func s3Handler(w http.ResponseWriter, r *http.Request) {\n\tif DescribeRestoreStateAs == NotStartedHead {\n\t\t// S3 HEAD handler will tell us this item is in Glacier, but not yet S3\n\t\tnetwork.S3HeadHandler(w, r)\n\t} else if DescribeRestoreStateAs == NotStartedAcceptNow {\n\t\t// Restore handler accepts a Glacier restore requests\n\t\tnetwork.S3RestoreHandler(w, r)\n\t} else if DescribeRestoreStateAs == NotStartedRejectNow {\n\t\t// Reject handler reject a Glacier restore requests\n\t\tnetwork.S3RestoreRejectHandler(w, r)\n\t} else if DescribeRestoreStateAs == InProgressHead {\n\t\t// This handler is an S3 call that tells us the Glacier restore\n\t\t// is in progress, but not yet complete.\n\t\tnetwork.S3HeadRestoreInProgressHandler(w, r)\n\t} else if DescribeRestoreStateAs == InProgressGlacier {\n\t\t// This is a Glacier API call that tells us the restore is\n\t\t// in progress, but not yet complete.\n\t\tnetwork.S3RestoreInProgressHandler(w, r)\n\t} else if DescribeRestoreStateAs == Completed {\n\t\t// This is an S3 API call, where the HEAD response includes\n\t\t// info saying the restore is complete and the item will be\n\t\t// available in S3 until a specific date/time.\n\t\tnetwork.S3HeadRestoreCompletedHandler(w, r)\n\t}\n}", "func (s3Uploader S3Uploader) Upload(id string, f io.ReadSeeker, hours int) (url string, err error) {\n\tfullKey := aws.String(s3Uploader.S3Key + strconv.Itoa(rand.Intn(999999)) + \"_\" + base64.StdEncoding.EncodeToString([]byte(id)))\n\t_, err = s3Uploader.S3SVC.PutObject(&s3.PutObjectInput{\n\t\tBucket: aws.String(s3Uploader.S3Bucket),\n\t\tKey: fullKey,\n\t\tBody: f,\n\t})\n\n\tif err != nil {\n\t\treturn url, errors.Wrap(err, \"Failed to upload object to S3\")\n\t}\n\n\treq, _ := s3Uploader.S3SVC.GetObjectRequest(&s3.GetObjectInput{\n\t\tBucket: aws.String(s3Uploader.S3Bucket),\n\t\tKey: fullKey,\n\t})\n\n\turlStr, err := req.Presign(24 * time.Hour)\n\tif err != nil {\n\t\treturn urlStr, errors.Wrap(err, \"Failed to sign request\")\n\t}\n\n\treturn urlStr, nil\n}", "func (s *k8sStore) ingressIsValid(ing *networkingv1.Ingress) bool {\n\tvar endpointKey string\n\tif ing.Spec.DefaultBackend != nil { // stream\n\t\tendpointKey = fmt.Sprintf(\"%s/%s\", ing.Namespace, ing.Spec.DefaultBackend.Service.Name)\n\t} else { // http\n\tLoop:\n\t\tfor _, rule := range ing.Spec.Rules {\n\t\t\tfor _, path := range rule.IngressRuleValue.HTTP.Paths {\n\t\t\t\tendpointKey = fmt.Sprintf(\"%s/%s\", ing.Namespace, path.Backend.Service.Name)\n\t\t\t\tif endpointKey != \"\" {\n\t\t\t\t\tbreak Loop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\titem, exists, err := s.listers.Endpoint.GetByKey(endpointKey)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Can not get endpoint by key(%s): %v\", endpointKey, err)\n\t\treturn false\n\t}\n\tif !exists {\n\t\tlogrus.Debugf(\"Endpoint %s does not exist.\", endpointKey)\n\t\treturn false\n\t}\n\tendpoint, ok := item.(*corev1.Endpoints)\n\tif !ok {\n\t\tlogrus.Errorf(\"Cant not convert %v to %v\", reflect.TypeOf(item), reflect.TypeOf(endpoint))\n\t\treturn false\n\t}\n\tif len(endpoint.Subsets) == 0 {\n\t\tlogrus.Debugf(\"Endpoints(%s) is empty, ignore it\", endpointKey)\n\t\treturn false\n\t}\n\tif !hasReadyAddresses(endpoint) {\n\t\tlogrus.Debugf(\"Endpoints(%s) is empty, ignore it\", endpointKey)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func genS3URL(region, bucket, s3Path string) string {\n\treturn fmt.Sprintf(\"https://s3-%s.amazonaws.com/%s/%s\", region, bucket, s3Path)\n}", "func HandleRequest(ctx context.Context, event events.S3Event) (string, error) {\n\n\t// Even if multiple events are sent, should be from same src\n\t// Maybe later spin off a concurrent function for every record\n\tfor _, record := range event.Records {\n\t\ts3Ses, err := session.NewSession(&aws.Config{\n\t\t\tRegion: &record.AWSRegion,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not instantiate s3 session %v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// Should I add the bucket names as env vars\n\t\t// or define them here somehow\n\t\tsrcBucket := record.S3.Bucket.Name\n\t\tsrcKey := record.S3.Object.Key\n\t\tfileWithoutExtension, fileExt := getImageNameAndExt(srcKey)\n\n\t\tphotoBuff := aws.WriteAtBuffer{} // Store the picture to memory\n\t\ts3downloader := s3manager.NewDownloader(s3Ses)\n\t\t_, err = s3downloader.Download(&photoBuff, &s3.GetObjectInput{\n\t\t\tBucket: &srcBucket,\n\t\t\tKey: &srcKey,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not download %s from bucket %s %v\", srcKey, srcBucket, err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not decode downloaded image %s %v\", srcKey, err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tphotoBytes := photoBuff.Bytes()\n\t\ts3uploader := s3manager.NewUploader(s3Ses)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(len(defaultPhotoSizes))\n\n\t\tfor _, size := range defaultPhotoSizes {\n\t\t\tsize := size\n\t\t\tgo func() {\n\t\t\t\tlog.Printf(\"size in go func is %v\", size)\n\t\t\t\tdefer wg.Done()\n\t\t\t\tresizedImage, err := resizeImage(&photoBytes, &size)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tencodeImageAndUploadToS3(resizedImage, fileWithoutExtension, fileExt, size.Suffix, s3uploader)\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t\tlog.Printf(\"Resized all images for %s\", srcKey)\n\t}\n\treturn \"Succesfully processed req\", nil\n}", "func (c *Client) UploadToS3(postData *RFPresignedPostData, filePath string) error {\n\tvar req *http.Request\n\tfileName := filepath.Base(filePath)\n\n\tf, err := os.Open(filePath)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileSize := int64(fi.Size())\n\n\tcontentLength := postData.emptyMultipartSize(\"file\", fileName) + fileSize\n\n\treadBody, writeBody := io.Pipe()\n\tdefer readBody.Close()\n\n\twriter := multipart.NewWriter(writeBody)\n\n\t// Do the writes async streamed\n\terrChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer writeBody.Close()\n\n\t\t// Add the required fields from S3\n\t\twriteFields(postData.RequiredFields, writer)\n\n\t\tpart, err := writer.CreateFormFile(\"file\", fileName)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tif _, err := io.CopyN(part, f, fileSize); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\terrChan <- writer.Close()\n\t}()\n\n\t// Create the Request\n\turl := postData.URL\n\treq, err = http.NewRequest(\"POST\", url, readBody)\n\tif err != nil {\n\t\t<-errChan\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\treq.ContentLength = contentLength\n\n\t// Perform the upload\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\t<-errChan\n\t\treturn err\n\t}\n\n\tstatus := resp.StatusCode\n\tif status >= 300 {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\n\t\t<-errChan\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn fmt.Errorf(\"There was an error uploading your file - %v: %v\", fileName, string(body))\n\t}\n\n\treturn nil\n}", "func TestEndpointCase34(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-gov-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://kinesis.us-gov-east-1.amazonaws.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func testDeleteBucketPolicyHandler(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,\n\tcredentials auth.Credentials, t *testing.T) {\n\n\t// template for constructing HTTP request body for PUT bucket policy.\n\tbucketPolicyTemplate := `{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": [\n \"s3:GetBucketLocation\",\n \"s3:ListBucket\"\n ],\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": [\n \"*\"\n ]\n },\n \"Resource\": [\n \"arn:aws:s3:::%s\"\n ]\n },\n {\n \"Action\": [\n \"s3:GetObject\"\n ],\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": [\n \"*\"\n ]\n },\n \"Resource\": [\n \"arn:aws:s3:::%s/this*\"\n ]\n }\n ]\n}`\n\n\t// Writing bucket policy before running test on DeleteBucketPolicy.\n\tputTestPolicies := []struct {\n\t\tbucketName string\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected Response.\n\t\texpectedRespStatus int\n\t}{\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNoContent,\n\t\t},\n\t}\n\n\t// Iterating over the cases and writing the bucket policy.\n\t// its required to write the policies first before running tests on GetBucketPolicy.\n\tfor i, testPolicy := range putTestPolicies {\n\t\t// obtain the put bucket policy request body.\n\t\tbucketPolicyStr := fmt.Sprintf(bucketPolicyTemplate, testPolicy.bucketName, testPolicy.bucketName)\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"PUT\", getPutPolicyURL(\"\", testPolicy.bucketName),\n\t\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)), testPolicy.accessKey, testPolicy.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\tif recV4.Code != testPolicy.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testPolicy.expectedRespStatus, recV4.Code)\n\t\t}\n\t}\n\n\t// testcases with input and expected output for DeleteBucketPolicyHandler.\n\ttestCases := []struct {\n\t\tbucketName string\n\t\taccessKey string\n\t\tsecretKey string\n\t\t// expected response.\n\t\texpectedRespStatus int\n\t}{\n\t\t// Test case - 1.\n\t\t{\n\t\t\tbucketName: bucketName,\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNoContent,\n\t\t},\n\t\t// Test case - 2.\n\t\t// Case with non-existent-bucket.\n\t\t{\n\t\t\tbucketName: \"non-existent-bucket\",\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusNotFound,\n\t\t},\n\t\t// Test case - 3.\n\t\t// Case with invalid bucket name.\n\t\t{\n\t\t\tbucketName: \".invalid-bucket-name\",\n\t\t\taccessKey: credentials.AccessKey,\n\t\t\tsecretKey: credentials.SecretKey,\n\t\t\texpectedRespStatus: http.StatusBadRequest,\n\t\t},\n\t}\n\t// Iterating over the cases and deleting the bucket policy and then asserting response.\n\tfor i, testCase := range testCases {\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV4 := httptest.NewRecorder()\n\t\t// construct HTTP request for Delete bucket policy endpoint.\n\t\treqV4, err := newTestSignedRequestV4(\"DELETE\", getDeletePolicyURL(\"\", testCase.bucketName),\n\t\t\t0, nil, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for GetBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler, DeleteBucketPolicyHandler handles the request.\n\t\tapiRouter.ServeHTTP(recV4, reqV4)\n\t\t// Assert the response code with the expected status.\n\t\tif recV4.Code != testCase.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testCase.expectedRespStatus, recV4.Code)\n\t\t}\n\t}\n\n\t// Iterating over the cases and writing the bucket policy.\n\t// its required to write the policies first before running tests on GetBucketPolicy.\n\tfor i, testPolicy := range putTestPolicies {\n\t\t// obtain the put bucket policy request body.\n\t\tbucketPolicyStr := fmt.Sprintf(bucketPolicyTemplate, testPolicy.bucketName, testPolicy.bucketName)\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for PUT bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"PUT\", getPutPolicyURL(\"\", testPolicy.bucketName),\n\t\t\tint64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)), testPolicy.accessKey, testPolicy.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for PutBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\tif recV2.Code != testPolicy.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testPolicy.expectedRespStatus, recV2.Code)\n\t\t}\n\t}\n\n\tfor i, testCase := range testCases {\n\t\t// initialize HTTP NewRecorder, this records any mutations to response writer inside the handler.\n\t\trecV2 := httptest.NewRecorder()\n\t\t// construct HTTP request for Delete bucket policy endpoint.\n\t\treqV2, err := newTestSignedRequestV2(\"DELETE\", getDeletePolicyURL(\"\", testCase.bucketName),\n\t\t\t0, nil, testCase.accessKey, testCase.secretKey)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %d: Failed to create HTTP request for GetBucketPolicyHandler: <ERROR> %v\", i+1, err)\n\t\t}\n\t\t// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.\n\t\t// Call the ServeHTTP to execute the handler, DeleteBucketPolicyHandler handles the request.\n\t\tapiRouter.ServeHTTP(recV2, reqV2)\n\t\t// Assert the response code with the expected status.\n\t\tif recV2.Code != testCase.expectedRespStatus {\n\t\t\tt.Fatalf(\"Case %d: Expected the response status to be `%d`, but instead found `%d`\", i+1, testCase.expectedRespStatus, recV2.Code)\n\t\t}\n\t}\n\t// Test for Anonymous/unsigned http request.\n\t// Bucket policy related functions doesn't support anonymous requests, setting policies shouldn't make a difference.\n\t// create unsigned HTTP request for PutBucketPolicyHandler.\n\tanonReq, err := newTestRequest(\"DELETE\", getPutPolicyURL(\"\", bucketName), 0, nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Minio %s: Failed to create an anonymous request for bucket \\\"%s\\\": <ERROR> %v\",\n\t\t\tinstanceType, bucketName, err)\n\t}\n\n\t// ExecObjectLayerAPIAnonTest - Calls the HTTP API handler using the anonymous request, validates the ErrAccessDeniedResponse,\n\t// sets the bucket policy using the policy statement generated from `getWriteOnlyObjectStatement` so that the\n\t// unsigned request goes through and its validated again.\n\tExecObjectLayerAPIAnonTest(t, obj, \"DeleteBucketPolicyHandler\", bucketName, \"\", instanceType, apiRouter, anonReq, getReadOnlyObjectStatement)\n\n\t// HTTP request for testing when `objectLayer` is set to `nil`.\n\t// There is no need to use an existing bucket and valid input for creating the request\n\t// since the `objectLayer==nil` check is performed before any other checks inside the handlers.\n\t// The only aim is to generate an HTTP request in a way that the relevant/registered end point is evoked/called.\n\tnilBucket := \"dummy-bucket\"\n\n\tnilReq, err := newTestSignedRequestV4(\"DELETE\", getDeletePolicyURL(\"\", nilBucket),\n\t\t0, nil, \"\", \"\")\n\n\tif err != nil {\n\t\tt.Errorf(\"Minio %s: Failed to create HTTP request for testing the response when object Layer is set to `nil`.\", instanceType)\n\t}\n\t// execute the object layer set to `nil` test.\n\t// `ExecObjectLayerAPINilTest` manages the operation.\n\tExecObjectLayerAPINilTest(t, nilBucket, \"\", instanceType, apiRouter, nilReq)\n}", "func ExtractS3Info(queryParameters map[string]string) (bucketRegion string, bucketName string, objectKey string, err error) {\n\tbucketRegion = queryParameters[\"bucket_region\"]\n\tbucketName = queryParameters[\"bucket_name\"]\n\tobjectKey = queryParameters[\"object_key\"]\n\n\tif bucketRegion == \"\" {\n\t\terr = ErrorQueryStringMissingBucketRegion\n\t\treturn\n\t}\n\n\tif bucketRegion != UsEast1S3Region && bucketRegion != UsWest1S3Region {\n\t\terr = ErrorQueryStringUnsupportedBucketRegion\n\t\treturn\n\t}\n\n\tif bucketName == \"\" {\n\t\terr = ErrorQueryStringMissingBucketName\n\t\treturn\n\t}\n\n\tif objectKey == \"\" {\n\t\terr = ErrorQueryStringMissingObjectKey\n\t\treturn\n\t}\n\n\treturn bucketRegion, bucketName, objectKey, nil\n}", "func HeadS3(ctx *task.Context, from S3Object, profile string) error {\n\tctx.Logf(\"s3 check: %s/%s\\n\", from.Bucket, from.Key)\n\n\tvar err error\n\tsess := session.Must(session.NewSession(&aws.Config{\n\t\tRegion: aws.String(from.Region),\n\t\tCredentials: s3Credentials(ctx, profile),\n\t}))\n\n\tsvc := s3.New(sess)\n\t_, err = svc.HeadObject(&s3.HeadObjectInput{\n\t\tBucket: aws.String(from.Bucket),\n\t\tKey: aws.String(from.Key),\n\t})\n\n\treturn err\n}", "func (c *AwsCredentials) IsValid() error {\n\tif c.AccessKeyId == \"\" {\n\t\treturn fmt.Errorf(\"AccessKeyId is empty\")\n\t}\n\tif c.SecretAccessKey == \"\" {\n\t\treturn fmt.Errorf(\"SecretAccessKey is empty\")\n\t}\n\tif c.SessionToken == \"\" {\n\t\treturn fmt.Errorf(\"SessionToken is empty\")\n\t}\n\treturn nil\n}", "func (c *Client) DownloadPrefixFromS3(bucket string, prefix string, localDirPath string, shouldTrimDirPrefix bool, maxFiles *int64) error {\n\tif _, err := files.CreateDirIfMissing(localDirPath); err != nil {\n\t\treturn err\n\t}\n\tcreatedDirs := strset.New(localDirPath)\n\n\tvar trimPrefix string\n\tif shouldTrimDirPrefix {\n\t\tlastIndex := strings.LastIndex(prefix, \"/\")\n\t\tif lastIndex == -1 {\n\t\t\ttrimPrefix = \"\"\n\t\t} else {\n\t\t\ttrimPrefix = prefix[:lastIndex+1]\n\t\t}\n\t}\n\n\terr := c.S3Iterator(bucket, prefix, true, maxFiles, nil, func(object *s3.Object) (bool, error) {\n\t\tlocalRelPath := *object.Key\n\t\tif shouldTrimDirPrefix {\n\t\t\tlocalRelPath = strings.TrimPrefix(localRelPath, trimPrefix)\n\t\t}\n\n\t\tlocalPath := filepath.Join(localDirPath, localRelPath)\n\n\t\t// check for directory objects\n\t\tif strings.HasSuffix(*object.Key, \"/\") {\n\t\t\tif !createdDirs.Has(localPath) {\n\t\t\t\tif _, err := files.CreateDirIfMissing(localPath); err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tcreatedDirs.Add(localPath)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\n\t\tlocalDir := filepath.Dir(localPath)\n\t\tif !createdDirs.Has(localDir) {\n\t\t\tif _, err := files.CreateDirIfMissing(localDir); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tcreatedDirs.Add(localDir)\n\t\t}\n\n\t\tif err := c.DownloadFileFromS3(bucket, *object.Key, localPath); err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func uploadFileToS3(s3Endpoint string, awsAccessKeyID string, awsSecretAccessKey string, useSsl bool, awsRegion string, localFile string, s3Location string, s3BucketName string) error {\n\t// Create an instance of the Minio Client\n minioClient, err := minio.New(s3Endpoint, awsAccessKeyID, awsSecretAccessKey, useSsl)\n if err != nil {\n return err\n }\n\n\t// Upload the file\n\t_, err = minioClient.FPutObject(s3BucketName, s3Location, localFile, minio.PutObjectOptions{});\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Settings) Validate() error {\n\tif len(s.URI) == 0 {\n\t\treturn fmt.Errorf(\"validate Settings: StorageURI missing\")\n\t}\n\treturn nil\n}", "func (bc BucketConfig) EndpointAsURL() string {\n\tprefix := \"http://\"\n\tif bc.Secure {\n\t\tprefix = \"https://\"\n\t}\n\treturn prefix + bc.Endpoint\n}", "func NewAwsS3ReverseProxy(opts Options) (*Handler, error) {\n\tlog.SetLevel(log.InfoLevel)\n\tif opts.Debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\tscheme := \"https\"\n\tif opts.UpstreamInsecure {\n\t\tscheme = \"http\"\n\t}\n\n\tvar parsedAllowedSourceSubnet []*net.IPNet\n\tfor _, sourceSubnet := range opts.AllowedSourceSubnet {\n\t\t_, subnet, err := net.ParseCIDR(sourceSubnet)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid allowed source subnet: %v\", sourceSubnet)\n\t\t}\n\t\tparsedAllowedSourceSubnet = append(parsedAllowedSourceSubnet, subnet)\n\t}\n\n\tparsedAwsCredentials := make(map[string]string)\n\tfor _, cred := range opts.AwsCredentials {\n\t\td := strings.Split(cred, \",\")\n\t\tif len(d) != 2 || len(d[0]) < 16 || len(d[1]) < 1 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid AWS credentials. Did you separate them with a ',' or are they too short?\")\n\t\t}\n\t\tparsedAwsCredentials[d[0]] = d[1]\n\t}\n\n\tsigners := make(map[string]*v4.Signer)\n\tfor accessKeyID, secretAccessKey := range parsedAwsCredentials {\n\t\tsigners[accessKeyID] = v4.NewSigner(credentials.NewStaticCredentialsFromCreds(credentials.Value{\n\t\t\tAccessKeyID: accessKeyID,\n\t\t\tSecretAccessKey: secretAccessKey,\n\t\t}))\n\t}\n\n\thandler := &Handler{\n\t\tDebug: opts.Debug,\n\t\tUpstreamScheme: scheme,\n\t\tUpstreamEndpoint: opts.UpstreamEndpoint,\n\t\tAllowedSourceEndpoint: opts.AllowedSourceEndpoint,\n\t\tAllowedSourceSubnet: parsedAllowedSourceSubnet,\n\t\tAWSCredentials: parsedAwsCredentials,\n\t\tSigners: signers,\n\t}\n\treturn handler, nil\n}", "func S3UsageInfo(s3Conn S3Conn) (S3Summary, error) {\n\ts3All := S3Summary{}\n\ts3All.S3Name = s3Conn.S3ConnName\n\n\ts3Config := &aws.Config{\n\t\tCredentials: credentials.NewStaticCredentials(s3Conn.S3ConnAccessKey, s3Conn.S3ConnSecretKey, \"\"),\n\t\tEndpoint: aws.String(s3Conn.S3ConnEndpoint),\n\t\tDisableSSL: &s3Conn.S3ConnDisableSsl,\n\t\tDisableEndpointHostPrefix: &s3Conn.S3ConnDisableEdnpointHostPrefix,\n\t\tS3ForcePathStyle: &s3Conn.S3ConnForcePathStyle,\n\t\t// Region aws.String(\"us-east-1\"), // This is counter intuitive but it will fail with a non-AWS region name\n\t\t//Region: aws.String(\"default\"),\n\t\t//Region: aws.String(&s3Conn.S3ConnRegion),\n\t\tRegion: aws.String(s3Conn.S3ConnRegion),\n\t}\n\tnewSession := session.New(s3Config)\n\ts3Client := s3.New(newSession)\n\n\tresult, err := s3Client.ListBuckets(nil)\n\tif err != nil {\n\t\t//log.Fatal(\"Connection to S3 endpoint failed (log.Fatal):\", err)\n\t\tfmt.Println(\"Connection to S3 endpoint failed :\", err)\n\t\ts3All.S3Status = false\n\t\treturn s3All, errors.New(\"s3 endpoint: unable to connect\")\n\t}\n\ts3All.S3Status = true\n\n\t// Processing calculation per Bucket\n\tfor _, b := range result.Buckets {\n\t\tsize, number := countBucketSize(aws.StringValue(b.Name), s3Client)\n\t\tbucketX := Bucket{BucketName: *b.Name, BucketObjectNumber: number, BucketSize: size}\n\t\ts3All.S3Buckets = append(s3All.S3Buckets, bucketX)\n\t\ts3All.S3Size += size\n\t\ts3All.S3ObjectNumber += number\n\t}\n\n\t// Save s3All\n\tbyteArray, err := json.MarshalIndent(s3All, \"\", \" \")\n\terr = ioutil.WriteFile(\"s3Information.json\", byteArray, 0777)\n\tif err != nil {\n\t\tfmt.Println(\"Didn't manage to dump S3 details as a json file, error :\", err)\n\t}\n\treturn s3All, nil\n}", "func New(endpoint, region, accessKey, secretKey string) Client {\n\ts3Client := s3.New(session.New(&aws.Config{\n\t\tS3ForcePathStyle: aws.Bool(true),\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(accessKey, secretKey, \"\"),\n\t\tRegion: aws.String(region),\n\t}))\n\treturn &S3Client{\n\t\ts3Client: s3Client,\n\t}\n}", "func (b *AmazonBucketProvider) EnsureBucketIsCreated(bucketURL string) error {\n\tsvc, err := b.s3()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.Parse(bucketURL)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse bucket name from %s\", bucketURL)\n\t}\n\tbucketName := u.Host\n\n\t// Check if bucket exists already\n\t_, err = svc.HeadBucket(&s3.HeadBucketInput{Bucket: aws.String(bucketName)})\n\tif err == nil {\n\t\treturn nil // bucket already exists\n\t}\n\taerr, ok := err.(awserr.Error)\n\tif !ok || aerr.Code() != s3.ErrCodeNoSuchBucket {\n\t\treturn errors.Wrapf(err, \"failed to check if %s bucket exists already\", bucketName)\n\t}\n\n\tinfoBucketURL := util.ColorInfo(bucketURL)\n\tlog.Logger().Infof(\"The bucket %s does not exist so lets create it\", infoBucketURL)\n\t_, err = svc.CreateBucket(&s3.CreateBucketInput{\n\t\tBucket: aws.String(bucketName),\n\t\tCreateBucketConfiguration: &s3.CreateBucketConfiguration{\n\t\t\tLocationConstraint: aws.String(b.Requirements.Cluster.Region),\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"there was a problem creating the bucket %s in the AWS\", bucketName)\n\t}\n\treturn nil\n}", "func (swagger *MgwSwagger) Validate() error {\n\tif (swagger.EndpointImplementationType != constants.MockedOASEndpointType) &&\n\t\t(swagger.EndpointType != constants.AwsLambda) {\n\t\tif (swagger.productionEndpoints == nil || len(swagger.productionEndpoints.Endpoints) == 0) &&\n\t\t\t(swagger.sandboxEndpoints == nil || len(swagger.sandboxEndpoints.Endpoints) == 0) {\n\n\t\t\tlogger.LoggerOasparser.Errorf(\"No Endpoints are provided for the API %s:%s\",\n\t\t\t\tswagger.title, swagger.version)\n\t\t\treturn errors.New(\"no endpoints are provided for the API\")\n\t\t}\n\t\terr := swagger.productionEndpoints.validateEndpointCluster(\"API level production\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\t\terr = swagger.sandboxEndpoints.validateEndpointCluster(\"API level sandbox\")\n\t\tif err != nil {\n\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\tswagger.title, swagger.version, err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, res := range swagger.resources {\n\t\t\terr := res.productionEndpoints.validateEndpointCluster(\"Resource level production\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the production endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = res.sandboxEndpoints.validateEndpointCluster(\"Resource level sandbox\")\n\t\t\tif err != nil {\n\t\t\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the sandbox endpoints of the API %s:%s - %v\",\n\t\t\t\t\tswagger.title, swagger.version, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\terr := swagger.validateBasePath()\n\tif err != nil {\n\t\tlogger.LoggerOasparser.Errorf(\"Error while parsing the API %s:%s - %v\", swagger.title, swagger.version, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func isVirtualHostStyle(hostURL string) bool {\n\tmatchS3, _ := filepath.Match(\"*.s3*.amazonaws.com\", hostURL)\n\tmatchGoogle, _ := filepath.Match(\"*.storage.googleapis.com\", hostURL)\n\treturn matchS3 || matchGoogle\n}", "func CheckRequestWithAwsV4(req *http.Request, key *Key, region, name string) (a *Authorization, sp *SignProcess, err error) {\n\tif a, err = NewAuthorization(req); err != nil {\n\t\treturn\n\t}\n\n\tvar t time.Time\n\tif t, err = a.Check(req, region, name); err != nil {\n\t\treturn\n\t}\n\n\tsp = new(SignProcess)\n\tsp.Key = key.Sign(t, region, name)\n\n\twriteStringToSign(t, req, a, sp, true, region, name)\n\tresult := hex.EncodeToString(sp.AllSHA256)\n\n\tif a.Signature != result {\n\t\tfmt.Println(sp)\n\t\terr = fmt.Errorf(\"awsv4 check faild. expected: %s, got: %s\", a.Signature, result)\n\t\treturn\n\t}\n\n\treturn\n}", "func (m *SdxCloudStorageRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdls(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdlsGen2(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEfs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFileSystemType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGcs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateS3(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateWasb(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}" ]
[ "0.6886191", "0.6830591", "0.64635575", "0.63935846", "0.6295366", "0.60866344", "0.59829074", "0.59396464", "0.586039", "0.58246577", "0.57538086", "0.5697277", "0.56723154", "0.56673247", "0.5654518", "0.5607397", "0.5597227", "0.55766237", "0.5466453", "0.54385525", "0.54135525", "0.53996015", "0.5389323", "0.5370809", "0.5369082", "0.53669626", "0.53493786", "0.5337392", "0.5272083", "0.52585185", "0.5252992", "0.52090687", "0.5189217", "0.5186196", "0.5179823", "0.5170607", "0.5142931", "0.5138524", "0.5112781", "0.51042247", "0.50930375", "0.50548065", "0.5052943", "0.50452423", "0.5024157", "0.50237143", "0.502206", "0.5020918", "0.5014656", "0.50128543", "0.5007258", "0.5000404", "0.49997863", "0.49994618", "0.4990442", "0.49834186", "0.49802732", "0.49769795", "0.49747616", "0.49728194", "0.49539775", "0.49492276", "0.49298072", "0.4929649", "0.4919106", "0.4911213", "0.49038512", "0.49021494", "0.4899677", "0.4897572", "0.48917487", "0.4889551", "0.48796213", "0.48774293", "0.486795", "0.48648006", "0.4859727", "0.4836708", "0.4833441", "0.48328406", "0.48293906", "0.4825594", "0.48166174", "0.48156187", "0.48152602", "0.4815036", "0.48148233", "0.48133713", "0.48071346", "0.48038396", "0.4802822", "0.48017082", "0.4794501", "0.47942895", "0.4792878", "0.47686064", "0.4765956", "0.4759404", "0.47581738", "0.4738625" ]
0.7837457
0
/ Execute executes the request
func (a *AmazonConnectionsApiService) ValidateS3EndpointExecute(r ApiValidateS3EndpointRequest) (CloudSubnetS3EndpointValidationResult, *_nethttp.Response, error) { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue CloudSubnetS3EndpointValidationResult ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AmazonConnectionsApiService.ValidateS3Endpoint") if err != nil { return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} } localVarPath := localBasePath + "/api/v1/amazonConnections/{amazonConnectionId}/validateS3endpoint" localVarPath = strings.Replace(localVarPath, "{"+"amazonConnectionId"+"}", _neturl.PathEscape(parameterToString(r.amazonConnectionId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} localVarFormParams := _neturl.Values{} if r.subnetId == nil { return localVarReturnValue, nil, reportError("subnetId is required and must be specified") } if r.xApiVersion == nil { return localVarReturnValue, nil, reportError("xApiVersion is required and must be specified") } localVarQueryParams.Add("subnetId", parameterToString(*r.subnetId, "")) // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["x-api-version"] = parameterToString(*r.xApiVersion, "") if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { if apiKey, ok := auth["Bearer"]; ok { var key string if apiKey.Prefix != "" { key = apiKey.Prefix + " " + apiKey.Key } else { key = apiKey.Key } localVarHeaderParams["Authorization"] = key } } } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= 300 { newErr := GenericOpenAPIError{ body: localVarBody, error: localVarHTTPResponse.Status, } if localVarHTTPResponse.StatusCode == 400 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 401 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == 500 { var v Error err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v } return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Request) Execute() (*Response, error) {\n\treturn r.sendRequest()\n}", "func ExecuteRequest(req *http.Request, result interface{}) error {\n\tclient := http.Client{}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error executing request call\")\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tout, err := ioutil.ReadAll(response.Body)\n\tif response.StatusCode == http.StatusUnauthorized {\n\t\tlog.Println(\"DOes not have permission to perform that action\")\n\t\treturn types.UnAuthorizedScope\n\t}\n\terr = json.NewDecoder(bytes.NewReader(out)).Decode(result)\n\tif err != nil {\n\t\tlog.Println(\"Error deserializing body in JSON Decoder\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *client) Execute(relativeURL string, params map[string]string) (*http.Response, error) {\n\tparams[\"appkey\"] = c.appKey\n\tparams[\"sid\"] = c.sid\n\tparams[\"timestamp\"] = fmt.Sprint(time.Now().Unix())\n\tparams[\"sign\"] = signRequest(params, c.appSecret)\n\n\treturn c.post(c.baseURL+relativeURL, params)\n}", "func Execute(method string, url string, bearer string) (resp *http.Response, err error) {\n\n\t// Create a new request using http\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// add authorization header to the req\n\treq.Header.Add(\"Authorization\", bearer)\n\n\t// Send req using http Client\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t}\n\tclient := &http.Client{Transport: transCfg}\n\tresp, err = client.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func (c *Client) Execute(r Request, data interface{}) error {\n\tpayload, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", c.Endpoint, bytes.NewBuffer(payload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range c.Headers {\n\t\treq.Header.Set(k, v)\n\t}\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tvar response Response\n\terr = json.NewDecoder(res.Body).Decode(&response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Data != nil {\n\t\terr = json.Unmarshal(*response.Data, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif response.Errors != nil {\n\t\tvar errors Errors\n\t\terr = json.Unmarshal(*response.Errors, &errors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (c *MakeRequestController) Execute() {\n\tmakeRequestData := c.AppCtx.GetMDR()\n\tprefix := \"[\" + strconv.Itoa(rand.Intn(100)) + \"] \"\n\n\t// Get current context to replace all variables\n\t_, currentContext := c.View.GetContext()\n\tcurrentContextValues := c.AppCtx.GetOutput().Context.GetAllKeyValue(currentContext)\n\n\tURL := types.URL(c.View.GetURL()).\n\t\tReplaceContext(makeRequestData.MapRequestHeaderKeyValue).\n\t\tReplaceContext(currentContextValues)\n\n\tmethod := makeRequestData.Method\n\tcontentType := makeRequestData.ContentType\n\tbody := []byte(makeRequestData.Body)\n\thttpHeaderValues := makeRequestData.GetHTTPHeaderValues().ReplaceContext(currentContextValues)\n\n\tHTTPClient, error := httpclient.Call(method, URL, contentType, body, httpHeaderValues, c.Action.DisplayErrorRequest)\n\tif error != nil {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\t\tc.AppCtx.PrintError(prefix + fmt.Sprint(error))\n\n\t\tc.Action.DisplayErrorRequest(fmt.Sprint(error), \"error\")\n\t} else {\n\t\tc.AppCtx.PrintInfo(prefix + makeRequestData.ToLog(URL))\n\n\t\tresponse := fmt.Sprintf(\"%+s\", HTTPClient.Body)\n\t\tif logRequestOn {\n\t\t\tc.AppCtx.PrintInfo(prefix + response)\n\t\t}\n\n\t\tc.Action.DisplayResponse(HTTPClient, response)\n\t}\n}", "func (g *HTTPGateway) Execute(req *retryablehttp.Request) ([]byte, error) {\n\tif g.Profile.AWS != nil {\n\t\t//sign request\n\t\tif err := signer.SignRequest(req, *g.Profile.AWS, signer.GetV4Signer); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tresponse, err := g.Client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := response.Body.Close()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\tif err = g.isValidResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ioutil.ReadAll(response.Body)\n}", "func (crawl *Crawl) Execute(req *Request) (resp *Response, err error) {\n\t// Make request\n\tresp, err = crawl.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If request.Raw is not true - parse html\n\tif !req.Raw {\n\t\terr = resp.ParseHTML()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set request context if empty\n\tif req.Context == nil {\n\t\treq.Context = context.Background()\n\t}\n\n\t// ctx = context.WithValue(ctx, \"crawl\", crawl)\n\t// ctx = context.WithValue(ctx, \"response\", resp)\n\n\t// Run handlers\n\tfor _, cb := range req.Callbacks {\n\t\tif handler := crawl.GetHandler(cb); handler != nil {\n\t\t\terr = handler(req.Context, crawl, resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warningf(\"Handler %v was not found\", cb)\n\t\t}\n\t}\n\n\tlog.V(2).Infof(\"%s %s %s - %v\", req.GetMethod(), resp.GetStatus(), resp.GetURL(), req.Callbacks)\n\n\treturn\n}", "func (a *ApiExecutor) Execute(request *Request) (Result, error) {\n\tmethod := a.Methods[request.MethodName]\n\tif method.IsEmpty() {\n\t\tmsg := fmt.Sprintf(\"Method '%s' was not recognized by executor\", request.MethodName)\n\t\tlog.Printf(\"[ERROR] \" + msg)\n\t\treturn NewResultMessage(http.StatusBadRequest, msg), errors.New(msg)\n\t}\n\n\tok, err := checkToken(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"Provided token is not valid, or expired. Please provide, valid token or authorize with 'auth'\"), nil\n\t}\n\n\tok, err = validateParams(method, request.Params)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusBadRequest, \"Provided parameters are not valid\"), nil\n\t}\n\n\tok, err = checkPermissions(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusBadRequest, err.Error()), err\n\t}\n\tif !ok {\n\t\treturn NewResultMessage(http.StatusForbidden, \"No permissions to perform operation '\" + request.MethodName + \"'\"), nil\n\t}\n\n\tresult, err := a.executeRequest(request)\n\tif err != nil {\n\t\treturn NewResultMessage(http.StatusInternalServerError, err.Error()), err\n\t}\n\treturn result, err\n}", "func (c clientType) execute(method, path string, body interface{}) (*resty.Response, error) {\n\treq := c.rest.R()\n\n\treq.SetBody(body)\n\n\tresp, err := req.Execute(method, path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t// fmt.Println(\"URL:\", resp.Request.URL)\n\treturn resp, nil\n}", "func (h HTTPAction) Execute(resultsChannel chan reporter.SampleReqResult, sessionMap map[string]string, vucontext *config.VUContext, vulog *log.Entry, playbook *config.TestDef) bool {\n\tvulog.Data[\"action\"] = h.Title\n\treturn DoHTTPRequest(h, resultsChannel, sessionMap, vucontext, vulog, playbook)\n}", "func (a *ApiExecutor) executeRequest(req *Request) (Result, error) {\n\tvar fsm *simple_fsm.Fsm\n\tstr := a.StructureMap[req.MethodName]\n\tfsm = simple_fsm.NewFsm(str)\n\tfsm.SetInput(\"methodName\", req.MethodName)\n\tfsm.SetInput(\"start_date\", time.Now())\n\tfsm.SetInput(\"failed\", false)\n\tfor k, v := range req.Params {\n\t\tfsm.SetInput(k, v)\n\t}\n\texecRes, err := fsm.Run()\n\tprintFsmDump(fsm)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error occured during flow execution: %v\", err)\n\t}\n\tlog.Printf(\"Exec result %v\", execRes)\n\treturn NewResultFrom(execRes), nil\n}", "func (c *Client) ExecuteRequest(req *http.Request, v interface{}, x interface{}) error {\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Do: \" + err.Error())\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.Read: \" + err.Error())\n\t}\n\n\tif v != nil && res.StatusCode == 200 {\n\t\tif err = json.Unmarshal(resBody, v); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalOK: \" + err.Error())\n\t\t}\n\t}\n\n\tif x != nil && res.StatusCode != 200 {\n\t\tif err = json.Unmarshal(resBody, x); err != nil {\n\t\t\treturn errors.New(\"sangu-bca.client.ExecuteRequest.UnmarshalNotOK: \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tt *TestCase) Execute(t *testing.T, fn echo.HandlerFunc) {\n\treq := tt.Request.Request()\n\trec, err := Do(fn, req, tt.Request.URLParams)\n\tif tt.ExpectedError != \"\" {\n\t\trequire.EqualError(t, err, tt.ExpectedError)\n\t} else {\n\t\trequire.NoError(t, err)\n\t\tEqualResp(t, tt.ExpectedResponse, rec)\n\t}\n}", "func (c *Executor) ExecuteRequest(request *Request) (*http.Response, error) {\n\tfollowRedirects := request.followRedirects\n\treq, err := c.newHTTPRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the request to the remote API\n\tr, err := c.do(req, followRedirects)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// it's possible the access token expired and the oauth subsystem could not obtain a new one because the\n\t// refresh token is expired or revoked. Attempt to get a new refresh and access token and retry the request.\n\tif r.StatusCode == http.StatusUnauthorized {\n\t\t_ = r.Body.Close()\n\t\terr = c.reAuthenticate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr, err = c.do(req, followRedirects)\n\t}\n\n\treturn r, err\n}", "func (s *server) Execute(args ExecuteArgs, resp *string) error {\n\tr, err := s.impl.Execute(args)\n\t*resp = r\n\treturn err\n}", "func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {\n\turl := sc.PortalURL\n\tmethod := config.method\n\treqBody := config.reqBody\n\n\t// Set options, prioritizing options passed to the API calls.\n\topts := sc.Options\n\tif config.EndpointPath != \"\" {\n\t\topts.EndpointPath = config.EndpointPath\n\t}\n\tif config.APIKey != \"\" {\n\t\topts.APIKey = config.APIKey\n\t}\n\tif config.CustomUserAgent != \"\" {\n\t\topts.CustomUserAgent = config.CustomUserAgent\n\t}\n\tif config.customContentType != \"\" {\n\t\topts.customContentType = config.customContentType\n\t}\n\n\t// Make the URL.\n\turl = makeURL(url, opts.EndpointPath, config.extraPath, config.query)\n\n\t// Create the request.\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, fmt.Sprintf(\"could not create %v request\", method))\n\t}\n\tif opts.APIKey != \"\" {\n\t\treq.SetBasicAuth(\"\", opts.APIKey)\n\t}\n\tif opts.CustomUserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", opts.CustomUserAgent)\n\t}\n\tif opts.customContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opts.customContentType)\n\t}\n\n\t// Execute the request.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"could not execute request\")\n\t}\n\tif resp.StatusCode >= 400 {\n\t\treturn nil, errors.AddContext(makeResponseError(resp), \"error code received\")\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) execute(method string, path string, params interface{}, headers Headers, model interface{}) error {\n\n\t// init vars\n\tvar url = baseUrl + path\n\n\t// init an empty payload\n\tpayload := strings.NewReader(\"\")\n\n\t// check for params\n\tif params != nil {\n\n\t\t// marshal params\n\t\tb, err := json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// set payload with params\n\t\tpayload = strings.NewReader(string(b))\n\n\t}\n\n\t// set request\n\trequest, _ := http.NewRequest(method, url, payload)\n\trequest.Header.Add(\"Authorization\", c.BasicAuth)\n\trequest.Header.Add(\"accept\", \"application/json\")\n\trequest.Header.Add(\"content-type\", \"application/json\")\n\n\t// add extra headers\n\tif headers != nil {\n\t\tfor key, value := range headers {\n\t\t\trequest.Header.Add(key, value)\n\t\t}\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\t// read response\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// init zoop error response\n\ter := &ErrResponse{}\n\n\t// check for error message\n\tif err = json.Unmarshal(data, er); err == nil && er.ErrObject != nil {\n\t\treturn er.ErrObject\n\t}\n\n\t// parse data\n\treturn json.Unmarshal(data, model)\n\n}", "func (req *Request) ExecuteRequest(client *http.Client) datastructure.Response {\n\tvar response datastructure.Response\n\tvar start = time.Now()\n\tvar err error\n\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tlog.Debug(\"ExecuteRequest | Executing request ...\")\n\t//client := &http.Client{Transport: req.Tr, Timeout: req.Timeout}\n\treq.Tr.DisableKeepAlives = true\n\tclient.Transport = req.Tr\n\tclient.Timeout = req.Timeout\n\tlog.Debugf(\"Request: %+v\\n\", req.Req)\n\tlog.Debugf(\"Client: %+v\\n\", client)\n\n\t// If content length was not specified (only for POST) add an headers with the length of the request\n\tif req.Method == \"POST\" && req.Req.Header.Get(\"Content-Length\") == \"\" {\n\t\tcontentLength := strconv.FormatInt(req.Req.ContentLength, 10)\n\t\treq.Req.Header.Set(\"Content-Length\", contentLength)\n\t\tlog.Debug(\"ExecuteRequest | Setting Content-Length -> \", contentLength)\n\n\t}\n\tresp, err := client.Do(req.Req)\n\n\tif err != nil {\n\t\tlog.Error(\"Error executing request | ERR:\", err)\n\t\terr = errors.New(\"ERROR_SENDING_REQUEST -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tdefer resp.Body.Close()\n\tresponse.Headers = make(map[string]string, len(resp.Header))\n\tfor k, v := range resp.Header {\n\t\tresponse.Headers[k] = strings.Join(v, `,`)\n\t}\n\tresponse.Cookie = resp.Cookies()\n\n\t//log.Debug(\"ExecuteRequest | Request executed, reading response ...\")]\n\tbodyResp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = resp.Body.Close(); err != nil {\n\t\tlog.Println(\"Error during connection closing! \", err.Error())\n\t}\n\tif err != nil {\n\t\tlog.Error(\"Unable to read response! | Err: \", err)\n\t\terr = errors.New(\"ERROR_READING_RESPONSE -> \" + err.Error())\n\t\tresponse.Error = err\n\t\treturn response\n\t}\n\n\tresponse.Body = bodyResp\n\tresponse.StatusCode = resp.StatusCode\n\tresponse.Error = nil\n\telapsed := time.Since(start)\n\tresponse.Time = elapsed\n\tresponse.Response = resp\n\tlog.Debug(\"ExecuteRequest | Elapsed -> \", elapsed, \" | STOP!\")\n\treturn response\n}", "func executeRequest(method string, url string, body *bytes.Buffer, asAdmin bool) *http.Response {\n\tconfig, err := loadConfig(testConfigPath)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to load config %s\", err))\n\t}\n\n\th := handler{\n\t\tlogger: log.NewNopLogger(),\n\t\tnewCredentialsProvider: newMockProvider,\n\t\targo: mockWorkflowSvc{},\n\t\tconfig: config,\n\t\tgitClient: newMockGitClient(),\n\t\tnewCredsProviderSvc: mockCredsProvSvc,\n\t\tenv: env.Vars{\n\t\t\tAdminSecret: testPassword,\n\t\t},\n\t\tdbClient: newMockDB(),\n\t}\n\n\tvar router = setupRouter(h)\n\treq, _ := http.NewRequest(method, url, body)\n\tauthorizationHeader := \"vault:user:\" + testPassword\n\tif asAdmin {\n\t\tauthorizationHeader = \"vault:admin:\" + testPassword\n\t}\n\treq.Header.Add(\"Authorization\", authorizationHeader)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\treturn w.Result()\n}", "func (r *Request) Execute(method, url string) (*Response, error) {\n\tvar addrs []*net.SRV\n\tvar resp *Response\n\tvar err error\n\n\tif r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) {\n\t\t// No OnError hook here since this is a request validation error\n\t\treturn nil, fmt.Errorf(\"multipart content is not allowed in HTTP verb [%v]\", method)\n\t}\n\n\tif r.SRV != nil {\n\t\t_, addrs, err = net.LookupSRV(r.SRV.Service, \"tcp\", r.SRV.Domain)\n\t\tif err != nil {\n\t\t\tr.client.onErrorHooks(r, nil, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tr.Method = method\n\tr.URL = r.selectAddr(addrs, url, 0)\n\n\tif r.client.RetryCount == 0 {\n\t\tr.Attempt = 1\n\t\tresp, err = r.client.execute(r)\n\t\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\t\treturn resp, unwrapNoRetryErr(err)\n\t}\n\n\terr = Backoff(\n\t\tfunc() (*Response, error) {\n\t\t\tr.Attempt++\n\n\t\t\tr.URL = r.selectAddr(addrs, url, r.Attempt)\n\n\t\t\tresp, err = r.client.execute(r)\n\t\t\tif err != nil {\n\t\t\t\tr.client.log.Errorf(\"%v, Attempt %v\", err, r.Attempt)\n\t\t\t}\n\n\t\t\treturn resp, err\n\t\t},\n\t\tRetries(r.client.RetryCount),\n\t\tWaitTime(r.client.RetryWaitTime),\n\t\tMaxWaitTime(r.client.RetryMaxWaitTime),\n\t\tRetryConditions(r.client.RetryConditions),\n\t)\n\n\tr.client.onErrorHooks(r, resp, unwrapNoRetryErr(err))\n\n\treturn resp, unwrapNoRetryErr(err)\n}", "func (exe *HTTPRemote) Execute(param map[string]interface{}) (map[string]interface{}, error) {\n\texeID, _ := util.GetStringParam(param, \"id\")\n\n\tparamJSON, err := json.Marshal(param)\n\tif err != nil {\n\t\texe.Errorf(\"Generate json param error: %s\", err)\n\t\treturn nil, errors.New(\"Generate json param error\")\n\t}\n\n\tsignatureBytes := util.CalculateMAC(paramJSON, []byte(exe.Secret))\n\tsignature := hex.EncodeToString(signatureBytes)\n\n\treq, err := http.NewRequest(\"POST\", exe.Host, bytes.NewBuffer(paramJSON))\n\tif err != nil {\n\t\texe.Errorf(\"Create request failed: %s\", err)\n\t\treturn nil, errors.New(\"Create request failed\")\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Herald-Signature\", signature)\n\n\texe.Infof(\"Start to connect to: %s\", exe.Host)\n\n\tclient := &http.Client{\n\t\tTimeout: exe.Timeout,\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\texe.Errorf(\"Remote execution request failed: %s\", err)\n\t\treturn nil, errors.New(\"Remote execution request failed\")\n\t}\n\tdefer resp.Body.Close()\n\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\n\texe.Debugf(\"Response status: %s\", resp.Status)\n\texe.Debugf(\"Response content type: %s\", contentType)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\texe.Errorf(\"Http status not OK: %s\", resp.Status)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\texe.Errorf(\"Remote error: %s\", string(body))\n\t\treturn nil, fmt.Errorf(`Http status %d: \"%s\"`, resp.StatusCode, string(body))\n\t}\n\n\tmediaType, mtParams, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\texe.Errorf(\"Parse media type error: %s\", err)\n\t\treturn nil, errors.New(\"Parse media type error\")\n\t}\n\n\tresult := make(map[string]interface{})\n\n\texe.Debugf(\"Parsed context type: %s\", mediaType)\n\tresult[\"context_type\"] = mediaType\n\n\tif mediaType == \"application/json\" {\n\t\texe.processJSONPart(result, resp.Body)\n\t} else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\texe.processMultiPart(result, resp.Body, mtParams[\"boundary\"], exeID)\n\t} else {\n\t\texe.Errorf(\"Unknown media type: %s\", mediaType)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\tresult[\"response\"] = string(body)\n\t\treturn result, errors.New(\"Unknown media type\")\n\t}\n\n\texitCodeFloat, err := util.GetFloatParam(result, \"exit_code\")\n\texitCode := int(exitCodeFloat)\n\tif exitCode != 0 {\n\t\treturn result, fmt.Errorf(\"Command failed with code %d\", exitCode)\n\t}\n\n\treturn result, nil\n}", "func (c *carHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"CarsHandler actived\")\n\tcontentType := r.Header.Get(\"Content-type\")\n\tif contentType != \"application/json\" {\n\t\tlog.Println(fmt.Errorf(\"Content Type is not valid\"))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar input []usecase.CarInput\n\tdefer r.Body.Close()\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.validate(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := c.CarUsecase.PutCars(input); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Println(fmt.Sprintf(\"Car created\"))\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func (runtime *Runtime) Execute(document *ast.Document, operationName string, variableValues map[string]interface{}) *Response {\n\trsp := &Response{}\n\n\t// TODO\n\t// err = validateDocument(document)\n\t// if err != nil {\n\t// \trsp.Errors = append(rsp.Errors, err)\n\t// \treturn rsp\n\t// }\n\n\toperation, err := runtime.getOperation(document, operationName)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\n\tcoercedVarVals, err := runtime.coerceVariableValues(operation, variableValues)\n\tif err != nil {\n\t\trsp.Errors = append(rsp.Errors, err)\n\t\treturn rsp\n\t}\n\treturn runtime.executeRequest(operation, coercedVarVals)\n}", "func (c Client) executeRequest(req *http.Request) ([]byte, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tbytes := buf.Bytes()\n\tif resp.StatusCode != 200 {\n\t\treturn bytes, fmt.Errorf(\"%s %s failed. Response code was %s\", req.Method, req.URL, resp.Status)\n\t}\n\treturn bytes, nil\n}", "func (s *mongoRequest) Execute(msession *mgo.Session, r *http.Request) (interface{}, error) {\n\t// FIXME add session to mongoRequest struct?\n\t// TODO test copy/clone/new against consistency modes\n\terr := s.Decode(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsession := msession.Copy()\n\tdefer session.Close()\n\tcoll := session.DB(s.Database).C(s.Collection)\n\tquery := new(mgo.Query)\n\tbakeAction(&query, s, coll)\n\tbakeSubActions(&query, s, coll)\n\tjdata, err := executeQuery(query, s, coll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jdata, nil\n}", "func (c *HTTPClient) exec(name string, params map[string]string, body io.Reader) (Response, error) {\n\turl := *c.url\n\turl.Path = path.Join(url.Path, name)\n\tif len(params) != 0 {\n\t\tquery := url.Query()\n\t\tfor k, v := range params {\n\t\t\tquery.Add(k, v)\n\t\t}\n\t\turl.RawQuery = query.Encode()\n\t}\n\tif body == nil {\n\t\tresp, err := c.client.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, NewError(NetworkError, \"http.Client.Get failed.\", map[string]interface{}{\n\t\t\t\t\"url\": url.String(),\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\treturn newHTTPResponse(resp)\n\t}\n\tresp, err := c.client.Post(url.String(), \"application/json\", body)\n\tif err != nil {\n\t\treturn nil, NewError(NetworkError, \"http.Client.Post failed.\", map[string]interface{}{\n\t\t\t\"url\": url.String(),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\treturn newHTTPResponse(resp)\n}", "func (w *Worker) Execute(req *http.Request, h func(resp *http.Response, err error) error) (err error) {\n\n\tj := &job{req, h, make(chan error)}\n\tw.jobQuene <- j\n\treturn <-j.end\n\n}", "func Execute(\n\tctx context.Context,\n\thandler Handler,\n\tabortHandler AbortHandler,\n\trequest interface{}) Awaiter {\n\ttask := &task{\n\t\trequest: request,\n\t\thandler: handler,\n\t\tabortHandler: abortHandler,\n\t\tresultQ: make(chan Response, 1),\n\t\trunning: true,\n\t}\n\tgo task.run(ctx) // run handler asynchronously\n\treturn task\n}", "func (c *Client) Execute(ctx context.Context, req *http.Request, r interface{}) (*http.Response, error) {\n\treq = req.WithContext(ctx)\n\tdebugReq(req)\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\t// If we got an error, and the context has been canceled,\n\t\t// the context's error is probably more useful.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t// If the error type is *url.Error, sanitize its URL before returning.\n\t\tif e, ok := err.(*url.Error); ok {\n\t\t\tif url, err := url.Parse(e.URL); err == nil {\n\t\t\t\te.URL = sanitizeURL(url).String()\n\t\t\t\treturn nil, e\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn nil, fmt.Errorf(\"Request to %s responded with status %d\", req.URL, resp.StatusCode)\n\t}\n\n\tif r != nil {\n\t\tif w, ok := r.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\tdecErr := json.NewDecoder(resp.Body).Decode(r)\n\t\t\tif decErr == io.EOF {\n\t\t\t\tdecErr = nil // ignore EOF errors caused by empty response body\n\t\t\t}\n\t\t\tif decErr != nil {\n\t\t\t\terr = decErr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (vk VK) Execute(Code string) (response []byte, vkErr Error) {\n\tp := make(map[string]string)\n\tp[\"code\"] = Code\n\tresponse, vkErr = vk.Request(\"execute\", p)\n\n\treturn\n}", "func execRequest(engine *req.Engine, method, url string, data interface{}) []error {\n\tif engine == nil {\n\t\treturn errEngineIsNil\n\t}\n\n\tif engine.UserAgent == \"\" {\n\t\tengine.SetUserAgent(\"go-ek-librato\", VERSION)\n\t}\n\n\trequest := req.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\n\t\tBasicAuthUsername: Mail,\n\t\tBasicAuthPassword: Token,\n\n\t\tContentType: req.CONTENT_TYPE_JSON,\n\n\t\tClose: true,\n\t}\n\n\tif data != nil {\n\t\trequest.Body = data\n\t}\n\n\tresp, err := engine.Do(request)\n\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\tif resp.StatusCode > 299 || resp.StatusCode == 0 {\n\t\treturn extractErrors(resp.String())\n\t}\n\n\tresp.Discard()\n\n\treturn nil\n}", "func (client *Client) ExecuteRequest(destinationNumber string, messageContent string, messageChannel chan Message) (Message, error) {\n\t// Returns you a message Object back\n\n\tvar message Message\n\n\tmessageDataBuffer := client.NewMessage(messageContent, destinationNumber)\n\n\trequest, err := client.NewRequest(messageDataBuffer)\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error concerning HTTP credentials ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tresponse, err := client.RequestExecutor.Do(request)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error executing the HTTP request ... here is the error %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tif response.StatusCode >= 300 {\n\t\terrStr := fmt.Sprintf(\"Status Code : %v\", response.StatusCode)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tdecoder := json.NewDecoder(response.Body)\n\terr = decoder.Decode(&message)\n\n\tif err != nil {\n\t\terrStr := fmt.Sprintf(\"Error decoding data into Message Object ... here is the data %v\", err)\n\t\treturn Message{}, &errorString{errStr}\n\t}\n\n\tmessageChannel <- message\n\treturn message, nil\n}", "func ExecuteRequest(testServer *server.HTTPServer, req *http.Request, config *server.Configuration) *httptest.ResponseRecorder {\n\trouter := testServer.Initialize()\n\n\trr := httptest.NewRecorder()\n\trouter.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (rt *rtuTransport) ExecuteRequest(req *pdu) (res *pdu, err error) {\n\t// set an i/o deadline on the link\n\terr\t= rt.link.SetDeadline(time.Now().Add(rt.timeout))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// build an RTU ADU out of the request object and\n\t// send the final ADU+CRC on the wire\n\t_, err\t= rt.link.Write(rt.assembleRTUFrame(req))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// observe inter-frame delays\n\ttime.Sleep(rt.interFrameDelay())\n\n\t// read the response back from the wire\n\tres, err = rt.readRTUFrame()\n\n\treturn\n}", "func (_e *handler_Expecter) Execute(req interface{}, s interface{}) *handler_Execute_Call {\n\treturn &handler_Execute_Call{Call: _e.mock.On(\"Execute\", req, s)}\n}", "func (r Search) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Search query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func execRequest(_ int, p *gop.Context) {\n\tret, ret1 := cgi.Request()\n\tp.Ret(0, ret, ret1)\n}", "func (job *JOB) Execute(ctx context.Context) error {\n\t//Host timezone set Asia/Singapore\n\treq, err := httpclient.MakeRequest(\n\t\thttpclient.Method(\"GET\"),\n\t\thttpclient.URL(\n\t\t\thttpclient.Schema(\"https\"),\n\t\t\thttpclient.Host(\"api.data.gov.sg\"),\n\t\t\thttpclient.URI(\"/v1/transport/carpark-availability\"),\n\t\t),\n\t\thttpclient.Query(\"date_time\", time.Now().Format(time.RFC3339)),\n\t)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"make request\")\n\t}\n\treturn job.Client.Execute(ctx, req, job)\n}", "func (test *RestTest) Execute(testcase *TestCase, ctx *TestContext) error {\n\ttestData := testcase.Data\n\n\tswitch testcase.Method {\n\tcase METHOD_CREATE_SERVICE, METHOD_CREATE_POLICY, METHOD_CREATE_ROLEPOLICY,\n\t\tMETHOD_IS_ALLOWED, METHOD_GET_GRANTED_ROLES, METHOD_GET_GRANTED_PERMISSIONS:\n\t\treturn test.Client.Post(testData)\n\tcase METHOD_GET_SERVICE, METHOD_QUERY_SERVICE, METHOD_GET_POLICY, METHOD_QUERY_POLICY,\n\t\tMETHOD_GET_ROLEPOLICY, METHOD_QUERY_ROLEPOLICY:\n\t\treturn test.Client.Get(testData)\n\tcase METHOD_DELETE_SERVICE, METHOD_DELETE_POLICY, METHOD_DELETE_ROLEPOLICY:\n\t\treturn test.Client.Delete(testData)\n\tdefault:\n\t\treturn errors.New(ERROR_SPEEDLE_NOT_SUPPORTED)\n\t}\n}", "func (c *HTTPClient) Exec(cmd string, body io.Reader) (Response, error) {\n\tcommand, err := ParseCommand(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommand.SetBody(body)\n\treturn c.Query(command)\n}", "func (s *executionServer) Execute(\n\treq *remoteexecution.ExecuteRequest, execServer remoteexecution.Execution_ExecuteServer) error {\n\tlog.Debugf(\"Received Execute request: %s\", req)\n\n\tif !s.IsInitialized() {\n\t\treturn status.Error(codes.Internal, \"Server not initialized\")\n\t}\n\n\tvar err error = nil\n\n\t// Record metrics based on final error condition\n\tdefer func() {\n\t\tif err == nil {\n\t\t\ts.stat.Counter(stats.BzExecSuccessCounter).Inc(1)\n\t\t} else {\n\t\t\ts.stat.Counter(stats.BzExecFailureCounter).Inc(1)\n\t\t}\n\t}()\n\tdefer s.stat.Latency(stats.BzExecLatency_ms).Time().Stop()\n\n\t// Transform ExecuteRequest into Scoot Job, validate and schedule\n\t// If we encounter an error here, assume it was due to an InvalidArgument\n\tjob, err := execReqToScoot(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to convert request to Scoot JobDefinition: %s\", err)\n\t\treturn status.Error(codes.InvalidArgument, fmt.Sprintf(\"Error converting request to internal definition: %s\", err))\n\t}\n\n\terr = domain.ValidateJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Scoot Job generated from request invalid: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Internal job definition invalid: %s\", err))\n\t}\n\n\tid, err := s.scheduler.ScheduleJob(job)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to schedule Scoot job: %s\", err)\n\t\treturn status.Error(codes.Internal, fmt.Sprintf(\"Failed to schedule Scoot job: %s\", err))\n\t}\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"jobID\": id,\n\t\t}).Info(\"Scheduled execute request as Scoot job\")\n\n\teom := &remoteexecution.ExecuteOperationMetadata{\n\t\tStage: remoteexecution.ExecuteOperationMetadata_QUEUED,\n\t\tActionDigest: req.GetActionDigest(),\n\t}\n\n\t// Marshal ExecuteActionMetadata to protobuf.Any format\n\teomAsPBAny, err := marshalAny(eom)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\t// Include the response message in the longrunning operation message\n\top := &longrunning.Operation{\n\t\tName: id,\n\t\tMetadata: eomAsPBAny,\n\t\tDone: false,\n\t}\n\n\t// Send the initial operation on the exec server stream\n\terr = execServer.Send(op)\n\tif err != nil {\n\t\treturn status.Error(codes.Internal, err.Error())\n\t}\n\n\tlog.Debug(\"ExecuteRequest completed successfully\")\n\treturn nil\n}", "func (cb *Breaker) Execute(req func() (interface{}, error)) (interface{}, error) {\n\tgeneration, err := cb.beforeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\te := recover()\n\t\tif e != nil {\n\t\t\tcb.afterRequest(generation, false)\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\n\tresult, err := req()\n\tcb.afterRequest(generation, err == nil)\n\treturn result, err\n}", "func (r apiGetLoyaltyProgramsRequest) Execute() (InlineResponse20011, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20011\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPrograms\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20011\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *Client) Execute(command string) {\n\tclient.SendResponse(command)\n}", "func execute(fhandler *flowHandler, request []byte) ([]byte, error) {\n\tvar result []byte\n\tvar err error\n\n\tpipeline := fhandler.getPipeline()\n\n\tcurrentNode, _ := pipeline.GetCurrentNodeDag()\n\n\t// trace node - mark as start of node\n\tfhandler.tracer.startNodeSpan(currentNode.GetUniqueId(), fhandler.id)\n\n\t// Execute all operation\n\tfor _, operation := range currentNode.Operations() {\n\n\t\tswitch {\n\t\t// If function\n\t\tcase operation.Function != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing function `%s`\\n\",\n\t\t\t\tfhandler.id, operation.Function)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\tresult, err = executeFunction(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Function(%s), error: function execution failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.Function, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t// If callback\n\t\tcase operation.CallbackUrl != \"\":\n\t\t\tfmt.Printf(\"[Request `%s`] Executing callback `%s`\\n\",\n\t\t\t\tfhandler.id, operation.CallbackUrl)\n\t\t\tif result == nil {\n\t\t\t\terr = executeCallback(pipeline, operation, request)\n\t\t\t} else {\n\t\t\t\terr = executeCallback(pipeline, operation, result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), Callback(%s), error: callback failed, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), operation.CallbackUrl, err)\n\t\t\t\tif operation.FailureHandler != nil {\n\t\t\t\t\terr = operation.FailureHandler(err)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t// If modifier\n\t\tdefault:\n\t\t\tfmt.Printf(\"[Request `%s`] Executing modifier\\n\", fhandler.id)\n\t\t\tif result == nil {\n\t\t\t\tresult, err = operation.Mod(request)\n\t\t\t} else {\n\t\t\t\tresult, err = operation.Mod(result)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Node(%s), error: Failed at modifier, %v\",\n\t\t\t\t\tcurrentNode.GetUniqueId(), err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = []byte(\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"[Request `%s`] Completed execution of Node %s\\n\", fhandler.id, currentNode.GetUniqueId())\n\n\treturn result, nil\n}", "func (this Interceptor) Run(vars map[string]interface{}, next func()) {\n\turl := httper.V(vars).GetRequest().URL.Path\n\texec := this[url]\n\tif exec != nil {\n\t\texec.Run(vars, next)\n\t} else {\n\t\tnext()\n\t}\n}", "func (c *Client) execute(req *Request) (string, bool, error) {\n\tdefer timeTrack(time.Now(), \"Executing\")\n\n\tres := &Response{}\n\n\tswitch req.method {\n\n\tcase \"websocket\":\n\t\trequestID++\n\t\treq.body.Set(requestID, \"id\")\n\n\t\terr := c.wsClient.WriteJSON(req.body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\\n\", err)\n\t\t}\n\n\t\t_, message, _ := c.wsClient.ReadMessage()\n\t\tif len(string(message)) > 0 {\n\t\t\tres.Parse(req, message)\n\t\t\treturn string(message), true, nil\n\t\t}\n\n\t\treturn string(message), true, nil\n\n\tcase \"post\":\n\t\tif isNil(req.body) {\n\t\t\tresp, err := c.httpClient.R().Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t} else {\n\t\t\tresp, err := c.httpClient.R().SetBody(req.body).Post(req.urlPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t\t}\n\t\t\tif resp.StatusCode() != 200 && resp.StatusCode() != 201 {\n\t\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t\t}\n\t\t\tres.OK = true\n\t\t\tres.Parse(req, resp.Body())\n\t\t}\n\t\treturn \"\", true, nil\n\n\tcase \"get\":\n\t\tresp, err := c.httpClient.R().Get(req.urlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"ERROR >> %s\", err)\n\t\t}\n\t\tif resp.StatusCode() != 200 {\n\t\t\tlog.Fatalf(\"PARSE ERROR HERE >> %s\", err)\n\t\t}\n\t\tres.OK = true\n\t\tres.Parse(req, resp.Body())\n\n\t\treturn string(resp.Body()), true, nil\n\n\tdefault:\n\t\treturn \"\", false, errors.New(\"Something went wrong\")\n\t}\n}", "func (e *HTTPExecuter) ExecuteHTTP(p *progress.Progress, reqURL string) *Result {\n\t// verify if pipeline was requested\n\tif e.bulkHTTPRequest.Pipeline {\n\t\treturn e.ExecuteTurboHTTP(reqURL)\n\t}\n\n\t// verify if a basic race condition was requested\n\tif e.bulkHTTPRequest.Race && e.bulkHTTPRequest.RaceNumberRequests > 0 {\n\t\treturn e.ExecuteRaceRequest(reqURL)\n\t}\n\n\t// verify if parallel elaboration was requested\n\tif e.bulkHTTPRequest.Threads > 0 {\n\t\treturn e.ExecuteParallelHTTP(p, reqURL)\n\t}\n\n\tvar requestNumber int\n\n\tresult := &Result{\n\t\tMatches: make(map[string]interface{}),\n\t\tExtractions: make(map[string]interface{}),\n\t\thistoryData: make(map[string]interface{}),\n\t}\n\n\tdynamicvalues := make(map[string]interface{})\n\n\t// verify if the URL is already being processed\n\tif e.bulkHTTPRequest.HasGenerator(reqURL) {\n\t\treturn result\n\t}\n\n\tremaining := e.bulkHTTPRequest.GetRequestCount()\n\te.bulkHTTPRequest.CreateGenerator(reqURL)\n\n\tfor e.bulkHTTPRequest.Next(reqURL) {\n\t\trequestNumber++\n\t\tresult.Lock()\n\t\thttpRequest, err := e.bulkHTTPRequest.MakeHTTPRequest(reqURL, dynamicvalues, e.bulkHTTPRequest.Current(reqURL))\n\t\tpayloads, _ := e.bulkHTTPRequest.GetPayloadsValues(reqURL)\n\t\tresult.Unlock()\n\t\t// ignore the error due to the base request having null paylods\n\t\tif err == requests.ErrNoPayload {\n\t\t\t// pass through\n\t\t} else if err != nil {\n\t\t\tresult.Error = err\n\t\t\tp.Drop(remaining)\n\t\t} else {\n\t\t\te.ratelimiter.Take()\n\t\t\t// If the request was built correctly then execute it\n\t\t\tformat := \"%s_\" + strconv.Itoa(requestNumber)\n\t\t\terr = e.handleHTTP(reqURL, httpRequest, dynamicvalues, result, payloads, format)\n\t\t\tif err != nil {\n\t\t\t\tresult.Error = errors.Wrap(err, \"could not handle http request\")\n\t\t\t\tp.Drop(remaining)\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", err)\n\t\t\t} else {\n\t\t\t\te.traceLog.Request(e.template.ID, reqURL, \"http\", nil)\n\t\t\t}\n\t\t}\n\t\tp.Update()\n\n\t\t// Check if has to stop processing at first valid result\n\t\tif e.stopAtFirstMatch && result.GotResults {\n\t\t\tp.Drop(remaining)\n\t\t\tbreak\n\t\t}\n\n\t\t// move always forward with requests\n\t\te.bulkHTTPRequest.Increment(reqURL)\n\t\tremaining--\n\t}\n\tgologger.Verbosef(\"Sent for [%s] to %s\\n\", \"http-request\", e.template.ID, reqURL)\n\treturn result\n}", "func (r apiGetAllAccessLogsRequest) Execute() (InlineResponse20019, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20019\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAllAccessLogs\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/access_logs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.rangeStart == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeStart is required and must be specified\")\n\t}\n\n\tif r.rangeEnd == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"rangeEnd is required and must be specified\")\n\t}\n\n\tlocalVarQueryParams.Add(\"rangeStart\", parameterToString(*r.rangeStart, \"\"))\n\tlocalVarQueryParams.Add(\"rangeEnd\", parameterToString(*r.rangeEnd, \"\"))\n\tif r.path != nil {\n\t\tlocalVarQueryParams.Add(\"path\", parameterToString(*r.path, \"\"))\n\t}\n\tif r.method != nil {\n\t\tlocalVarQueryParams.Add(\"method\", parameterToString(*r.method, \"\"))\n\t}\n\tif r.status != nil {\n\t\tlocalVarQueryParams.Add(\"status\", parameterToString(*r.status, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20019\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (hh *HealthCheckHandler) Execute(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\tif uuid == \"\" {\n\t\thttp.Error(w, marshalError(\"invalid uuid\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tqueryParams := r.URL.Query()\n\ttimeout, err := time.ParseDuration(queryParams[\"timeout\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\thc, err := hh.db.Get(uuid)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// make a copy and run the healthcheck\n\ttry := &models.HealthCheck{\n\t\tID: hc.ID,\n\t\tEndpoint: hc.Endpoint,\n\t}\n\n\ttry = service.Run(try, timeout)\n\n\tb, err := json.Marshal(try)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func (e *Explorer) Execute(forWallet WalletType, address string) ([]byte, error) {\n\tif e.client == nil {\n\t\te.client = http.DefaultClient\n\t}\n\n\tresp, err := e.client.Get(fmt.Sprintf(e.getURI(forWallet), address))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuff, err := ioutil.ReadAll(resp.Body)\n\treturn buff, err\n}", "func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {\n\treturn executeCommand(method, url, data)\n}", "func Execute() *fire.Callback {\n\t// prepare matchers\n\tgetFilterMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyIDMatcher := fire.Except(fire.List | fire.Create | fire.CollectionAction)\n\tverifyModelMatcher := fire.Except(fire.Create | fire.CollectionAction)\n\tverifyCreateMatcher := fire.Only(fire.Create)\n\tverifyUpdateMatcher := fire.Only(fire.Update)\n\tgetFieldsAndPropsMatcher := fire.Except(fire.Delete | fire.CollectionAction | fire.ResourceAction)\n\n\t// prepare access tables\n\tgenericAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t\tfire.Delete: Delete,\n\t\tfire.ResourceAction: Find,\n\t}\n\treadAccess := map[fire.Operation]Access{\n\t\tfire.List: List,\n\t\tfire.Find: Find,\n\t\tfire.Create: Find,\n\t\tfire.Update: Find,\n\t}\n\twriteAccess := map[fire.Operation]Access{\n\t\tfire.Create: Create,\n\t\tfire.Update: Update,\n\t}\n\n\treturn fire.C(\"ash/Execute\", fire.Authorizer, fire.All(), func(ctx *fire.Context) error {\n\t\t// get policy\n\t\tpolicy, _ := ctx.Data[PolicyDataKey].(*Policy)\n\t\tif policy == nil {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// check access\n\t\taccess := genericAccess[ctx.Operation]\n\t\tif policy.Access&access != access {\n\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t}\n\n\t\t// apply filter if available\n\t\tif getFilterMatcher(ctx) && policy.GetFilter != nil {\n\t\t\tctx.Filters = append(ctx.Filters, policy.GetFilter(ctx))\n\t\t}\n\n\t\t// verify action access\n\t\tif ctx.Operation.Action() {\n\t\t\t// get action\n\t\t\taction := ctx.JSONAPIRequest.CollectionAction\n\t\t\tif ctx.Operation == fire.ResourceAction {\n\t\t\t\taction = ctx.JSONAPIRequest.ResourceAction\n\t\t\t}\n\n\t\t\t// check action\n\t\t\tif !policy.Actions[action] {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify ID if available\n\t\tif verifyIDMatcher(ctx) && policy.VerifyID != nil {\n\t\t\t// get access\n\t\t\taccess := policy.VerifyID(ctx, ctx.Selector[\"_id\"].(coal.ID))\n\n\t\t\t// check access\n\t\t\tif access&genericAccess[ctx.Operation] == 0 {\n\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t}\n\t\t}\n\n\t\t// verify model if available\n\t\tif verifyModelMatcher(ctx) && policy.VerifyModel != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyModel\", fire.Verifier, verifyModelMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// get required access\n\t\t\t\treqAccess := genericAccess[ctx.Operation]\n\n\t\t\t\t// check access\n\t\t\t\tif ctx.Operation == fire.List {\n\t\t\t\t\tfor _, model := range ctx.Models {\n\t\t\t\t\t\tif policy.VerifyModel(ctx, model)&reqAccess == 0 {\n\t\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif policy.VerifyModel(ctx, ctx.Model)&reqAccess == 0 {\n\t\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify create if available\n\t\tif verifyCreateMatcher(ctx) && policy.VerifyCreate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyCreate\", fire.Validator, verifyCreateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyCreate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// verify update if available\n\t\tif verifyUpdateMatcher(ctx) && policy.VerifyUpdate != nil {\n\t\t\tctx.Defer(fire.C(\"ash/Execute-VerifyUpdate\", fire.Validator, verifyUpdateMatcher, func(ctx *fire.Context) error {\n\t\t\t\t// check access\n\t\t\t\tif !policy.VerifyUpdate(ctx, ctx.Model) {\n\t\t\t\t\treturn fire.ErrAccessDenied.Wrap()\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t}\n\n\t\t// collect fields\n\t\treadableFields := policy.Fields.Collect(readAccess[ctx.Operation])\n\t\twritableFields := policy.Fields.Collect(writeAccess[ctx.Operation])\n\n\t\t// set intersections of fields\n\t\tctx.ReadableFields = stick.Intersect(ctx.ReadableFields, readableFields)\n\t\tctx.WritableFields = stick.Intersect(ctx.WritableFields, writableFields)\n\n\t\t// set fields getters if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetFields != nil {\n\t\t\tctx.GetReadableFields = func(model coal.Model) []string {\n\t\t\t\tif model == nil {\n\t\t\t\t\treturn readableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t\tctx.GetWritableFields = func(model coal.Model) []string {\n\t\t\t\tif ctx.Operation == fire.Create {\n\t\t\t\t\treturn writableFields\n\t\t\t\t}\n\t\t\t\treturn policy.GetFields(ctx, model).Collect(writeAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\t// set properties getter if available\n\t\tif getFieldsAndPropsMatcher(ctx) && policy.GetProperties != nil {\n\t\t\tctx.GetReadableProperties = func(model coal.Model) []string {\n\t\t\t\treturn policy.GetProperties(ctx, model).Collect(readAccess[ctx.Operation])\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (c *client) exec(r *http.Request) (io.ReadCloser, error) {\n\tresp, err := c.doRaw(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"bad response code: %d\\n\"+\n\t\t\t\"request was: %v\\n\",\n\t\t\tresp.StatusCode,\n\t\t\tr)\n\t}\n\n\tif resp.Body == nil {\n\t\treturn nil, fmt.Errorf(\"no body in response\")\n\t}\n\n\treturn resp.Body, nil\n}", "func Execute() {\n\tgodotenv.Load()\n\tthirdparty.InitAirtableHTTPClient()\n\n\tthirdparty.Bases = strings.Split(os.Getenv(\"AIRTABLE_TABLES\"), \",\")\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/checknews\", api.CheckAirtableAllNewsHandler)\n\tlog.Fatal(http.ListenAndServe(\":6060\", api.RequestLogger(mux)))\n}", "func (p *Pool) Execute(query string) (resp []Response, err error) {\n\tpc, err := p.Get()\n\tif err != nil {\n\t\tfmt.Printf(\"Error aquiring connection from pool: %s\", err)\n\t\treturn nil, err\n\t}\n\tdefer pc.Close()\n\treturn pc.Client.Execute(query)\n}", "func (c *Client) ExecuteFunction(request *ExecuteFunctionRequest) (response *ExecuteFunctionResponse, err error) {\n if request == nil {\n request = NewExecuteFunctionRequest()\n }\n response = NewExecuteFunctionResponse()\n err = c.Send(request, response)\n return\n}", "func (r *Client) Execute(s ...string) {\n\n\tout := r.ExecuteAndReturn(s...)\n\n\tprint(out)\n}", "func (r apiGetExportsRequest) Execute() (InlineResponse20039, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20039\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetExports\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/exports\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.applicationId != nil {\n\t\tlocalVarQueryParams.Add(\"applicationId\", parameterToString(*r.applicationId, \"\"))\n\t}\n\tif r.campaignId != nil {\n\t\tlocalVarQueryParams.Add(\"campaignId\", parameterToString(*r.campaignId, \"\"))\n\t}\n\tif r.entity != nil {\n\t\tlocalVarQueryParams.Add(\"entity\", parameterToString(*r.entity, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20039\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiStartUsingPOSTRequest) Execute() (ResponseEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseEntity\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"PipelineControllerApiService.StartUsingPOST\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/pipelines/start\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.map_ == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"map_ is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"*/*\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.map_\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ResponseEntity\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (h *Hook) Execute(r *admission.AdmissionRequest) (*Result, error) {\n\tswitch r.Operation {\n\tcase admission.Create:\n\t\treturn wrapperExecution(h.Create, r)\n\tcase admission.Update:\n\t\treturn wrapperExecution(h.Update, r)\n\tcase admission.Delete:\n\t\treturn wrapperExecution(h.Delete, r)\n\tcase admission.Connect:\n\t\treturn wrapperExecution(h.Connect, r)\n\t}\n\n\treturn &Result{Message: fmt.Sprintf(\"Invalid operation: %s\", r.Operation)}, nil\n}", "func (e *Execute) Execute(args []string) error {\n\tfmt.Println(\"args: \", args)\n\tif len(args) <= 0 {\n\t\treturn fmt.Errorf(\"no args passed to echo\")\n\t}\n\n\tcli := client.NewClient(e.ClientOpts)\n\terr := cli.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\tresp, err := cli.Execute(request.Request{Query: string(args[0])})\n\tfmt.Println(\"ERROR: \", err, \" RESP: \", resp)\n\n\treturn nil\n}", "func (request *S3Request) execute(client *http.Client) (*S3Response, error) {\n method := request.method\n url := request.constructUrl()\n\n httpRequest,err := http.NewRequest(method, url, nil)\n if err != nil {\n return nil,err\n }\n\n for key,value := range request.headers {\n httpRequest.Header.Add(key, value)\n }\n httpRequest.Header.Add(HTTP_HDR_AUTH, request.authHeader())\n\n log.Println(\"executing\", httpRequest)\n httpResponse,err := client.Do(httpRequest)\n if err != nil {\n return nil, err\n }\n\n return NewS3Response(httpResponse)\n}", "func Execute() {\n\tzk.Execute()\n}", "func (worker *Worker) Execute() {\n\tfor i := 0; i < worker.NumberOfRequests; i++ {\n\t\tworker.Responses[i] = worker.DoRequest()\n\t}\n\tworker.wg.Done()\n}", "func (rb *ByProjectKeyImageSearchRequestMethodPost) Execute(ctx context.Context) (result *ImageSearchResponse, err error) {\n\tdata := rb.body\n\tvar queryParams url.Values\n\tif rb.params != nil {\n\t\tqueryParams = rb.params.Values()\n\t} else {\n\t\tqueryParams = url.Values{}\n\t}\n\tresp, err := rb.client.post(\n\t\tctx,\n\t\trb.url,\n\t\tqueryParams,\n\t\trb.headers,\n\t\tdata,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = json.Unmarshal(content, &result)\n\t\treturn result, nil\n\tdefault:\n\t\tresult := GenericRequestError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tContent: content,\n\t\t\tResponse: resp,\n\t\t}\n\t\treturn nil, result\n\t}\n\n}", "func (r apiGetLoyaltyStatisticsRequest) Execute() (LoyaltyStatistics, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyStatistics\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyStatistics\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/statistics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyStatistics\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (config HomeAssistantConfig) Execute(command string) error {\n\tcmd, ok := config.Commands[command]\n\tif !ok {\n\t\treturn fmt.Errorf(`\"%v\" is not a valid command`, command)\n\t}\n\n\tif len(cmd.Method) == 0 {\n\t\tcmd.Method = \"GET\"\n\t}\n\n\tvar reqBody *bytes.Buffer\n\tif len(cmd.Payload) > 0 {\n\t\treqBody = bytes.NewBufferString(cmd.Payload)\n\t}\n\n\turl := config.Server + cmd.Endpoint\n\tlog.Printf(\"sending request to %s\", url)\n\treq, err := http.NewRequest(cmd.Method, url, reqBody)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating request to Home Assistant server: %v\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tif len(config.Password) > 0 {\n\t\treq.Header.Set(config.AuthorizationHeader, config.Password)\n\t}\n\n\tresp, err := config.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making request to Home Assistant server: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tcode := resp.StatusCode\n\tif code != http.StatusOK {\n\t\treturn fmt.Errorf(\"received %d status code\", code)\n\t}\n\n\tlog.Printf(\"Response code %d\", resp.StatusCode)\n\n\treturn nil\n}", "func (r apiGetLoyaltyProgramRequest) Execute() (LoyaltyProgram, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyProgram\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgram\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyProgram\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiTransferLoyaltyCardRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.TransferLoyaltyCard\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards/{loyaltyCardId}/transfer\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyCardId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyCardId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif strlen(r.loyaltyCardId) > 108 {\n\t\treturn nil, reportError(\"loyaltyCardId must have less than 108 elements\")\n\t}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func executeGenericHttpRequest(request genericHttpRequest) (int, string, error) {\n\tclient := http.Client{}\n\n\t// define the request\n\tlog.Println(request.method, request.uri, request.uri, request.body)\n\treq, err := http.NewRequest(request.method, request.uri, bytes.NewBufferString(request.body))\n\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\t// add the headers\n\tfor key, value := range request.headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\t// execute\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn -1, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\treturn resp.StatusCode, string(body), err\n}", "func (r *Carol) Execute(cfg ExecConfig) {\n\tr.Responder.Execute(cfg, r.exec)\n}", "func (cu *CurlJob) Execute(ctx context.Context) {\n\tcu.request = cu.request.WithContext(ctx)\n\tvar err error\n\tcu.Response, err = cu.httpClient.Do(cu.request)\n\n\tif err == nil && cu.Response.StatusCode >= 200 && cu.Response.StatusCode < 400 {\n\t\tcu.JobStatus = OK\n\t} else {\n\t\tcu.JobStatus = FAILURE\n\t}\n}", "func (r apiGetLoyaltyCardsRequest) Execute() (InlineResponse20013, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20013\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyCards\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/cards\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.identifier != nil {\n\t\tlocalVarQueryParams.Add(\"identifier\", parameterToString(*r.identifier, \"\"))\n\t}\n\tif r.profileId != nil {\n\t\tlocalVarQueryParams.Add(\"profileId\", parameterToString(*r.profileId, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20013\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiAddLoyaltyPointsRequest) Execute() (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.AddLoyaltyPoints\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}/add_points\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (c *ServiceClient) ExecuteAPI(method, url string, queryParam map[string]string, buffer []byte) ([]byte, error) {\n\theaders, err := c.createHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest := coreapi.Request{\n\t\tMethod: method,\n\t\tURL: url,\n\t\tQueryParams: queryParam,\n\t\tHeaders: headers,\n\t\tBody: buffer,\n\t}\n\n\tresponse, err := c.apiClient.Send(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(ErrNetwork, err.Error())\n\t}\n\n\tswitch response.Code {\n\tcase http.StatusOK:\n\t\treturn response.Body, nil\n\tcase http.StatusUnauthorized:\n\t\treturn nil, ErrAuthentication\n\tdefault:\n\t\tlogResponseErrors(response.Body)\n\t\treturn nil, ErrRequestQuery\n\t}\n}", "func (c *ToyController) Execute(ctx context.Context) error {\n\tc.le.Debug(\"toy controller executed\")\n\t<-ctx.Done()\n\treturn nil\n}", "func (r Forecast) Perform(ctx context.Context) (*http.Response, error) {\n\treq, err := r.HttpRequest(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := r.transport.Perform(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"an error happened during the Forecast query execution: %w\", err)\n\t}\n\n\treturn res, nil\n}", "func Execute(ctx context.Context, query string, vars map[string]interface{}) (map[string]*json.RawMessage, error) {\n\tmediaQuery := graphql.NewRequest(query)\n\tfor k, v := range vars {\n\t\tmediaQuery.Var(k, v)\n\t}\n\n\tvar res map[string]*json.RawMessage\n\tif err := client.Run(ctx, mediaQuery, &res); err != nil {\n\t\treturn map[string]*json.RawMessage{}, err\n\t}\n\treturn res, nil\n}", "func (r *GetWebVersionRequest) Execute() (res *GetWebVersionResult, err error) {\n\tvar result GetWebVersionResult\n\tif err = r.request.Execute(\"getWebVersion\", &result); err != nil {\n\t\treturn\n\t}\n\n\tres = &result\n\n\treturn\n}", "func (a *RequestServiceApiService) GetRequestExecute(r ApiGetRequestRequest) (*os.File, *_nethttp.Response, GenericOpenAPIError) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\texecutionError GenericOpenAPIError\n\t\tlocalVarReturnValue *os.File\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"RequestServiceApiService.GetRequest\")\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarPath := localBasePath + \"/requests/{uuid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uuid\"+\"}\", _neturl.PathEscape(parameterToString(r.uuid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.authorization != nil {\n\t\tlocalVarHeaderParams[\"Authorization\"] = parameterToString(*r.authorization, \"\")\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, nil, executionError\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\texecutionError.error = err.Error()\n\t\treturn localVarReturnValue, localVarHTTPResponse, executionError\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, executionError\n}", "func (r apiGetLoyaltyProgramTransactionsRequest) Execute() (InlineResponse20012, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20012\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyProgramTransactions\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/transactions\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.loyaltyTransactionType != nil {\n\t\tlocalVarQueryParams.Add(\"loyaltyTransactionType\", parameterToString(*r.loyaltyTransactionType, \"\"))\n\t}\n\tif r.subledgerId != nil {\n\t\tlocalVarQueryParams.Add(\"subledgerId\", parameterToString(*r.subledgerId, \"\"))\n\t}\n\tif r.startDate != nil {\n\t\tlocalVarQueryParams.Add(\"startDate\", parameterToString(*r.startDate, \"\"))\n\t}\n\tif r.endDate != nil {\n\t\tlocalVarQueryParams.Add(\"endDate\", parameterToString(*r.endDate, \"\"))\n\t}\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20012\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (r apiGetAdditionalCostsRequest) Execute() (InlineResponse20032, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20032\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAdditionalCosts\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/additional_costs\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20032\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c HTTPGetHealthcheck) Execute() Result {\n\tinput := struct {\n\t\tURL string `json:\"url\"`\n\t}{\n\t\thttp.CleanURL(c.URL),\n\t}\n\n\tclient := http.NewClient(c.URL)\n\n\tstart := time.Now()\n\tresp, err := client.Get(\"\")\n\tend := time.Now()\n\n\tif err != nil {\n\t\treturn FailWithInput(err.Error(), input)\n\t}\n\n\tcontext := HTTPExpectationContext{\n\t\tResponse: resp,\n\t\tResponseTime: end.Sub(start),\n\t}\n\n\treturn c.VerifyExpectation(input, func(assertion interface{}) []*AssertionGroup {\n\t\treturn assertion.(HTTPResponseExpectation).Verify(context)\n\t})\n}", "func execute(yaml string, method string, endpoint string, f func(http.ResponseWriter, *http.Request), t *testing.T) *httptest.ResponseRecorder {\n\t// Read data, create a request manually, instantiate recording apparatus.\n\tdata := strings.NewReader(yaml)\n\treq, err := http.NewRequest(method, endpoint, data)\n\tok(t, err)\n\trr := httptest.NewRecorder()\n\n\t// Create handler and process request\n\thandler := http.HandlerFunc(f)\n\thandler.ServeHTTP(rr, req)\n\n\treturn rr\n}", "func (bq *InMemoryBuildQueue) Execute(in *remoteexecution.ExecuteRequest, out remoteexecution.Execution_ExecuteServer) error {\n\t// Fetch the action corresponding to the execute request.\n\t// Ideally, a scheduler is oblivious of what this message looks\n\t// like, if it weren't for the fact that DoNotCache and Platform\n\t// are used for scheduling decisions.\n\t//\n\t// To prevent loading this messages from the Content Addressable\n\t// Storage (CAS) multiple times, the scheduler holds on to it\n\t// and passes it on to the workers.\n\tctx := out.Context()\n\tinstanceName, err := digest.NewInstanceName(in.InstanceName)\n\tif err != nil {\n\t\treturn util.StatusWrapf(err, \"Invalid instance name %#v\", in.InstanceName)\n\t}\n\n\tif err := auth.AuthorizeSingleInstanceName(ctx, bq.executeAuthorizer, instanceName); err != nil {\n\t\treturn util.StatusWrap(err, \"Authorization\")\n\t}\n\n\tactionDigest, err := instanceName.NewDigestFromProto(in.ActionDigest)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract digest for action\")\n\t}\n\tactionMessage, err := bq.contentAddressableStorage.Get(ctx, actionDigest).ToProto(&remoteexecution.Action{}, bq.maximumMessageSizeBytes)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to obtain action\")\n\t}\n\taction := actionMessage.(*remoteexecution.Action)\n\tplatformKey, err := platform.NewKey(instanceName, action.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Forward the client-provided request metadata, so that the\n\t// worker logs it.\n\trequestMetadata := getRequestMetadata(ctx)\n\ttargetID := requestMetadata.GetTargetId()\n\tvar auxiliaryMetadata []*anypb.Any\n\tif requestMetadata != nil {\n\t\trequestMetadataAny, err := anypb.New(requestMetadata)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrapWithCode(err, codes.InvalidArgument, \"Failed to marshal request metadata\")\n\t\t}\n\t\tauxiliaryMetadata = []*anypb.Any{requestMetadataAny}\n\t}\n\tw3cTraceContext := otel.W3CTraceContextFromContext(ctx)\n\n\t// TODO: Remove this code once all clients support REv2.2.\n\tif action.Platform == nil || targetID == \"\" {\n\t\tcommandDigest, err := instanceName.NewDigestFromProto(action.CommandDigest)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to extract digest for command\")\n\t\t}\n\t\tcommandMessage, err := bq.contentAddressableStorage.Get(ctx, commandDigest).ToProto(&remoteexecution.Command{}, bq.maximumMessageSizeBytes)\n\t\tif err != nil {\n\t\t\treturn util.StatusWrap(err, \"Failed to obtain command\")\n\t\t}\n\t\tcommand := commandMessage.(*remoteexecution.Command)\n\n\t\t// REv2.1 and older don't provide platform properties as\n\t\t// part of the Action message.\n\t\tif action.Platform == nil {\n\t\t\tplatformKey, err = platform.NewKey(instanceName, command.Platform)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// REv2.1 RequestMetadata doesn't include the target_id\n\t\t// field. Provide the argv[0] instead, so that we gain\n\t\t// some insight in what this action does.\n\t\tif targetID == \"\" && len(command.Arguments) > 0 {\n\t\t\ttargetID = command.Arguments[0]\n\t\t}\n\t}\n\n\t// Create an invocation key. Operations are scheduled by\n\t// grouping them by invocation, so that scheduling is fair.\n\tplatformHooks := bq.platformHooks[bq.platformHooksTrie.GetLongestPrefix(platformKey)+1]\n\tinvocationID, err := platformHooks.ExtractInvocationID(ctx, instanceName, action, requestMetadata)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to extract invocation ID from request\")\n\t}\n\tinvocationKey, err := newInvocationKey(invocationID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Analyze the action, so that we can later determine on which\n\t// size class this action needs to run.\n\tinitialSizeClassSelector, err := platformHooks.Analyze(ctx, actionDigest.GetDigestFunction(), action)\n\tif err != nil {\n\t\treturn util.StatusWrap(err, \"Failed to analyze initial size class of action\")\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tif t, ok := bq.inFlightDeduplicationMap[actionDigest]; ok {\n\t\t// A task for the same action digest already exists\n\t\t// against which we may deduplicate. No need to create a\n\t\t// task.\n\t\tinitialSizeClassSelector.Abandoned()\n\t\tscq := t.getSizeClassQueue()\n\t\ti := scq.getOrCreateInvocation(invocationKey)\n\t\tif o, ok := t.operations[i]; ok {\n\t\t\t// Task is already associated with the current\n\t\t\t// invocation. Simply wait on the operation that\n\t\t\t// already exists.\n\t\t\treturn o.waitExecution(bq, out)\n\t\t}\n\n\t\t// Create an additional operation for this task.\n\t\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\t\tswitch t.getStage() {\n\t\tcase remoteexecution.ExecutionStage_QUEUED:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is still queued.\n\t\t\to.enqueue()\n\t\tcase remoteexecution.ExecutionStage_EXECUTING:\n\t\t\t// The request has been deduplicated against a\n\t\t\t// task that is already in the executing stage.\n\t\t\ti.incrementExecutingWorkersCount()\n\t\tdefault:\n\t\t\tpanic(\"Task in unexpected stage\")\n\t\t}\n\t\treturn o.waitExecution(bq, out)\n\t}\n\n\t// We need to create a new task. For that we first need to\n\t// obtain the size class queue in which we're going to place it.\n\tplatformQueueIndex := bq.platformQueuesTrie.GetLongestPrefix(platformKey)\n\tif platformQueueIndex < 0 {\n\t\tcode := codes.FailedPrecondition\n\t\tif bq.now.Before(bq.platformQueueAbsenceHardFailureTime) {\n\t\t\t// The scheduler process started not too long\n\t\t\t// ago. It may be the case that clients ended up\n\t\t\t// connecting to the scheduler before workers\n\t\t\t// got a chance to synchronize.\n\t\t\t//\n\t\t\t// Prevent builds from failing unnecessarily by\n\t\t\t// providing a brief window of time where\n\t\t\t// soft errors are returned to the client,\n\t\t\t// giving workers time to reconnect.\n\t\t\tcode = codes.Unavailable\n\t\t}\n\t\tinitialSizeClassSelector.Abandoned()\n\t\treturn status.Errorf(code, \"No workers exist for instance name prefix %#v platform %s\", platformKey.GetInstanceNamePrefix().String(), platformKey.GetPlatformString())\n\t}\n\tpq := bq.platformQueues[platformQueueIndex]\n\tsizeClassIndex, timeout, initialSizeClassLearner := initialSizeClassSelector.Select(pq.sizeClasses)\n\tscq := pq.sizeClassQueues[sizeClassIndex]\n\n\t// Create the task.\n\tactionWithCustomTimeout := *action\n\tactionWithCustomTimeout.Timeout = durationpb.New(timeout)\n\tt := &task{\n\t\toperations: map[*invocation]*operation{},\n\t\tactionDigest: actionDigest,\n\t\tdesiredState: remoteworker.DesiredState_Executing{\n\t\t\tActionDigest: in.ActionDigest,\n\t\t\tAction: &actionWithCustomTimeout,\n\t\t\tQueuedTimestamp: bq.getCurrentTime(),\n\t\t\tAuxiliaryMetadata: auxiliaryMetadata,\n\t\t\tInstanceNameSuffix: pq.instanceNamePatcher.PatchInstanceName(instanceName).String(),\n\t\t\tW3CTraceContext: w3cTraceContext,\n\t\t},\n\t\ttargetID: targetID,\n\t\tinitialSizeClassLearner: initialSizeClassLearner,\n\t\tstageChangeWakeup: make(chan struct{}),\n\t}\n\tif !action.DoNotCache {\n\t\tbq.inFlightDeduplicationMap[actionDigest] = t\n\t}\n\ti := scq.getOrCreateInvocation(invocationKey)\n\to := t.newOperation(bq, in.ExecutionPolicy.GetPriority(), i, false)\n\tt.schedule(bq)\n\treturn o.waitExecution(bq, out)\n}", "func (r apiGetAudiencesRequest) Execute() (InlineResponse20029, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue InlineResponse20029\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetAudiences\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/audiences\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.sort != nil {\n\t\tlocalVarQueryParams.Add(\"sort\", parameterToString(*r.sort, \"\"))\n\t}\n\tif r.withTotalResultSize != nil {\n\t\tlocalVarQueryParams.Add(\"withTotalResultSize\", parameterToString(*r.withTotalResultSize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v InlineResponse20029\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (e *LoopbackHTTPExecutor) Execute(ctx context.Context, t *Task, done func(retry bool)) {\n\tif t.Message != nil {\n\t\tdone(false)\n\t\tpanic(\"Executing PubSub tasks is not supported yet\") // break tests loudly\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\tdone(!success)\n\t}()\n\n\tvar method taskspb.HttpMethod\n\tvar requestURL string\n\tvar headers map[string]string\n\tvar body []byte\n\n\tswitch mt := t.Task.MessageType.(type) {\n\tcase *taskspb.Task_HttpRequest:\n\t\tmethod = mt.HttpRequest.HttpMethod\n\t\trequestURL = mt.HttpRequest.Url\n\t\theaders = mt.HttpRequest.Headers\n\t\tbody = mt.HttpRequest.Body\n\tcase *taskspb.Task_AppEngineHttpRequest:\n\t\tmethod = mt.AppEngineHttpRequest.HttpMethod\n\t\trequestURL = mt.AppEngineHttpRequest.RelativeUri\n\t\theaders = mt.AppEngineHttpRequest.Headers\n\t\tbody = mt.AppEngineHttpRequest.Body\n\tdefault:\n\t\tlogging.Errorf(ctx, \"Bad task, no payload: %q\", t.Task)\n\t\treturn\n\t}\n\n\tparsedURL, err := url.Parse(requestURL)\n\tif err != nil {\n\t\tlogging.Errorf(ctx, \"Bad task URL %q\", requestURL)\n\t\treturn\n\t}\n\thost := parsedURL.Host\n\n\t// Make the URL relative.\n\tparsedURL.Scheme = \"\"\n\tparsedURL.Host = \"\"\n\trequestURL = parsedURL.String()\n\n\treq := httptest.NewRequest(method.String(), requestURL, bytes.NewReader(body))\n\treq.Host = host\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\t// See https://cloud.google.com/tasks/docs/creating-http-target-tasks#handler\n\t// We emulate only headers we actually use.\n\treq.Header.Set(\"X-CloudTasks-TaskExecutionCount\", strconv.Itoa(t.Attempts-1))\n\tif t.Attempts > 1 {\n\t\treq.Header.Set(\"X-CloudTasks-TaskRetryReason\", \"task handler failed\")\n\t}\n\n\trr := httptest.NewRecorder()\n\te.Handler.ServeHTTP(rr, req)\n\tstatus := rr.Result().StatusCode\n\tsuccess = status >= 200 && status <= 299\n}", "func executeEsRequest(es EsConnection, httpMethod, api string, body []byte) ([]byte, error) {\n\tlogrus.Debugln(\"Executing\", httpMethod, \"request to\", api)\n\tesURL := fmt.Sprintf(\"%s:%s%s\", es.URL, es.Port, api)\n\n\t// Create the client to interact with the API\n\tvar transport *http.Transport\n\tif es.RootCAs == nil {\n\t\tlogrus.Debugln(\"The request does not use secure certificates\")\n\t\ttransport = &http.Transport{}\n\t} else {\n\t\tlogrus.Debugln(\"The request uses secure certificates\")\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tCertificates: []tls.Certificate{es.Certificate},\n\t\t\tRootCAs: es.RootCAs,\n\t\t}\n\n\t\ttransport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\tclient := http.Client{Transport: transport}\n\n\treq, err := http.NewRequest(httpMethod, esURL, bytes.NewBuffer(body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request creation failed: %s\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tlogrus.Debugln(\"Executing request...\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"the HTTP request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn io.ReadAll(resp.Body)\n}", "func (b *hereNowBuilder) Execute() (*HereNowResponse, StatusResponse, error) {\n\trawJSON, status, err := executeRequest(b.opts)\n\tif err != nil {\n\t\treturn emptyHereNowResponse, status, err\n\t}\n\n\treturn newHereNowResponse(rawJSON, b.opts.Channels, status)\n}", "func (c *HTTPClient) Do(ctx context.Context, method string, path string, params map[string]string, data interface{}, result interface{}) (statusCode int, err error) {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treq, err := c.prepareRequest(method, path, params, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.do(ctx, req, result, true, true, false)\n}", "func (c *HTTPClient) Invoke(name string, params map[string]interface{}, body io.Reader) (Response, error) {\n\tcmd, err := NewCommand(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcmd.SetBody(body)\n\treturn c.Query(cmd)\n}", "func (r apiTrackEventRequest) Execute() (IntegrationState, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue IntegrationState\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.TrackEvent\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/events\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\tif r.dry != nil {\n\t\tlocalVarQueryParams.Add(\"dry\", parameterToString(*r.dry, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 201 {\n\t\t\tvar v IntegrationState\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 409 {\n\t\t\tvar v map[string]interface{}\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (builder QueryBuilder) Execute(ctx context.Context, options ...OperationExecutorOptionFn) (*Response, error) {\n\texecutor := NewDGoExecutor(builder.client)\n\n\tfor _, option := range options {\n\t\toption(executor)\n\t}\n\treturn executor.ExecuteQueries(ctx, builder)\n}", "func Execute() {\n\n\t// initialize router\n\trouter := mux.NewRouter()\n\n\t// load custom routes\n\tloadRoutes(router)\n\n\t// initialize http server configs\n\tserver := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.BackendPort),\n\t\tHandler: router,\n\t}\n\n\t// start http server\n\tfmt.Printf(\"HTTP Server listening on port: %s\\n\", config.BackendPort)\n\tserver.ListenAndServe()\n}", "func (c *Client) PerformRequest(opt PerformRequestOptions) (*Response, error) {\n\tvar err error\n\tvar req *Request\n\tvar resp *Response\n\n\tpathWithParmas := opt.Path\n\tif len(opt.Params) > 0 {\n\t\tpathWithParmas += \"?\" + opt.Params.Encode()\n\t}\n\tfmt.Println(opt.Method, c.serverURL+pathWithParmas)\n\treq, err = NewRequest(opt.Method, c.serverURL+pathWithParmas)\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: connot create request for %s %s: %v \\n\", strings.ToUpper(opt.Method), c.serverURL+pathWithParmas, err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-ApiKeys\", fmt.Sprintf(\"accessKey=%s; secretKey=%s\", c.accessKey, c.secretKey))\n\n\tif opt.ContentType != \"\" {\n\t\treq.Header.Set(\"Content-Type\", opt.ContentType)\n\t}\n\n\tif len(opt.Headers) > 0 {\n\t\tfor key, value := range opt.Headers {\n\t\t\tfor _, val := range value {\n\t\t\t\treq.Header.Add(key, val)\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Body != nil {\n\t\terr = req.SetBody(opt.Body, false)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"nessus: couldn't set body %+v for request: %v \\n\", opt.Body, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tres, err := c.c.Do((*http.Request)(req))\n\n\tif err != nil {\n\t\tfmt.Printf(\"nessus: send request failed: %v \\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tresp, err = c.newResponse(res, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (r apiSyncCatalogRequest) Execute() (Catalog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Catalog\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"IntegrationApiService.SyncCatalog\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/catalogs/{catalogId}/sync\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"catalogId\"+\"}\", _neturl.QueryEscape(parameterToString(r.catalogId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Catalog\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorResponse\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ErrorResponseWithStatus\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func executeRequest(method string, path string, contact c.Contact) *httptest.ResponseRecorder {\n\tresponse := httptest.NewRecorder()\n\tif (c.Contact{})==contact {\n\t\treq, _ := http.NewRequest(method, path, nil)\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t} else {\n\t\tpayload,_:= json.Marshal(contact)\n\t\treq, _ := http.NewRequest(method, path, bytes.NewBuffer(payload))\n\t\tserver.GetRouter().ServeHTTP(response, req)\n\t}\n\treturn response\n}", "func (s *Search) Execute() (*SearchResponse, error) {\n\t// set defaults\n\tif s.Params.Limit == 0 {\n\t\ts.Params.Limit = 100\n\t}\n\n\tpayload, err := json.Marshal(s.Params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := baseSearchPath + \"/\" + s.Type\n\tif s.Deleted == true {\n\t\tpath += \"/deleted\"\n\t}\n\treq, err := s.client.NewRequest(\"POST\", path, nil, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Close()\n\n\tbody, err := ioutil.ReadAll(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchResp := &SearchResponse{}\n\t// bytes.Reader implements Seek, which we need to use to 'rewind' the Body below\n\tsearchResp.RawResponse = bytes.NewReader(body)\n\terr = json.Unmarshal(body, searchResp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif searchResp.Response.MoreItems == true {\n\t\tsearchResp.NextOffset = s.Params.Offset + s.Params.Limit\n\t} else {\n\t\tsearchResp.NextOffset = 0\n\t}\n\n\t// 'rewind' the raw response\n\tsearchResp.RawResponse.Seek(0, 0)\n\n\treturn searchResp, nil\n}", "func (r apiGetLoyaltyPointsRequest) Execute() (LoyaltyLedger, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue LoyaltyLedger\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetLoyaltyPoints\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/loyalty_programs/{loyaltyProgramId}/profile/{integrationId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"loyaltyProgramId\"+\"}\", _neturl.QueryEscape(parameterToString(r.loyaltyProgramId, \"\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"integrationId\"+\"}\", _neturl.QueryEscape(parameterToString(r.integrationId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v LoyaltyLedger\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}" ]
[ "0.77782923", "0.7582797", "0.741287", "0.7358983", "0.7292987", "0.7218151", "0.7215562", "0.7154855", "0.7145005", "0.70240575", "0.69687915", "0.695788", "0.6858044", "0.6820558", "0.67871475", "0.6751008", "0.6732763", "0.67267585", "0.66466635", "0.6637201", "0.663456", "0.66195893", "0.66184837", "0.65956116", "0.659285", "0.6544845", "0.65049857", "0.65011257", "0.65000814", "0.6493455", "0.6460489", "0.6453609", "0.64343137", "0.64236", "0.64120454", "0.6355321", "0.6342087", "0.6331583", "0.63299066", "0.63238937", "0.6321131", "0.63138837", "0.63020885", "0.6295367", "0.62723947", "0.6269672", "0.6269614", "0.6256541", "0.623812", "0.619001", "0.61871004", "0.61584073", "0.6158075", "0.61575884", "0.6155383", "0.61397356", "0.6137546", "0.61318165", "0.61306256", "0.6130486", "0.6120463", "0.6110921", "0.61030287", "0.609429", "0.609231", "0.60802615", "0.6079677", "0.60763776", "0.60466146", "0.60460013", "0.6042795", "0.603318", "0.60318524", "0.6027752", "0.60168314", "0.60028964", "0.59875226", "0.5975002", "0.59709895", "0.5970853", "0.59664345", "0.59484684", "0.5939464", "0.59340656", "0.59327954", "0.59259856", "0.5914416", "0.59013766", "0.58966976", "0.58898723", "0.5884585", "0.5876751", "0.58755565", "0.58714074", "0.5854153", "0.5852719", "0.5848799", "0.58466387", "0.584653", "0.58371776", "0.583316" ]
0.0
-1
Validate template and get URL for cost estimation.
func ValidateAndEstimateCosts(context *context.Context) bool { valid := false defer printResult(&valid, context.Logger) if *context.CliArguments.MFA { err := updateSessionToken(context.Config.Profile, context.Config.Region, context.Logger) if err != nil { context.Logger.Error(err.Error()) return false } } session, err := createSession(&context.Config.Region, context.Config.Profile, context.Logger) if err != nil { context.Logger.Error(err.Error()) return false } rawTemplate, err := ioutil.ReadFile(*context.CliArguments.TemplatePath) if err != nil { context.Logger.Error(err.Error()) return false } template := string(rawTemplate) valid, err = isTemplateValid(session, &template) if err != nil { context.Logger.Error(err.Error()) return false } estimateCosts(session, &template, context.Logger) return valid }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tplValid(stack *ctlaws.Stack, path string) error {\n\tvar tplByte []byte\n\tvar url string\n\tvar err error\n\n\tif utils.IsUrlRegexp(path) {\n\t\turl = path\n\t} else {\n\t\ttplByte, err = ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = stack.ValidateTemplate(tplByte, url)\n\n\treturn err\n}", "func ValidateTemplate(text string) error {\n\tvc := ValidationContext{\n\t\tFromAddress: \"[email protected]\",\n\t\tBaseURL: \"http://example.com\",\n\t}\n\ttd := Result{\n\t\tBaseRecipient: BaseRecipient{\n\t\t\tEmail: \"[email protected]\",\n\t\t\tFirstName: \"Foo\",\n\t\t\tLastName: \"Bar\",\n\t\t\tPosition: \"Test\",\n\t\t},\n\t\tRId: \"123456\",\n\t}\n\tptx, err := NewPhishingTemplateContext(vc, td.BaseRecipient, td.RId)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = ExecuteTemplate(text, ptx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func determineURL(gc *GatewayClient, opType structures.OperationType) (string, error) {\n\t// Complete URL for request\n\tvar completeURL string\n\n\t// Validate API config, base URL and version of API\n\tif gc.API.BaseURI == \"\" {\n\t\treturn \"\", errors.New(\"Gateway client's URL is empty in, API settings\")\n\t}\n\n\tif gc.API.Version == \"\" {\n\t\treturn \"\", errors.New(\"Gateway client's Version is empty in, API settings\")\n\t}\n\n\t// Try to get operation type from request data\n\tif opType == \"\" {\n\t\treturn \"\", errors.New(\"Operation type is empty. Problem in operation builder\")\n\t}\n\n\t// AS example must be like: http://url.pay.com/v55.0/sms\n\tcompleteURL = fmt.Sprintf(\"%s/v%s/%s\", gc.API.BaseURI, gc.API.Version, opType)\n\n\t// @TODO Debug print URL\n\tfmt.Println(\"REQUEST URL \" + completeURL)\n\n\treturn completeURL, nil\n}", "func GetUrlAndValidate() (string, error) {\n // If server URL is not set\n if !viper.IsSet(settings.ServerUrlKey) {\n fmt.Fprint(os.Stderr, \"Error: Server URL is not found\\n\")\n os.Exit(1)\n }\n // Get server URL\n serverUrlStr := viper.GetString(settings.ServerUrlKey)\n\n // Check whether the string is URL or not\n if !govalidator.IsRequestURL(serverUrlStr) {\n return serverUrlStr, errors.Errorf(\"'%s' is not URL\\n\", serverUrlStr)\n }\n\n return serverUrlStr, nil\n}", "func createURL(searchTerm, realTerm, realTermLat, searchTermLat, realTermLng, searchTermLng string) string {\n\n\t// 1. Return the appropriate URL based on whether the environment is development or production\n\tif config.IsDevelopmentEnvironment(os.Getenv(\"DEPLOYMENT_TYPE\")) {\n\t\treturn os.Getenv(\"DEVELOPMENT_SERVICE_PATH\") + createPath(searchTerm, realTerm, realTermLat, searchTermLat, realTermLng, searchTermLng)\n\t}\n\treturn os.Getenv(\"PRODUCTION_SERVICE_PATH\") + createPath(searchTerm, realTerm, realTermLat, searchTermLat, realTermLng, searchTermLng)\n}", "func getUrl(config map[string]string, path string) (string) {\n url := fmt.Sprint(\"https://\", config[\"CONTROL_SERVICE\"], \":\", config[\"CONTROL_PORT\"], path)\n return url\n}", "func validateTemplate(t *testing.T, tplI config.Template, dest bot.Destination) {\n\tt.Helper()\n\n\t// First, make sure all advertised files exist.\n\tfor _, file := range tplI.Describe(dest) {\n\t\t// Don't bother checking directories, they're meant to be black\n\t\t// boxes. We could implement type-specific checks if we really\n\t\t// wanted.\n\t\tif file.IsDir {\n\t\t\tcontinue\n\t\t}\n\n\t\tbytes, err := dest.Read(file.Name)\n\t\trequire.NoError(t, err)\n\n\t\t// Should at least be non-empty.\n\t\tt.Logf(\"Expected file %q for template %q has length: %d\", file.Name, tplI.Name(), len(bytes))\n\t\trequire.Truef(t, len(bytes) > 0, \"file %q in template %q must be non-empty\", file.Name, tplI.Name())\n\t}\n\n\t// Next, for supported template types, make sure they're valid.\n\t// TODO: consider adding further type-specific tests.\n\tswitch tpl := tplI.(type) {\n\tcase *config.TemplateIdentity:\n\t\t// Make sure the identityfile package can read this identity file.\n\t\tb, err := dest.Read(tpl.FileName)\n\t\trequire.NoError(t, err)\n\n\t\tbuf := bytes.NewBuffer(b)\n\t\t_, err = identityfile.Read(buf)\n\t\trequire.NoError(t, err)\n\tcase *config.TemplateTLSCAs:\n\t\tb, err := dest.Read(tpl.HostCAPath)\n\t\trequire.NoError(t, err)\n\t\t_, err = tlsca.ParseCertificatePEM(b)\n\t\trequire.NoError(t, err)\n\n\t\tb, err = dest.Read(tpl.UserCAPath)\n\t\trequire.NoError(t, err)\n\t\t_, err = tlsca.ParseCertificatePEM(b)\n\t\trequire.NoError(t, err)\n\t}\n}", "func ProcessTemplate(templateFile string, values interface{}) (string, []byte, error) {\n\tname := path.Base(templateFile)\n\tt := template.New(name).Funcs(map[string]interface{}{\n\t\t\"addURIAndSha\": func(url, tag string) string {\n\t\t\tt := struct {\n\t\t\t\tTagName string\n\t\t\t}{\n\t\t\t\tTagName: tag,\n\t\t\t}\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\ttemp, err := template.New(\"url\").Parse(url)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\terr = temp.Execute(buf, t)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tlogrus.Infof(\"getting sha256 for %s\", buf.String())\n\t\t\tsha256, err := getSha256ForAsset(buf.String())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(`uri: %s\n sha256: %s`, buf.String(), sha256)\n\t\t},\n\t})\n\n\ttemplateObject, err := t.ParseFiles(templateFile)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr = templateObject.Execute(buf, values)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tkrewFile, err := ioutil.TempFile(\"\", \"krew-\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\terr = ioutil.WriteFile(krewFile.Name(), buf.Bytes(), 0644)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tprocessedTemplate := buf.Bytes()\n\tpluginName, err := krew.GetPluginName(krewFile.Name())\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\treturn pluginName, processedTemplate, nil\n}", "func Process(tmpl string, data *CheckVATPost, w io.Writer) error {\n\tt := template.Must(template.New(\"check-vat-request\").Parse(tmpl))\n\n\t// send the template to whatever writer is provided.\n\treturn t.Execute(w, data)\n}", "func (ac *attackcost) AttackCost(w http.ResponseWriter, r *http.Request) {\n\tprice := 24.42\n\tif ac.xcBot != nil {\n\t\tif rate := ac.xcBot.Conversion(1.0); rate != nil {\n\t\t\tprice = rate.Value\n\t\t}\n\t}\n\n\tac.reorgLock.Lock()\n\n\tstr, err := ac.templates.ExecTemplateToString(\"attackcost\", struct {\n\t\t*web.CommonPageData\n\t\tHashRate float64\n\t\tHeight int64\n\t\tDCRPrice float64\n\t\tTicketPrice float64\n\t\tTicketPoolSize int64\n\t\tTicketPoolValue float64\n\t\tCoinSupply int64\n\t}{\n\t\tCommonPageData: ac.commonData(r),\n\t\tHashRate: ac.hashrate,\n\t\tHeight: ac.height,\n\t\tDCRPrice: price,\n\t\tTicketPrice: ac.ticketPrice,\n\t\tTicketPoolSize: ac.ticketPoolSize,\n\t\tTicketPoolValue: ac.ticketPoolValue,\n\t\tCoinSupply: ac.coinSupply,\n\t})\n\tac.reorgLock.Unlock()\n\n\tif err != nil {\n\t\tlog.Errorf(\"Template execute failure: %v\", err)\n\t\tac.StatusPage(w, r, web.DefaultErrorCode, web.DefaultErrorMessage, \"\", web.ExpStatusError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.WriteHeader(http.StatusOK)\n\tif _, err = io.WriteString(w, str); err != nil {\n\t\tlog.Error(err)\n\t}\n}", "func (s *ValidateService) buildURL() (string, url.Values, error) {\n\tvar err error\n\tvar path string\n\t// Build URL\n\tif len(s.index) > 0 && len(s.typ) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/{type}/_validate/query\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t\t\"type\": strings.Join(s.typ, \",\"),\n\t\t})\n\t} else if len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_validate/query\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else {\n\t\tpath, err = uritemplates.Expand(\"/_validate/query\", map[string]string{\n\t\t\t\"type\": strings.Join(s.typ, \",\"),\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif v := s.pretty; v != nil {\n\t\tparams.Set(\"pretty\", fmt.Sprint(*v))\n\t}\n\tif v := s.human; v != nil {\n\t\tparams.Set(\"human\", fmt.Sprint(*v))\n\t}\n\tif v := s.errorTrace; v != nil {\n\t\tparams.Set(\"error_trace\", fmt.Sprint(*v))\n\t}\n\tif len(s.filterPath) > 0 {\n\t\tparams.Set(\"filter_path\", strings.Join(s.filterPath, \",\"))\n\t}\n\tif s.explain != nil {\n\t\tparams.Set(\"explain\", fmt.Sprintf(\"%v\", *s.explain))\n\t}\n\tif s.rewrite != nil {\n\t\tparams.Set(\"rewrite\", fmt.Sprintf(\"%v\", *s.rewrite))\n\t}\n\tif s.allShards != nil {\n\t\tparams.Set(\"all_shards\", fmt.Sprintf(\"%v\", *s.allShards))\n\t}\n\tif s.defaultOperator != \"\" {\n\t\tparams.Set(\"default_operator\", s.defaultOperator)\n\t}\n\tif v := s.lenient; v != nil {\n\t\tparams.Set(\"lenient\", fmt.Sprint(*v))\n\t}\n\tif s.q != \"\" {\n\t\tparams.Set(\"q\", s.q)\n\t}\n\tif v := s.analyzeWildcard; v != nil {\n\t\tparams.Set(\"analyze_wildcard\", fmt.Sprint(*v))\n\t}\n\tif s.analyzer != \"\" {\n\t\tparams.Set(\"analyzer\", s.analyzer)\n\t}\n\tif s.df != \"\" {\n\t\tparams.Set(\"df\", s.df)\n\t}\n\tif v := s.allowNoIndices; v != nil {\n\t\tparams.Set(\"allow_no_indices\", fmt.Sprint(*v))\n\t}\n\tif s.expandWildcards != \"\" {\n\t\tparams.Set(\"expand_wildcards\", s.expandWildcards)\n\t}\n\tif v := s.ignoreUnavailable; v != nil {\n\t\tparams.Set(\"ignore_unavailable\", fmt.Sprint(*v))\n\t}\n\treturn path, params, nil\n}", "func main() {\n\tvar template string\n\tvar network string\n\tvar generate bool\n\tvar showVer bool\n\tflag.StringVar(&template, \"t\", \"\",\"template\")\n\tflag.StringVar(&network, \"n\",defaultNetwork ,\"network [mainnet|testnet|0.9testnet|mixnet|privnet]\")\n\tflag.BoolVar(&generate, \"new\", false, \"generate new address\")\n\tflag.BoolVar(&showVer, \"version\", false, \"show version\")\n\tflag.Parse()\n\tif showVer {\n\t\tversion();\n\t\tos.Exit(0);\n\t}\n\tp, err := getParams(network);\n\texitIfErr(err)\n\tif template == \"\" {\n\t\ttemplate = genTemplateByParams(p,network)\n\t}\n\taddr, err := getAddr(template,p,generate)\n\texitIfErr(err)\n\tfmt.Printf(\" network = %s \\n\", network)\n\tfmt.Printf(\"template = %s \\n\", template)\n\tfmt.Printf(\" addr = %v \\n\", string(addr));\n}", "func Validate(c *gophercloud.ServiceClient, opts ValidateOptsBuilder) ValidateResult {\n\tvar res ValidateResult\n\n\treqBody, err := opts.ToStackTemplateValidateMap()\n\tif err != nil {\n\t\tres.Err = err\n\t\treturn res\n\t}\n\n\t_, res.Err = c.Post(validateURL(c), reqBody, &res.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\treturn res\n}", "func (tr *TerraformResource) Url(platform Platform) string {\n\treplacer := strings.NewReplacer(\"${name}\", tr.Name, \"${version}\", tr.Version, \"${os}\", platform.Os, \"${arch}\", platform.Arch)\n\turl := tr.UrlTemplate\n\tif url == \"\" {\n\t\turl = HashicorpUrlTemplate\n\t}\n\n\treturn replacer.Replace(url)\n}", "func (r EstimateTemplateCostRequest) Send(ctx context.Context) (*EstimateTemplateCostResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &EstimateTemplateCostResponse{\n\t\tEstimateTemplateCostOutput: r.Request.Data.(*EstimateTemplateCostOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func CreateReportTargetURL(templateText string, params ReportParams) string {\n\ttemplateData, err := util.ToObjectMap(params)\n\tif err != nil {\n\t\tlog.Logger().WithError(err).Warnf(\"failed to convert git ReportParams to a map for %#v\", params)\n\t\treturn \"\"\n\t}\n\n\tfuncMap := helm.NewFunctionMap()\n\ttmpl, err := template.New(\"target_url.tmpl\").Option(\"missingkey=error\").Funcs(funcMap).Parse(templateText)\n\tif err != nil {\n\t\tlog.Logger().WithError(err).Warnf(\"failed to parse git ReportsParam template: %s\", templateText)\n\t\treturn \"\"\n\t}\n\n\tvar buf strings.Builder\n\terr = tmpl.Execute(&buf, templateData)\n\tif err != nil {\n\t\tlog.Logger().WithError(err).Warnf(\"failed to evaluate git ReportsParam template: %s due to: %s\", templateText, err.Error())\n\t\treturn \"\"\n\t}\n\treturn buf.String()\n}", "func buildURLTemplate(path string) string {\n\tpath = strings.TrimRight(path, \"*\")\n\ttemplate, start, end := \"\", -1, -1\n\tfor i := 0; i < len(path); i++ {\n\t\tif path[i] == '<' && start < 0 {\n\t\t\tstart = i\n\t\t} else if path[i] == '>' && start >= 0 {\n\t\t\tname := path[start+1 : i]\n\t\t\tfor j := start + 1; j < i; j++ {\n\t\t\t\tif path[j] == ':' {\n\t\t\t\t\tname = path[start+1 : j]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate += path[end+1:start] + \"<\" + name + \">\"\n\t\t\tend = i\n\t\t\tstart = -1\n\t\t}\n\t}\n\tif end < 0 {\n\t\ttemplate = path\n\t} else if end < len(path)-1 {\n\t\ttemplate += path[end+1:]\n\t}\n\treturn template\n}", "func buildURLTemplate(path string) string {\n\tpath = strings.TrimRight(path, \"*\")\n\ttemplate, start, end := \"\", -1, -1\n\tfor i := 0; i < len(path); i++ {\n\t\tif path[i] == '<' && start < 0 {\n\t\t\tstart = i\n\t\t} else if path[i] == '>' && start >= 0 {\n\t\t\tname := path[start+1 : i]\n\t\t\tfor j := start + 1; j < i; j++ {\n\t\t\t\tif path[j] == ':' {\n\t\t\t\t\tname = path[start+1 : j]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate += path[end+1:start] + \"<\" + name + \">\"\n\t\t\tend = i\n\t\t\tstart = -1\n\t\t}\n\t}\n\tif end < 0 {\n\t\ttemplate = path\n\t} else if end < len(path)-1 {\n\t\ttemplate += path[end+1:]\n\t}\n\treturn template\n}", "func URL(opts ...options.OptionFunc) string {\n\treturn singleFakeData(URLTag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\tu, err := i.url()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn u\n\t}, opts...).(string)\n}", "func TemplatePathURL(fullPath string) (string, string) {\n\tvar templateDirectory string\n\tconfigData := config.DefaultConfig\n\tif configData.TemplatesDirectory != \"\" && strings.HasPrefix(fullPath, configData.TemplatesDirectory) {\n\t\ttemplateDirectory = configData.TemplatesDirectory\n\t} else {\n\t\treturn \"\", \"\"\n\t}\n\n\tfinalPath := strings.TrimPrefix(strings.TrimPrefix(fullPath, templateDirectory), \"/\")\n\ttemplateURL := TemplatesRepoURL + finalPath\n\treturn finalPath, templateURL\n}", "func (config *TOTPConfig) generateURL(label string) string {\n\tsecret := config.ExportKey()\n\tu := url.URL{}\n\tv := url.Values{}\n\tu.Scheme = \"otpauth\"\n\tu.Host = \"totp\"\n\tu.Path = label\n\tv.Add(\"secret\", secret)\n\tif config.Size != totpDefaultDigits {\n\t\tv.Add(\"digits\", fmt.Sprintf(\"%d\", config.Size))\n\t}\n\n\t// If other hash algorithms become supported in Google\n\t// Authenticator, enable these.\n\t// switch {\n\t// case config.Algo == crypto.SHA256:\n\t// \tv.Add(\"algorithm\", \"SHA256\")\n\t// case config.Algo == crypto.SHA512:\n\t// \tv.Add(\"algorithm\", \"SHA512\")\n\t// }\n\n\tif config.Provider != \"\" {\n\t\tv.Add(\"provider\", config.Provider)\n\t}\n\n\tu.RawQuery = v.Encode()\n\treturn u.String()\n}", "func (o BuildSpecSourceOutput) Url() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BuildSpecSource) string { return v.Url }).(pulumi.StringOutput)\n}", "func ValidateIgnitionTemplate(tmpl string, metadata map[string]string, ipam *IPAMConfig) error {\n\tmc := NewMachine(MachineSpec{\n\t\tSerial: \"1234abcd\",\n\t\tRack: 1,\n\t})\n\tu, err := url.Parse(\"http://localhost:10080\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tipam.GenerateIP(mc)\n\tign, err := RenderIgnition(tmpl, &IgnitionParams{Metadata: metadata, MachineSpec: mc.Spec, MyURL: u})\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, rpt, err := ignition.Parse([]byte(ign))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(rpt.Entries) > 0 {\n\t\treturn errors.New(rpt.String())\n\t}\n\treturn nil\n}", "func checkUrl(writer http.ResponseWriter, request *http.Request) {\n\tvars := mux.Vars(request)\n\thostname := vars[\"hostname\"]\n\tquerypath := vars[\"querypath\"]\n\n\tresponse := APIResponse{}\n\terr := utils.ValidateUrl(hostname)\n\tif err != nil {\n\t\tresponse.BadRequest(err)\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\tdecodedPath, err := utils.URLDecode(querypath)\n\tif err != nil {\n\t\tresponse.BadRequest(err)\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\t// Generate URL service for querying the URL\n\turlService, err := services.NewUrlService(hostname, decodedPath, config.DBType, config.CacheType)\n\n\tif err != nil {\n\t\tutils.LogError(utils.LogFields{\"hostname\": hostname, \"path\": decodedPath}, err, \"Error getting URL\")\n\t\tresponse.InternalError(errors.New(\"An error occurred\"))\n\t\thttp_respond(response, writer)\n\t\treturn\n\t}\n\n\turlStatus, err := urlService.FindUrl()\n\tif err != nil {\n\t\tutils.LogError(utils.LogFields{\"hostname\": hostname, \"path\": decodedPath}, err, \"Error getting URL\")\n\t\tresponse.InternalError(errors.New(\"An error occurred\"))\n\t} else {\n\t\tresponse.Success(urlStatus)\n\t}\n\n\thttp_respond(response, writer)\n}", "func (i Internet) URL() string {\n\turl := i.Faker.RandomStringElement(urlFormats)\n\n\t// {{domain}}\n\turl = strings.Replace(url, \"{{domain}}\", i.Domain(), 1)\n\n\t// {{slug}}\n\turl = strings.Replace(url, \"{{slug}}\", i.Slug(), 1)\n\n\treturn url\n}", "func BuildURL(path string, geometry string, options *Options) (string, error) {\n\tsecretValues := make(url.Values)\n\textraValues := make(url.Values)\n\tg, err := ParseGeometry(geometry)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tw := \"\"\n\th := \"\"\n\n\tif g.X != 0 {\n\t\tw = strconv.Itoa(g.X)\n\t\tsecretValues.Add(\"w\", w)\n\t}\n\n\tif g.Y != 0 {\n\t\th = strconv.Itoa(g.Y)\n\t\tsecretValues.Add(\"h\", h)\n\t}\n\n\tif options.Quality != \"\" {\n\t\tsecretValues.Add(\"q\", options.Quality)\n\t\textraValues.Add(\"q\", options.Quality)\n\t}\n\tif options.Upscale != nil {\n\t\tsecretValues.Add(\"upscale\", strconv.Itoa(*options.Upscale))\n\t\textraValues.Add(\"upscale\", strconv.Itoa(*options.Upscale))\n\t}\n\n\top := options.Ops[0]\n\n\tsecretValues.Add(\"path\", path)\n\n\tfor i := range options.Ops {\n\t\tsecretValues.Add(\"op\", options.Ops[i])\n\t\tif i != 0 {\n\t\t\textraValues.Add(\"op\", options.Ops[i])\n\t\t}\n\t}\n\n\tu, err := url.Parse(options.BaseURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tu.Path = strings.Join([]string{\n\t\toptions.DefaultMethod,\n\t\tSignParams(options.SecretKey, secretValues),\n\t\top,\n\t\tfmt.Sprintf(\"%sx%s\", w, h),\n\t\tpath,\n\t}, \"/\")\n\n\tu.RawQuery = extraValues.Encode()\n\n\treturn u.String(), nil\n}", "func (a *AWSSigv4) CreateURL() string {\n\n\tqs := a.QueryString\n\tver := apisVersion[a.Svc]\n\thostname := a.Svc + \".\" + a.Region + \".\" + a.AWSDomain\n\n\turl := a.Scheme + \"://\" + hostname + a.URI\n\tif a.Method == \"GET\" {\n\t\tif qs != \"\" {\n\t\t\tqs += \"&\"\n\t\t}\n\t\tqs += \"Action=\" + kebabToCamelCase(a.Action)\n\t\tqs += \"&Version=\" + ver\n\t\turl += \"?\" + qs\n\n\t\ta.QueryString = qs\n\t}\n\n\treturn url\n}", "func constructTemplate(url string) urlMetaTemplate {\n\tcurrentIndex := 0\n\ttmplt := urlMetaTemplate{\n\t\tstartingIndices: []int{},\n\t\tendingIndices: []int{},\n\t}\n\tdelimiterLen := len(delimiter)\n\tfor {\n\t\tcurrentIndex = currentIndex + strings.Index(url[currentIndex:], delimiter)\n\t\tif currentIndex == -1 {\n\t\t\tbreak\n\t\t}\n\t\tstartIndex := currentIndex + delimiterLen\n\t\tendingIndex := strings.Index(url[startIndex:], delimiter)\n\t\tif endingIndex == -1 {\n\t\t\tbreak\n\t\t}\n\t\tendingIndex = endingIndex + startIndex - 1\n\t\ttmplt.startingIndices = append(tmplt.startingIndices, startIndex)\n\t\ttmplt.endingIndices = append(tmplt.endingIndices, endingIndex)\n\t\tcurrentIndex = endingIndex + delimiterLen + 1\n\t\tif currentIndex >= len(url)-1 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn tmplt\n}", "func (c *CaptchaGID) URL() string {\n\tif *c == \"\" || *c == \"-1\" {\n\t\treturn \"\"\n\t}\n\treturn APIEndpoints.CommunityBase.String() + \"/public/captcha.php?gid=\" + c.String()\n}", "func (h *handler) CreateURL(response http.ResponseWriter, request *http.Request) {\n\tvar body createURLRequest\n\n\tdecoder := json.NewDecoder(request.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\thttp.Error(response, \"Invalid body: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := getUniquePath(body.URL)\n\n\tlog.Infof(\"Request to shorten URL '%s'. Path assigned: '%s'\", body.URL, path)\n\n\tif err := h.store.Put(path, body.URL); err != nil {\n\t\tlog.Errorf(\"Generated path '%s' cannot be stored due to: %+v\", path, err)\n\t\thttp.Error(response, \"There was a collision with the generated path, please try again\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Location\", \"/\"+path)\n\tresponse.WriteHeader(http.StatusCreated)\n}", "func (w *Worker) Url(path string, params url.Values) string {\n\t// random choice one host for load balance\n\ti := rand.Intn(len(w.ctx.addrs))\n\taddr := w.ctx.addrs[i]\n\ts := fmt.Sprintf(\"http://%s%s\", addr, path)\n\tif params == nil {\n\t\treturn s\n\t}\n\tp := params.Encode()\n\treturn fmt.Sprintf(\"%s?%s\", s, p)\n}", "func (f stepFailure) URL() string {\n\treturn client.StepURL(f.masterName, f.builderName, f.step.Name, f.build.Number)\n}", "func URL(data ValidationData) error {\n\tv, err := helper.ToString(data.Value)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a string\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tparsed, err := url.Parse(v)\n\tif err != nil {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: \"is not a valid URL\",\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Scheme != \"http\" && parsed.Scheme != \"https\" {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid scheme '%s'\", parsed.Scheme),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\tif parsed.Host == \"\" || strings.IndexRune(parsed.Host, '\\\\') > 0 {\n\t\treturn ErrInvalid{\n\t\t\tValidationData: data,\n\t\t\tFailure: fmt.Sprintf(\"has an invalid host ('%s')\", parsed.Host),\n\t\t\tMessage: data.Message,\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ftc *FlavorTemplateController) ValidateFlavorTemplateCreateRequest(FlvrTemp hvs.FlavorTemplate, template string) (string, error) {\n\tdefaultLog.Trace(\"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Entering\")\n\tdefer defaultLog.Trace(\"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Leaving\")\n\t// Check whether the template is adhering to the schema\n\tschemaLoader := gojsonschema.NewSchemaLoader()\n\n\tvar err error\n\tif ftc.DefinitionsSchemaJSON == \"\" {\n\t\tftc.DefinitionsSchemaJSON, err = readJSON(ftc.CommonDefinitionsSchema)\n\t\tif err != nil {\n\t\t\treturn \"Unable to read the common definitions schema\", errors.Wrap(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Unable to read the file\"+consts.CommonDefinitionsSchema)\n\t\t}\n\t}\n\n\tdefinitionsSchema := gojsonschema.NewStringLoader(ftc.DefinitionsSchemaJSON)\n\n\tif ftc.TemplateSchemaJSON == \"\" {\n\t\tftc.TemplateSchemaJSON, err = readJSON(ftc.FlavorTemplateSchema)\n\t\tif err != nil {\n\t\t\treturn \"Unable to read the template schema\", errors.Wrap(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Unable to read the file\"+consts.FlavorTemplateSchema)\n\t\t}\n\t}\n\n\tflvrTemplateSchema := gojsonschema.NewStringLoader(ftc.TemplateSchemaJSON)\n\tschemaLoader.AddSchemas(definitionsSchema)\n\n\tschema, err := schemaLoader.Compile(flvrTemplateSchema)\n\tif err != nil {\n\t\treturn \"Unable to compile the template\", errors.Wrap(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Unable to compile the schemas\")\n\t}\n\n\tdocumentLoader := gojsonschema.NewStringLoader(template)\n\n\tresult, err := schema.Validate(documentLoader)\n\tif err != nil {\n\t\treturn \"Unable to validate the template\", errors.Wrap(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Unable to validate the template\")\n\t}\n\n\tvar errorMsg string\n\tif !result.Valid() {\n\t\tfor _, desc := range result.Errors() {\n\t\t\terrorMsg = errorMsg + fmt.Sprintf(\"- %s\\n\", desc)\n\t\t}\n\t\treturn errorMsg, errors.New(\"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() The provided template is not valid\" + errorMsg)\n\t}\n\n\tdefaultLog.Infof(\"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() The provided template with template ID %s is valid\", FlvrTemp.ID)\n\n\t//Validation the syntax of the conditions\n\ttempDoc, err := jsonquery.Parse(strings.NewReader(\"{}\"))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Unable to parse json query\")\n\t}\n\n\tfor _, condition := range FlvrTemp.Condition {\n\t\t_, err := jsonquery.Query(tempDoc, condition)\n\t\tif err != nil {\n\t\t\treturn \"Invalid syntax in condition statement\", errors.Wrapf(err, \"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Invalid syntax in condition : %s\", condition)\n\t\t}\n\t}\n\n\t//Check whether each pcr index is associated with not more than one bank.\n\tpcrMap := make(map[*hvs.FlavorPart][]hvs.PCR)\n\tflavorParts := []*hvs.FlavorPart{FlvrTemp.FlavorParts.Platform, FlvrTemp.FlavorParts.OS, FlvrTemp.FlavorParts.HostUnique}\n\tfor _, flavorPart := range flavorParts {\n\t\tif flavorPart != nil {\n\t\t\tif _, ok := pcrMap[flavorPart]; !ok {\n\t\t\t\tvar pcrs []hvs.PCR\n\t\t\t\tfor _, pcrRule := range flavorPart.PcrRules {\n\t\t\t\t\tpcrs = append(pcrs, pcrRule.Pcr)\n\t\t\t\t}\n\t\t\t\tpcrMap[flavorPart] = pcrs\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, pcrList := range pcrMap {\n\t\ttemp := make(map[int]bool)\n\t\tfor _, pcr := range pcrList {\n\t\t\tif _, ok := temp[pcr.Index]; !ok {\n\t\t\t\ttemp[pcr.Index] = true\n\t\t\t} else {\n\t\t\t\treturn \"Template has duplicate banks for same PCR index\", errors.New(\"controllers/flavortemplate_controller:validateFlavorTemplateCreateRequest() Template has duplicate banks for same PCR index\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func genObjURL(isSecure, isXML bool) (s string) {\n\tif isSecure || !isXML { // Using JSON requires HTTPS: \"SSL is required to perform this operation.\"\n\t\ts = \"https://\"\n\t} else {\n\t\ts = \"http://\"\n\t}\n\tif isXML {\n\t\ts += fmt.Sprintf(\"storage.googleapis.com/%s/%s\", gcsBck, gcsObjXML)\n\t} else {\n\t\t// Reformat object name from XML to JSON API requirements.\n\t\tgcsObjJSON := strings.ReplaceAll(gcsObjXML, \"/\", \"%2F\")\n\t\ts += fmt.Sprintf(\"www.googleapis.com/storage/v1/b/%s/o/%s?alt=media\", gcsBck, gcsObjJSON)\n\t}\n\treturn s\n}", "func (a *Api) buildPreview(res http.ResponseWriter, req *http.Request, vars map[string]string) {\n\t//Determine the email template:\n\tvar templateName models.TemplateName\n\tlang := \"en\"\n\tswitch vars[\"template\"] {\n\tcase \"careteam_invitation\":\n\t\ttemplateName = models.TemplateNameCareteamInvite\n\tcase \"medicalteam_patient_invitation\":\n\t\ttemplateName = models.TemplateNameMedicalteamPatientInvite\n\tcase \"medicalteam_monitoring_invitation\":\n\t\ttemplateName = models.TemplateNameMedicalteamMonitoringInvite\n\tcase \"medicalteam_invitation\":\n\t\ttemplateName = models.TemplateNameMedicalteamInvite\n\tcase \"medicalteam_do_admin\":\n\t\ttemplateName = models.TemplateNameMedicalteamDoAdmin\n\tcase \"medicalteam_remove\":\n\t\ttemplateName = models.TemplateNameMedicalteamRemove\n\tcase \"no_account\":\n\t\ttemplateName = models.TemplateNameNoAccount\n\tcase \"password_reset\":\n\t\ttemplateName = models.TemplateNamePasswordReset\n\tcase \"patient_password_reset\":\n\t\ttemplateName = models.TemplateNamePatientPasswordReset\n\tcase \"patient_password_info\":\n\t\ttemplateName = models.TemplateNamePatientPasswordInfo\n\tcase \"patient_information\":\n\t\ttemplateName = models.TemplateNamePatientInformation\n\tcase \"patient_pin_reset\":\n\t\ttemplateName = models.TemplateNamePatientPinReset\n\tcase \"signup_confirmation\":\n\t\ttemplateName = models.TemplateNameSignup\n\tcase \"signup_clinic_confirmation\":\n\t\ttemplateName = models.TemplateNameSignupClinic\n\tcase \"signup_custodial_confirmation\":\n\t\ttemplateName = models.TemplateNameSignupCustodial\n\tcase \"signup_custodial_clinic_confirmation\":\n\t\ttemplateName = models.TemplateNameSignupCustodialClinic\n\tcase \"app_prescription\":\n\t\ttemplateName = models.TemplateNameAppPrescription\n\tdefault:\n\t\tlog.Printf(\"Unknown template %s\", vars[\"template\"])\n\t\ts := status.NewApiStatus(400, \"Incorrect template name\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlangs, ok := req.URL.Query()[\"lang\"]\n\tif ok && len(langs[0]) >= 2 {\n\t\tlang = langs[0]\n\t}\n\temail, err := a.generateEmail(templateName, lang)\n\tif err != nil {\n\t\tlog.Println(\"Error generating email preview\", err)\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, err.Error())\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t} else {\n\t\tres.Header().Set(\"content-type\", \"text/html\")\n\t\tres.WriteHeader(200)\n\t\tres.Write([]byte(email))\n\t}\n\n\treturn\n}", "func (c *client) createURL(urlPath string, query url.Values) string {\n\tu := c.endpoint\n\tu.Path = urlPath\n\tif query != nil {\n\t\tu.RawQuery = query.Encode()\n\t}\n\treturn u.String()\n}", "func Template(templatePath string) Result {\n\tconfig := config.GetLoadedConfig()\n\tfullPath := filepath.Join(config.GetTemplatePath(), templatePath)\n\n\tif f, err := os.Open(fullPath); err != nil {\n\t\tlog.Printf(\"could not open template file %s\\n\", fullPath)\n\t} else {\n\t\tif bytes, err := io.ReadAll(f); err != nil {\n\t\t\tlog.Printf(\"could not read template file %s\\n\", fullPath)\n\t\t} else {\n\t\t\treturn StringResult(bytes)\n\t\t}\n\t}\n\n\treturn StringResult(\"\")\n}", "func (o ApiLicenseOutput) Url() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiLicense) *string { return v.Url }).(pulumi.StringPtrOutput)\n}", "func (a *Api) generateEmail(templateName models.TemplateName, lang string) (string, error) {\n\n\tlog.Printf(\"trying preview with template '%s' with language '%s'\", templateName, lang)\n\n\tcontent := map[string]string{\n\t\t\"Key\": \"123456789123456789123456789123456789\",\n\t\t\"Email\": \"[email protected]\",\n\t\t\"EncodedEmail\": url.QueryEscape(\"[email protected]\"),\n\t\t\"FullName\": \"John Doe\",\n\t\t\"PatientName\": \"John Doe\",\n\t\t\"WebPath\": \"login\",\n\t\t\"ShortKey\": \"12345678\",\n\t\t\"Duration\": \"1\",\n\t\t\"OTP\": \"165236984\",\n\t\t\"SupportEmail\": a.Config.SupportURL,\n\t\t\"MedicalteamName\": \"Team CHU\",\n\t\t\"MedicalteamAddress\": \"Bd de la chantourne, 38000 Grenoble\",\n\t\t\"MedicalteamPhone\": \"33 4 760 101\",\n\t\t\"MedicalteamIentification\": \"123-456-789\",\n\t\t\"CreatorName\": \"John Doe\",\n\t\t\"Language\": \"en\",\n\t\t\"Product\": \"DBLG2\",\n\t\t\"PrescriptionCode\": \"123456789\",\n\t\t\"Invitor\": \"John Doe\",\n\t}\n\t// Content collection is here to replace placeholders in template body/content\n\tcontent[\"WebURL\"] = a.Config.WebURL\n\tcontent[\"SupportURL\"] = a.Config.SupportURL\n\tcontent[\"AssetURL\"] = a.Config.AssetURL\n\tcontent[\"PatientPasswordResetURL\"] = a.Config.PatientPasswordResetURL\n\n\t// Retrieve the template from all the preloaded templates\n\tvar template models.Template\n\tvar ok bool\n\ttemplate, ok = a.templates[templateName]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"Unknown template type %s\", templateName)\n\t}\n\n\t// Get localized subject of email\n\tsubject, body, err := template.Execute(content, lang)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error executing email template '%s'\", err)\n\t}\n\tresult := fmt.Sprintf(\"<div align=\\\"center\\\" id=\\\"subject\\\">Subject: %s \\n</div><div id=\\\"body\\\">%s</div>\", subject, body)\n\treturn result, nil\n}", "func URLGen(uri string) string {\n\tconfig, err := generalConfigLoad()\n\tif err != nil {\n\t\tfmt.Println(\"URLGen:\", err)\n\t\tos.Exit(1)\n\t}\n\turl := config.Scheme + \"://\" + config.Dstip + uri\n\n\treturn url\n}", "func renderValidationForm(w http.ResponseWriter, r *http.Request, errMsg string) {\n\ttmpl := template.New(\"layout\")\n\ttmpl, err := tmpl.Parse(templates.Layout)\n\tif err != nil {\n\t\tlog.ShowWrite(\"[Error] failed to parse html layout page: %s\", err.Error())\n\t\tfail(w, r, http.StatusInternalServerError, \"something went wrong\")\n\t\treturn\n\t}\n\ttmpl, err = tmpl.Parse(templates.PubValidate)\n\tif err != nil {\n\t\tlog.ShowWrite(\"[Error] failed to render public validation page: %s\", err.Error())\n\t\tfail(w, r, http.StatusInternalServerError, \"something went wrong\")\n\t\treturn\n\t}\n\tyear, _, _ := time.Now().Date()\n\tloggedUsername := getLoggedUserName(r)\n\tsrvcfg := config.Read()\n\tdata := struct {\n\t\tGinURL string\n\t\tCurrentYear int\n\t\tErrorMessage string\n\t\tUserName string\n\t}{\n\t\tsrvcfg.GINAddresses.WebURL,\n\t\tyear,\n\t\terrMsg,\n\t\tloggedUsername,\n\t}\n\terr = tmpl.Execute(w, &data)\n\tif err != nil {\n\t\tlog.ShowWrite(\"[Error] failed to parse data to public validation page: %s\", err.Error())\n\t\tfail(w, r, http.StatusInternalServerError, \"something went wrong\")\n\t}\n}", "func (cr *Core) Cost(req CostRequest) (res CostResponse, err error) {\n\turlPath := \"cost\"\n\theaders := map[string]string{\n\t\t\"key\": cr.Client.APIKey,\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t}\n\terr = cr.CallPro(fasthttp.MethodPost, urlPath, headers, bytes.NewBufferString(StructToMap(&req).Encode()), &res)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func Provide(cfg config.Config) (string, error) {\n\tsanitizedName := cfg.Template\n\tif strings.HasPrefix(cfg.Template, \"https\") {\n\t\tsanitizedName = sanitizedName[len(\"https://\")-1:]\n\t\tmyPath := filepath.Join(cfg.TmpDir, sanitizedName)\n\t\tif err := git.CloneOrPull(cfg.Template, myPath); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn myPath, nil\n\t}\n\n\treturn cfg.Template, nil\n}", "func Generate(w http.ResponseWriter, r *http.Request) {\n\n\tvar js []byte\n\n\tdefer func() {\n\t\tw.Write(js)\n\t}()\n\n\t// Client POST request\n\treq := models.URL{}\n\n\tif err := json.NewDecoder().DecodeReader(r.Body, &req); err != nil {\n\t\tutils.Error(r, err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjs, _ = json.Marshal(httpError(http.StatusBadRequest, \"Couldn't decode json.\"))\n\n\t\treturn\n\t}\n\n\t// Verify URL\n\tif ok, err := utils.IsURL(req.LongURL); !ok || err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tif err != nil {\n\t\t\tutils.Error(r, err)\n\t\t\tjs, _ = json.Marshal(httpError(http.StatusBadRequest, err.Error()))\n\n\t\t\treturn\n\t\t}\n\n\t\tjs, _ = json.Marshal(httpError(http.StatusBadRequest, fmt.Sprintf(\"%s is invalid.\", req.LongURL)))\n\n\t\treturn\n\t}\n\n\t// Verify if URL is on the blacklist\n\tif ban, err := utils.IsOnBlackList(req.LongURL); ban || err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tif err != nil {\n\t\t\tutils.Error(r, err)\n\t\t\tjs, _ = json.Marshal(httpError(http.StatusBadRequest, err.Error()))\n\n\t\t\treturn\n\t\t}\n\n\t\tjs, _ = json.Marshal(httpError(http.StatusBadRequest, fmt.Sprintf(\"%s is on the blacklist.\", req.LongURL)))\n\n\t\treturn\n\t}\n\n\t// Trim trailing slash\n\tif strings.HasSuffix(req.LongURL, \"/\") {\n\t\treq.LongURL = req.LongURL[0 : len(req.LongURL)-1]\n\t}\n\n\t// Reorder url query for consistency\n\treq.LongURL = utils.ReOrderQuery(req.LongURL)\n\n\thash := fmt.Sprintf(\"%x\", sha256.Sum256([]byte(req.LongURL)))\n\n\tresp, _ := models.FindURL(bson.M{\"hash\": hash})\n\tif resp.LongURL != \"\" {\n\t\tresp.TargetURL = utils.Conf.Server.Base + resp.ID\n\t\tjs, _ = json.Marshal(&resp)\n\n\t\treturn\n\t}\n\n\tcounter, _ := models.FindAndModify(bson.M{\"$inc\": bson.M{\"sequence\": 1}})\n\n\treq.ReadyToInsert(hash, &counter)\n\n\terr := models.InsertURL(req)\n\tif err != nil {\n\t\tutils.Error(r, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjs, _ = json.Marshal(httpError(http.StatusInternalServerError, err.Error()))\n\n\t\treturn\n\t}\n\n\treq.TargetURL = utils.Conf.Server.Base + req.ID\n\n\tjs, _ = json.Marshal(&req)\n}", "func (t *Target) URL() *url.URL {\n\tparams := url.Values{}\n\n\tfor k, v := range t.params {\n\t\tparams[k] = make([]string, len(v))\n\t\tcopy(params[k], v)\n\t}\n\tt.labels.Range(func(l labels.Label) {\n\t\tif !strings.HasPrefix(l.Name, model.ParamLabelPrefix) {\n\t\t\treturn\n\t\t}\n\t\tks := l.Name[len(model.ParamLabelPrefix):]\n\n\t\tif len(params[ks]) > 0 {\n\t\t\tparams[ks][0] = l.Value\n\t\t} else {\n\t\t\tparams[ks] = []string{l.Value}\n\t\t}\n\t})\n\n\treturn &url.URL{\n\t\tScheme: t.labels.Get(model.SchemeLabel),\n\t\tHost: t.labels.Get(model.AddressLabel),\n\t\tPath: t.labels.Get(model.MetricsPathLabel),\n\t\tRawQuery: params.Encode(),\n\t}\n}", "func (input *BeegoInput) URL() string {\n\treturn input.Context.Request.URL.Path\n}", "func validateHTTP(url string) error {\n\treq := []byte(`{\"res\":\"PASS\"}`)\n\terr := sendHTTP(url, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get response: %v\", err)\n\t}\n\toutput, err := ioutil.ReadFile(outputFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"reading output file: %v\", err)\n\t}\n\tif string(output) != string(req) {\n\t\treturn fmt.Errorf(\"unexpected HTTP data: got %s, want %s\", output, req)\n\t}\n\treturn nil\n}", "func (s *NodesInfoService) buildURL() (string, url.Values, error) {\n\t// Build URL\n\tpath, err := uritemplates.Expand(\"/_nodes/{node_id}/{metric}\", map[string]string{\n\t\t\"node_id\": strings.Join(s.nodeId, \",\"),\n\t\t\"metric\": strings.Join(s.metric, \",\"),\n\t})\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif s.flatSettings != nil {\n\t\tparams.Set(\"flat_settings\", fmt.Sprintf(\"%v\", *s.flatSettings))\n\t}\n\tif s.human != nil {\n\t\tparams.Set(\"human\", fmt.Sprintf(\"%v\", *s.human))\n\t}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", \"1\")\n\t}\n\treturn path, params, nil\n}", "func (conf FileConfiguration) URL() string {\n\treturn \"\"\n}", "func CheckHTTP(url string, redirect, insecure bool, host string, timeout int, format, path, expectedValue, expression string) (string, int) {\n\tconst checkName = \"CheckHttp\"\n\tvar retCode int\n\tvar msg string\n\n\tacceptText, err := getAcceptText(format)\n\tif err != nil {\n\t\tmsg, _ = resultMessage(checkName, statusTextCritical, fmt.Sprintf(\"The format (--format) \\\"%s\\\" is not valid. The only valid value is \\\"json\\\".\", format))\n\n\t\treturn msg, 2\n\t}\n\n\tstatus, body, _ := statusCode(url, insecure, timeout, acceptText, host)\n\n\tretCode, responseStateText := evaluateStatusCode(status, redirect)\n\tresponseCode := strconv.Itoa(status)\n\n\tvar checkMsg = \"\"\n\tif retCode == 0 && len(format) > 0 && len(path) > 0 {\n\t\tvar queryValue string\n\n\t\tswitch {\n\t\tcase format == \"json\":\n\t\t\texpectedValueLen := len(expectedValue)\n\t\t\texpressionLen := len(expression)\n\n\t\t\tvalue := gojsonq.New().JSONString(body).Find(path)\n\n\t\t\tif value == nil {\n\t\t\t\tretCode = 2\n\t\t\t\tresponseStateText = statusTextCritical\n\t\t\t\tcheckMsg = fmt.Sprintf(\". No entry at path %s\", path)\n\t\t\t} else if expectedValueLen > 0 && expressionLen > 0 {\n\t\t\t\tretCode = 2\n\t\t\t\tresponseStateText = statusTextCritical\n\t\t\t\tcheckMsg = fmt.Sprintf(\". Both --expectedValue and --expression given but only one is used\")\n\t\t\t} else if expectedValueLen > 0 {\n\t\t\t\tqueryValue = fmt.Sprintf(\"%v\", value)\n\t\t\t\tretCode, responseStateText, checkMsg = evaluateExpectedValue(queryValue, expectedValue, path)\n\t\t\t} else if expressionLen > 0 {\n\t\t\t\tretCode, responseStateText, checkMsg = evaluateExpression(value, expression, path)\n\t\t\t} else {\n\t\t\t\tretCode = 2\n\t\t\t\tresponseStateText = statusTextCritical\n\t\t\t\tcheckMsg = fmt.Sprintf(\". --expectedValue or --expression not given\")\n\t\t\t}\n\t\t}\n\t}\n\n\tmsg, _ = resultMessage(checkName, responseStateText, fmt.Sprintf(\"Url %s responded with %s%s\", url, responseCode, checkMsg))\n\n\treturn msg, retCode\n}", "func (r AssetRequest) URL() string {\n\treturn \"v3/asset\"\n}", "func resourceObjectstorageTempurlV1Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\tconfig := meta.(*Config)\n\tobjectStorageClient, err := config.ObjectStorageV1Client(GetRegion(d, config))\n\tif err != nil {\n\t\treturn diag.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tmethod := objects.GET\n\tswitch d.Get(\"method\") {\n\tcase \"post\":\n\t\tmethod = objects.POST\n\t\t// gophercloud doesn't have support for PUT yet,\n\t\t// although it's a valid method for swift\n\t\t//case \"put\":\n\t\t//\tmethod = objects.PUT\n\t}\n\n\tturlOptions := objects.CreateTempURLOpts{\n\t\tMethod: method,\n\t\tTTL: d.Get(\"ttl\").(int),\n\t\tSplit: d.Get(\"split\").(string),\n\t}\n\n\tcontainerName := d.Get(\"container\").(string)\n\tobjectName := d.Get(\"object\").(string)\n\n\tlog.Printf(\"[DEBUG] Create temporary url Options: %#v\", turlOptions)\n\n\turl, err := objects.CreateTempURL(objectStorageClient, containerName, objectName, turlOptions)\n\tif err != nil {\n\t\treturn diag.Errorf(\"Unable to generate a temporary url for the object %s in container %s: %s\",\n\t\t\tobjectName, containerName, err)\n\t}\n\n\tlog.Printf(\"[DEBUG] URL Generated: %s\", url)\n\n\t// Set the URL and Id fields.\n\thasher := md5.New()\n\thasher.Write([]byte(url))\n\td.SetId(hex.EncodeToString(hasher.Sum(nil)))\n\td.Set(\"url\", url)\n\treturn nil\n}", "func templateHandler(w http.ResponseWriter, r *http.Request) {\n\t//fmt.Fprint(w, \"Guessing Game! \")\n\tm := Data{Message: \"Guess a number between 1 and 20: \"}\n\t//g.Execute(w, Data{Message: \"Guess a number between 1 and 20\"})\n\n\tt, _ := template.ParseFiles(\"guess.html\")\n\n\tt.Execute(w, m)\n}", "func (t *TestRuntime) URL() string {\n\tif t.url != \"\" {\n\t\t// fast path once it has been computed\n\t\treturn t.url\n\t}\n\n\tt.urlMtx.Lock()\n\tdefer t.urlMtx.Unlock()\n\n\t// check again in the lock, it might have changed on us..\n\tif t.url != \"\" {\n\t\treturn t.url\n\t}\n\n\taddrs := t.Runtime.Addrs()\n\tif len(addrs) == 0 {\n\t\treturn \"\"\n\t}\n\t// Just pick the first one, if a test was configured with >1 they\n\t// will need to determine the URLs themselves.\n\taddr := addrs[0]\n\n\tparsed, err := t.AddrToURL(addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tt.url = parsed\n\n\treturn t.url\n}", "func getURL(tl string) string {\n\treturn fmt.Sprintf(\"https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=%s&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e\", tl)\n}", "func (s *cachedURLShortenerService) Create(fullUrl string) (URL, error) {\n\turl, err := s.service.Create(fullUrl)\n\tif err != nil {\n\t\treturn URL{}, err\n\t}\n\n\tgo func() {\n\t\ts.cache.Cache(url)\n\t}()\n\n\treturn url, nil\n}", "func (ie *CommonIE) ValidURL() string {\n\treturn ie.VALIDURL\n}", "func Validator(request events.APIGatewayProxyRequest) (bool, string, int, searchutil.SearchPeriod) {\n\tif request.HTTPMethod != \"GET\" {\n\t\treturn false, \"{\\\"msg\\\": \\\"only HTTP GET is allowed on this resource\\\"}\", -1, searchutil.Day\n\t}\n\tnumber, pres := request.QueryStringParameters[\"number\"]\n\tif !pres {\n\t\tnumber = \"10\"\n\t}\n\tnum, _ := strconv.Atoi(number)\n\tif num <= 0 {\n\t\treturn false, \"{\\\"msg\\\": \\\"number nmust be greater than 0\\\"}\", -1, searchutil.Day\n\t}\n\tduration, _ := request.QueryStringParameters[\"duration\"]\n\treturn true, \"\", num, ConvertDurationToSearchPeriod(duration)\n}", "func (input *Input) URL() string {\n\treturn input.Context.Request.URL.Path\n}", "func (op OperationRequest) BuildURL() (endpoint string, err error) {\n\tnParams := countParams(op.ForAccount, op.ForLedger, op.ForLiquidityPool, op.forOperationID, op.ForTransaction)\n\n\tif nParams > 1 {\n\t\treturn endpoint, errors.New(\"invalid request: too many parameters\")\n\t}\n\n\tif op.endpoint == \"\" {\n\t\treturn endpoint, errors.New(\"internal error, endpoint not set\")\n\t}\n\n\tendpoint = op.endpoint\n\tif op.ForAccount != \"\" {\n\t\tendpoint = fmt.Sprintf(\"accounts/%s/%s\", op.ForAccount, op.endpoint)\n\t}\n\tif op.ForClaimableBalance != \"\" {\n\t\tendpoint = fmt.Sprintf(\"claimable_balances/%s/%s\", op.ForClaimableBalance, op.endpoint)\n\t}\n\tif op.ForLedger > 0 {\n\t\tendpoint = fmt.Sprintf(\"ledgers/%d/%s\", op.ForLedger, op.endpoint)\n\t}\n\tif op.ForLiquidityPool != \"\" {\n\t\tendpoint = fmt.Sprintf(\"liquidity_pools/%s/%s\", op.ForLiquidityPool, op.endpoint)\n\t}\n\tif op.forOperationID != \"\" {\n\t\tendpoint = fmt.Sprintf(\"operations/%s\", op.forOperationID)\n\t}\n\tif op.ForTransaction != \"\" {\n\t\tendpoint = fmt.Sprintf(\"transactions/%s/%s\", op.ForTransaction, op.endpoint)\n\t}\n\n\tqueryParams := addQueryParams(cursor(op.Cursor), limit(op.Limit), op.Order,\n\t\tincludeFailed(op.IncludeFailed), join(op.Join))\n\tif queryParams != \"\" {\n\t\tendpoint = fmt.Sprintf(\"%s?%s\", endpoint, queryParams)\n\t}\n\n\t_, err = url.Parse(endpoint)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"failed to parse endpoint\")\n\t}\n\n\treturn endpoint, err\n}", "func (s EstimateTemplateCostInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func populateTemplate(points *Points, apikey *string) []byte {\n\t// func populateTemplate(points *Points, apikey *string) []byte {\n\tvar page Page\n\tvar convexData string\n\tvar heatmap string\n\tvar driveData string\n\thigh, low := 0, 0\n\tif apikey != nil {\n\t\tpage.Apikey = apikey\n\t} else {\n\t\tpage.Apikey = nil\n\t}\n\tvar tplBuffer bytes.Buffer\n\tconvexPoints := findConvexHull(*points)\n\tfor _, point := range convexPoints {\n\t\tconvexData += fmt.Sprintf(\"(new google.maps.LatLng(%g, %g)), \", point.Y, point.X)\n\t}\n\tfor _, point := range *points {\n\t\theatmap += fmt.Sprintf(\"{location: new google.maps.LatLng(%g, %g), weight: %f}, \", point.Y, point.X, (float64(point.Dbm)/10.0)+9.0)\n\t\tsigCheck(&high, &low, point.Dbm)\n\t}\n\tfor _, point := range *points {\n\t\tdriveData += fmt.Sprintf(\"(new google.maps.LatLng(%g, %g)), \", point.Y, point.X)\n\t}\n\tpage.Lat = (*points)[0].Y\n\tpage.Lng = (*points)[0].X\n\tpage.PathLength = len(*points)\n\tpage.ConvexHull = template.JS(\"[\" + convexData[:len(convexData)-2] + \"]\")\n\tpage.Heatmap = template.JS(\"[\" + heatmap[:len(heatmap)-2] + \"]\")\n\tpage.Drive = template.JS(\"[\" + driveData[:len(driveData)-2] + \"]\")\n\tpage.HighDB = template.JS(fmt.Sprintf(\"%v\", high))\n\tpage.LowDB = template.JS(fmt.Sprintf(\"%v\", low))\n\tt, err := template.New(\"webpage\").Parse(tpl)\n\tcheckError(err)\n\terr = t.Execute(&tplBuffer, page)\n\tcheckError(err)\n\treturn tplBuffer.Bytes()\n}", "func (p *para) checkUrl(s string) error {\n\tr := regexp.MustCompile(`google\\.com\\/(\\w.+)\\/d\\/(\\w.+)\\/`)\n\tif r.MatchString(s) {\n\t\tres := r.FindAllStringSubmatch(s, -1)\n\t\tp.Kind = res[0][1]\n\t\tp.Id = res[0][2]\n\t\tif p.Kind == \"file\" {\n\t\t\tp.Url = anyurl + \"&id=\" + p.Id\n\t\t} else {\n\t\t\tif p.Kind == \"presentation\" {\n\t\t\t\tp.Url = docutl + p.Kind + \"/d/\" + p.Id + \"/export/\" + p.Ext\n\t\t\t} else {\n\t\t\t\tp.Url = docutl + p.Kind + \"/d/\" + p.Id + \"/export?format=\" + p.Ext\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn errors.New(\"Error: URL is wrong.\")\n\t}\n\treturn nil\n}", "func (calculator LinearPolynomCostCalculator) GetCost() (cost float64) {\n\tcurrentSpline := calculator.GetSpline()\n\tcost = getPositionCost(currentSpline, positionCostPower)*calculator.weights.Position +\n\t\tgetAngleCost(currentSpline, angleCostPower)*calculator.weights.Angle +\n\t\tgetRadiusCost(currentSpline, radiusCostPower, radiusCostResolution)*calculator.weights.Radius\n\n\treturn cost\n}", "func (doc Document) URL() string {\n\treturn fmt.Sprintf(\"https://www.wiso-net.de/document/%s\", doc.SourceAndID())\n}", "func (es *ExploreServer) parseTemplate(templateName string, data interface{}) ([]byte, error) {\n\n\t// funcMap is passed to the template engine so that templates may have\n\t// access to these functions. Defined here to give access to functions of es.\n\tvar funcMap = template.FuncMap{\n\t\t\"siacoinString\": siacoinString,\n\t\t\"byteString\": byteString,\n\t\t\"hashAvgString\": hashAvgString,\n\t\t\"timeString\": timeString,\n\t\t\"parseTemplate\": es.parseTemplate,\n\t\t\"parseTransaction\": es.parseTransaction,\n\t\t\"findOutput\": es.findOutput,\n\t\t\"increment\": func(x types.BlockHeight) types.BlockHeight { return x + 1 },\n\t\t\"uint64\": func(x int) uint64 { return uint64(x) },\n\t\t\"int64_uint64\": func(x int64) uint64 { return uint64(x) },\n\t\t\"txidToHash\": func(x types.TransactionID) crypto.Hash { return crypto.Hash(x) },\n\t}\n\n\tt, err := template.New(templateName).Funcs(funcMap).ParseFiles(\"templates/\" + templateName)\n\tif err != nil {\n\t\ts := fmt.Sprintf(\"Error parsing template %s: %v\", templateName, err)\n\t\tfmt.Println(s)\n\t\treturn nil, errors.New(s)\n\t}\n\n\t// Use a bytes buffer to avoid requiring the writing\n\t// object. This way we can return a byte slice\n\tvar doc bytes.Buffer\n\terr = t.Execute(&doc, data)\n\tif err != nil {\n\t\ts := fmt.Sprintf(\"Error executing template %s: %v\", templateName, err)\n\t\tfmt.Println(s)\n\t\treturn nil, errors.New(s)\n\t}\n\n\treturn doc.Bytes(), nil\n}", "func (p *PerTypeEmitterProvider) validateFilenameTemplate(filenameTemplate string) error {\n\tif \"\" == filenameTemplate {\n\t\treturn fmt.Errorf(\"You must provide a filename template, e.g. path/to/file.json\")\n\t}\n\n\tdowncased := strings.ToLower(filepath.Base(filenameTemplate))\n\n\tif \".json\" != filepath.Ext(downcased) {\n\t\treturn fmt.Errorf(\"Filename template must have a `.json` extension\")\n\t}\n\n\tif \".json\" == downcased {\n\t\treturn fmt.Errorf(\"Filename template must have a basename before the `.json` extension\")\n\t}\n\n\tbasedir := filepath.Dir(filenameTemplate)\n\n\tdirExists, patherr := isDir(basedir)\n\n\tif patherr != nil {\n\t\treturn fmt.Errorf(\"Failed to stat() %q: %v\", basedir, patherr)\n\t}\n\n\tif !dirExists {\n\t\treturn fmt.Errorf(\"Directory %q is not a directory\", basedir)\n\t}\n\n\treturn nil\n}", "func CreateUrl(widget string) string {\n\t//println(widget)\n\tif _, err := os.Stat(widget); os.IsNotExist(err) {\n\t\treturn path.Join(os.Getenv(\"GOPATH\"), \"src\", PACKAGE_NAME, widget)\n\t}\n\treturn widget\n}", "func GetUrl(c *gin.Context) {\n\tsurl := c.Param(\"surl\")\n\tfmt.Println(surl)\n\tkey, err := strconv.ParseUint(surl, 36, 0)\n\tif err != nil {\n\t\tfmt.Println(\"\\033[;31murl not validated\\033[;0m\")\n\t}\n\tstr := storage.RedisPool.GetShortUrlFromRedis(key)\n\tfmt.Println(str)\n\tif str == \"\" {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"surl\": \"\",\n\t\t\t\"msg\": \"failed\",\n\t\t})\n\t}\n\tc.Redirect(302, str)\n}", "func TestPostSlidesDocumentInvalidtemplatePath(t *testing.T) {\n request := createPostSlidesDocumentRequest()\n request.templatePath = invalidizeTestParamValue(request.templatePath, \"templatePath\", \"string\").(string)\n e := initializeTest(\"PostSlidesDocument\", \"templatePath\", request.templatePath)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesDocument(request)\n assertError(t, \"PostSlidesDocument\", \"templatePath\", r.Code, e)\n}", "func (b Backend) Valid(tlsPassthrough bool) error {\n\tif tlsPassthrough {\n\t\t_, _, err := asIpPort(string(b))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse backend %s with error: %w\", b, err)\n\t\t}\n\n\t} else {\n\t\tu, err := url.Parse(string(b))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse backend with error: %w\", err)\n\t\t}\n\n\t\tif u.Scheme != \"http\" {\n\t\t\treturn fmt.Errorf(\"scheme expected to be http\")\n\t\t}\n\n\t\tip := net.ParseIP(u.Hostname())\n\t\tif len(ip) == 0 || ip.IsLoopback() {\n\t\t\treturn fmt.Errorf(\"invalid ip address in backend: %s\", u.Hostname())\n\t\t}\n\t}\n\n\treturn nil\n}", "func generateTemplateVarsVerification(vt string) verificationVars {\n\tverificationLink := os.Getenv(\"RT_DOMAIN\") + \"/verify?key=\" + vt\n\treturn verificationVars{\n\t\tVerificationLink: verificationLink,\n\t}\n}", "func (o *URLCreateOptions) Validate() (err error) {\n\tif !util.CheckOutputFlag(o.OutputFlag) {\n\t\treturn fmt.Errorf(\"given output format %s is not supported\", o.OutputFlag)\n\t}\n\n\t// if experimental mode is enabled, and devfile is provided.\n\terrorList := make([]string, 0)\n\tif o.isDevFile {\n\t\tif !o.isDocker && o.tlsSecret != \"\" && (o.urlType != envinfo.INGRESS || !o.secureURL) {\n\t\t\terrorList = append(errorList, \"TLS secret is only available for secure URLs of Ingress kind\")\n\t\t}\n\n\t\t// check if a host is provided for route based URLs\n\t\tif len(o.host) > 0 {\n\t\t\tif o.urlType == envinfo.ROUTE {\n\t\t\t\terrorList = append(errorList, \"host is not supported for URLs of Route Kind\")\n\t\t\t}\n\t\t\tif err := validation.ValidateHost(o.host); err != nil {\n\t\t\t\terrorList = append(errorList, err.Error())\n\t\t\t}\n\t\t} else if o.urlType == envinfo.INGRESS {\n\t\t\terrorList = append(errorList, \"host must be provided in order to create URLS of Ingress Kind\")\n\t\t}\n\t\tfor _, localURL := range o.EnvSpecificInfo.GetURL() {\n\t\t\tif o.urlName == localURL.Name {\n\t\t\t\terrorList = append(errorList, fmt.Sprintf(\"URL %s already exists\", o.urlName))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, localURL := range o.LocalConfigInfo.GetURL() {\n\t\t\tif o.urlName == localURL.Name {\n\t\t\t\terrorList = append(errorList, fmt.Sprintf(\"URL %s already exists in application: %s\", o.urlName, o.Application))\n\t\t\t}\n\t\t}\n\t}\n\t// Check if url name is more than 63 characters long\n\tif len(o.urlName) > 63 {\n\t\terrorList = append(errorList, \"URL name must be shorter than 63 characters\")\n\t}\n\n\tif !o.isExperimental {\n\t\tif o.now {\n\t\t\tif err = o.ValidateComponentCreate(); err != nil {\n\t\t\t\terrorList = append(errorList, err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errorList) > 0 {\n\t\tfor i := range errorList {\n\t\t\terrorList[i] = fmt.Sprintf(\"\\t- %s\", errorList[i])\n\t\t}\n\t\treturn fmt.Errorf(\"URL creation failed:\\n%s\", strings.Join(errorList, \"\\n\"))\n\t}\n\treturn\n}", "func ValidateURL(c *Config) error {\n\t_, err := url.Parse(c.MetricsPath)\n\treturn err\n}", "func (s ServiceInfo) Url() string {\n\turl := fmt.Sprintf(\"%s://%s:%v\", DefaultHttpProtocol, s.Host, s.Port)\n\treturn url\n}", "func getGoldInstanceURL(instanceID string) string {\n\tif instanceID == instanceIDFuchsia {\n\t\treturn hostFuchsiaCorp\n\t}\n\treturn fmt.Sprintf(goldHostTemplate, instanceID)\n}", "func (f *FortiWebClient) CreateHTTPContentRoutingUsingURL(HTTPContentRoutingPolicy string,\n\tmatchExpression string,\n\turlCondition int,\n\tconcatenate concatenateOperator) error {\n\n\tbody := map[string]interface{}{\n\t\t\"matchObject\": httpURL,\n\t\t\"matchExpression\": strings.TrimSpace(matchExpression),\n\t\t\"urlCondition\": urlCondition,\n\t\t\"concatenate\": concatenate,\n\t}\n\n\tjsonByte, err := json.Marshal(body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error in json data: %s\\n\", err)\n\t\treturn err\n\t}\n\n\turl := strings.Join([]string{\"api/v1.0/ServerObjects/Server/HTTPContentRoutingPolicy/\",\n\t\tf.SafeName(HTTPContentRoutingPolicy),\n\t\t\"/HTTPContentRoutingPolicyNewHTTPContentRouting\"},\n\t\t\"\")\n\tresponse, error := f.DoPost(url, string(jsonByte))\n\n\tif error != nil {\n\t\tfmt.Printf(\"The HTTP request failed with error %s\\n\", error)\n\t\treturn error\n\t}\n\tif response != nil && response.StatusCode != 200 {\n\t\tfmt.Printf(\"The HTTP request failed with HTTP code: %d, %s\\n\", response.StatusCode, response.Status)\n\t}\n\n\treturn nil\n}", "func (r *GetTemplateReq) Rel(link string, resp *GetTemplateResponse) bool {\n\tu := getRelLink(resp.HTTPResponse(), link)\n\tif u == \"\" {\n\t\treturn false\n\t}\n\tr._url = u\n\treturn true\n}", "func (joint UrlFilterJoint) Process(context *model.Context) error {\n\n\tsnapshot := context.MustGet(model.CONTEXT_SNAPSHOT).(*model.Snapshot)\n\n\toriginalUrl := context.GetStringOrDefault(model.CONTEXT_TASK_OriginalUrl, \"\")\n\turl := context.MustGetString(model.CONTEXT_TASK_URL)\n\thost := context.MustGetString(model.CONTEXT_TASK_Host)\n\tif url == \"\" {\n\t\tcontext.Exit(\"nil url\")\n\t\treturn nil\n\t}\n\n\tif originalUrl != \"\" {\n\t\tif !joint.validRule(urlMatchRule, originalUrl) {\n\t\t\tcontext.Exit(\"invalid url (original), \" + originalUrl)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif !joint.validRule(urlMatchRule, url) {\n\t\tcontext.Exit(\"invalid url, \" + url)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(hostMatchRule, host) {\n\t\tcontext.Exit(\"invalid host, \" + host)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(pathMatchRule, snapshot.Path) {\n\t\tcontext.Exit(\"invalid path, \" + snapshot.Path)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileMatchRule, snapshot.File) {\n\t\tcontext.Exit(\"invalid file, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\tif !joint.validRule(fileExtensionMatchRule, util.FileExtension(snapshot.File)) {\n\t\tcontext.Exit(\"invalid file extension, \" + snapshot.File)\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func (s *FieldStatsService) buildURL() (string, url.Values, error) {\n\t// Build URL\n\tvar err error\n\tvar path string\n\tif len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_field_stats\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else {\n\t\tpath = \"/_field_stats\"\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif s.allowNoIndices != nil {\n\t\tparams.Set(\"allow_no_indices\", fmt.Sprintf(\"%v\", *s.allowNoIndices))\n\t}\n\tif s.expandWildcards != \"\" {\n\t\tparams.Set(\"expand_wildcards\", s.expandWildcards)\n\t}\n\tif len(s.fields) > 0 {\n\t\tparams.Set(\"fields\", strings.Join(s.fields, \",\"))\n\t}\n\tif s.ignoreUnavailable != nil {\n\t\tparams.Set(\"ignore_unavailable\", fmt.Sprintf(\"%v\", *s.ignoreUnavailable))\n\t}\n\tif s.level != \"\" {\n\t\tparams.Set(\"level\", s.level)\n\t}\n\treturn path, params, nil\n}", "func URLValidator(u string) {\n\t_, err := url.ParseRequestURI(u)\n\tif err != nil {\n\t\terror := fmt.Errorf(\"%v\", aurora.Index(197, err))\n\t\tfmt.Println(error.Error())\n\t\tos.Exit(1)\n\t}\n}", "func (env Environment) generateURL(version string, path string) string {\n\treturn string(env) + version + path\n}", "func URLform(url, body string) (result string) {\n\tresult = fmt.Sprintf(`[%s](%s)`, body, url)\n\treturn\n}", "func (h *Harness) URL() string {\n\treturn h.backend.URL()\n}", "func (dsr *DeleteSSPRequest) URL() string {\n\treturn fmt.Sprintf(\"/v1/ssps/%v\", dsr.ID)\n}", "func StyleURL(value string) *SimpleElement { return newSEString(\"styleUrl\", value) }", "func validateTriggerTemplate(template *v1alpha1.TriggerTemplate) error {\n\tif template == nil {\n\t\treturn errors.Errorf(\"trigger template can't be nil\")\n\t}\n\tif template.Name == \"\" {\n\t\treturn errors.Errorf(\"trigger must define a name\")\n\t}\n\tif template.Switch != nil && template.Switch.All != nil && template.Switch.Any != nil {\n\t\treturn errors.Errorf(\"trigger condition can't have both any and all condition\")\n\t}\n\tif template.K8s != nil {\n\t\tif err := validateK8STrigger(template.K8s); err != nil {\n\t\t\treturn errors.Wrapf(err, \"trigger for template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.ArgoWorkflow != nil {\n\t\tif err := validateArgoWorkflowTrigger(template.ArgoWorkflow); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.HTTP != nil {\n\t\tif err := validateHTTPTrigger(template.HTTP); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.AWSLambda != nil {\n\t\tif err := validateAWSLambdaTrigger(template.AWSLambda); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.Kafka != nil {\n\t\tif err := validateKafkaTrigger(template.Kafka); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.NATS != nil {\n\t\tif err := validateNATSTrigger(template.NATS); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.Slack != nil {\n\t\tif err := validateSlackTrigger(template.Slack); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.OpenWhisk != nil {\n\t\tif err := validateOpenWhiskTrigger(template.OpenWhisk); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\tif template.CustomTrigger != nil {\n\t\tif err := validateCustomTrigger(template.CustomTrigger); err != nil {\n\t\t\treturn errors.Wrapf(err, \"template %s is invalid\", template.Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {\n\tmethodString := obs.HTTP_GET\n\tmethod, ok := options[\"method\"]\n\tif ok {\n\t\tmethodString, ok = method.(string)\n\t\tif !ok || (methodString != obs.HTTP_GET && methodString != obs.HTTP_HEAD) {\n\t\t\treturn \"\", storagedriver.ErrUnsupportedMethod{}\n\t\t}\n\t}\n\n\texpiresIn := 2000000 * time.Minute\n\texpires, ok := options[\"expiry\"]\n\tif ok {\n\t\tet, ok := expires.(time.Time)\n\t\tif ok {\n\t\t\texpiresIn = et.Sub(time.Now())\n\t\t}\n\t}\n\n\toutput, err := d.Client.CreateSignedUrl(&obs.CreateSignedUrlInput{\n\t\tMethod: obs.HttpMethodType(methodString),\n\t\tBucket: d.Bucket,\n\t\tKey: d.obsPath(path),\n\t\tExpires: int(expiresIn) * 600,\n\t})\n\treturn output.SignedUrl, err\n}", "func checkRedirect(url string) (returnObj returnCheckerObj) {\n\treturnObj.url = url\n\turl = *HostURL + url\n\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturnObj.message = err.Error()\n\t\treturnObj.success = false\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturnObj.message = err.Error()\n\t\treturnObj.success = false\n\t\treturn\n\t}\n\n\tbodyString := string(bodyBytes)\n\treturnObj.message = bodyString\n\treturnObj.success = true\n\n\tswitch {\n\tcase strings.HasSuffix(url, \"?wsdl\"):\n\t\tif !strings.Contains(bodyString, \"<wsdl:definitions\") {\n\t\t\treturnObj.message = \"URL was ending with ?wsdl but did not contain <wsdl:definition!\"\n\t\t\treturnObj.success = false\n\t\t}\n\tcase strings.HasSuffix(url, \".xsd\"):\n\t\tif !strings.Contains(bodyString, \"<xs:schema\") {\n\t\t\treturnObj.message = \"URL was ending with .xsd but did not contain <xs:schema!\"\n\t\t\treturnObj.success = false\n\t\t}\n\t}\n\treturn\n}", "func templateFunctionRequired(value interface{}) (interface{}, error) {\n\tif value == nil {\n\t\treturn nil, errors.NewConfigurationError(\"required value is nil\")\n\t}\n\n\treturn value, nil\n}", "func CheckTargetURL(url string) (string, int, int64, *html.Node, error) {\n\tprefixSplit := strings.Split(url, \"://\")\n\tprefix := \"http://\"\n\tif len(prefixSplit) == 1 {\n\t\turl = prefix + url\n\t} else {\n\t\tprefix = prefixSplit[0] + \"://\"\n\t}\n\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\tdefer httpClient.CloseIdleConnections()\n\n\tst := time.Now()\n\tresponse, err := httpClient.Get(url)\n\tet := time.Now()\n\tif err != nil {\n\t\treturn \"\", 0, time.Duration(0).Milliseconds(), nil, err\n\t}\n\tdefer response.Body.Close()\n\n\trt := et.Sub(st).Milliseconds()\n\tbaseURL := prefix + response.Request.Host\n\n\tbody, err := html.Parse(response.Body)\n\tif err != nil {\n\t\treturn baseURL, response.StatusCode, rt, nil, err\n\t}\n\n\treturn baseURL, response.StatusCode, rt, body, nil\n}", "func (s *IndicesStatsService) buildURL() (string, url.Values, error) {\n\tvar err error\n\tvar path string\n\tif len(s.index) > 0 && len(s.metric) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_stats/{metric}\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t\t\"metric\": strings.Join(s.metric, \",\"),\n\t\t})\n\t} else if len(s.index) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/{index}/_stats\", map[string]string{\n\t\t\t\"index\": strings.Join(s.index, \",\"),\n\t\t})\n\t} else if len(s.metric) > 0 {\n\t\tpath, err = uritemplates.Expand(\"/_stats/{metric}\", map[string]string{\n\t\t\t\"metric\": strings.Join(s.metric, \",\"),\n\t\t})\n\t} else {\n\t\tpath = \"/_stats\"\n\t}\n\tif err != nil {\n\t\treturn \"\", url.Values{}, err\n\t}\n\n\t// Add query string parameters\n\tparams := url.Values{}\n\tif s.pretty {\n\t\tparams.Set(\"pretty\", \"true\")\n\t}\n\tif len(s.groups) > 0 {\n\t\tparams.Set(\"groups\", strings.Join(s.groups, \",\"))\n\t}\n\tif s.human != nil {\n\t\tparams.Set(\"human\", fmt.Sprintf(\"%v\", *s.human))\n\t}\n\tif s.level != \"\" {\n\t\tparams.Set(\"level\", s.level)\n\t}\n\tif len(s.types) > 0 {\n\t\tparams.Set(\"types\", strings.Join(s.types, \",\"))\n\t}\n\tif len(s.completionFields) > 0 {\n\t\tparams.Set(\"completion_fields\", strings.Join(s.completionFields, \",\"))\n\t}\n\tif len(s.fielddataFields) > 0 {\n\t\tparams.Set(\"fielddata_fields\", strings.Join(s.fielddataFields, \",\"))\n\t}\n\tif len(s.fields) > 0 {\n\t\tparams.Set(\"fields\", strings.Join(s.fields, \",\"))\n\t}\n\treturn path, params, nil\n}", "func (cfg *HTTPConfig) Valid() error {\n\t// TODO: more validation, for example, the file existence\n\tif cfg.Schema != \"https\" && cfg.Schema != \"http\" {\n\t\treturn fmt.Errorf(\"invalid schema '%s', only 'http' and 'https' are supported \", cfg.Schema)\n\t}\n\n\treturn nil\n}", "func (s server) Eval(ctx context.Context, req *entity.Request) (*entity.Result, error) {\n\tlog.Printf(\"Received a request: %+v\\n\", req)\n\tresult := &entity.Result{}\n\tres, err := s.usecase.Eval(req.Value)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Value = strconv.FormatFloat(res, 'G', -1, 64)\n\treturn result, nil\n}", "func New(text string) error {\n\t// 没有取地址\n\treturn errorString(text)\n}", "func ValidateTemplate(wf *Workflow) error {\n\ttaskNameMap := make(map[string]struct{})\n\tfor _, task := range wf.Tasks {\n\t\tif hasEmptyName(task.Name) {\n\t\t\treturn errors.New(errEmptyName + task.Name)\n\t\t}\n\t\tif !hasValidLength(task.Name) {\n\t\t\treturn errors.New(errInvalidLength + task.Name)\n\t\t}\n\t\t_, ok := taskNameMap[task.Name]\n\t\tif ok {\n\t\t\treturn errors.New(errDuplicateTaskName + task.Name)\n\t\t}\n\t\ttaskNameMap[task.Name] = struct{}{}\n\t\tactionNameMap := make(map[string]struct{})\n\t\tfor _, action := range task.Actions {\n\t\t\tif hasEmptyName(action.Name) {\n\t\t\t\treturn errors.New(errEmptyName + action.Name)\n\t\t\t}\n\n\t\t\tif !hasValidLength(action.Name) {\n\t\t\t\treturn errors.New(errInvalidLength + action.Name)\n\t\t\t}\n\n\t\t\tif !hasValidImageName(action.Image) {\n\t\t\t\treturn errors.New(errInvalidActionImage + action.Image)\n\t\t\t}\n\n\t\t\t_, ok := actionNameMap[action.Name]\n\t\t\tif ok {\n\t\t\t\treturn errors.New(errDuplicateActionName + action.Name)\n\t\t\t}\n\t\t\tactionNameMap[action.Name] = struct{}{}\n\t\t}\n\t}\n\treturn nil\n}", "func loadTemplate() *template.Template {\n\t// define template\n\tt := &template.Template{\n\t\tDelimiter: delimiter,\n\t\tFilter: filter,\n\t\tFormat: format,\n\t\tOutfile: outfile,\n\t\tPrefix: prefix,\n\t}\n\tif err := validation.Validate.Struct(t); err != nil {\n\t\tlogrus.WithError(err).Fatalln(\"error loading template...\")\n\t}\n\treturn t\n}", "func (o BuildRunStatusBuildSpecSourceOutput) Url() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BuildRunStatusBuildSpecSource) string { return v.Url }).(pulumi.StringOutput)\n}", "func mustTemplate(name, src string) *template.Template {\n\treturn template.Must(template.New(name).Parse(src))\n}" ]
[ "0.5740493", "0.52863187", "0.51645577", "0.51583594", "0.49364486", "0.48836643", "0.47784847", "0.47778913", "0.47723264", "0.47432086", "0.4731789", "0.46830058", "0.46793166", "0.46765676", "0.46701744", "0.46615675", "0.46551394", "0.46551394", "0.46465498", "0.46139225", "0.46022296", "0.45522505", "0.4527301", "0.44910333", "0.44801757", "0.4474217", "0.44625685", "0.44582063", "0.4403753", "0.44021884", "0.4389137", "0.4388688", "0.43827066", "0.43417794", "0.4325331", "0.43178076", "0.42996845", "0.42942718", "0.42905787", "0.42889374", "0.42676234", "0.42612723", "0.4242844", "0.42393178", "0.42286396", "0.4218944", "0.42183483", "0.4217148", "0.42164397", "0.42163742", "0.42162046", "0.4215461", "0.4213721", "0.42114902", "0.42102194", "0.42062676", "0.42032441", "0.41994005", "0.41857538", "0.4178194", "0.4178109", "0.41732687", "0.41713262", "0.41650364", "0.41613725", "0.41559064", "0.415332", "0.41532856", "0.41505712", "0.4148147", "0.4144142", "0.41433522", "0.41415036", "0.41404104", "0.41344234", "0.41330677", "0.41276586", "0.41162404", "0.41145983", "0.4110711", "0.41076747", "0.41048333", "0.41041312", "0.41039604", "0.41006672", "0.4096561", "0.40964842", "0.4090707", "0.40902317", "0.40887323", "0.40834376", "0.4081807", "0.40727246", "0.40709826", "0.40658024", "0.40647537", "0.4063879", "0.40630028", "0.40482196", "0.40470794" ]
0.5397925
1
WithEndpoint configures a [Client] to use the specified Metadata API endpoint.
func WithEndpoint(endpoint string) ClientOption { return func(client *Client) { client.endpoint = strings.TrimRight(endpoint, "/") } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithEndpoint(endpoint string) Opt {\n\treturn func(c *Client) {\n\t\tc.endpoint = endpoint\n\t}\n}", "func WithEndpoint(s string) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.endpoint = s\n\t\treturn nil\n\t}\n}", "func WithEndpoint(endpoint string) ClientOption {\n\treturn func(o *requestFactory) {\n\t\to.endpoint = endpoint\n\t}\n}", "func WithEndpoint(endpoint string) {\n\tcfg.endpoint = strings.TrimRight(endpoint, \"/\")\n}", "func WithEndpoint(endpoint string) Option {\n\treturn wrappedOption{oconf.WithEndpoint(endpoint)}\n}", "func WithEndpoint(endpoint string) Option {\n\treturn func(o *options) {\n\t\to.endpoint = endpoint\n\t}\n}", "func WithEndpoint(v string) (p Pair) {\n\treturn Pair{Key: \"endpoint\", Value: v}\n}", "func WithEndpoint(e string) Option {\n\treturn func(o *Options) {\n\t\to.Endpoint = e\n\t}\n}", "func WithEndpoint(endpoint string) Option {\n\treturn wrappedOption{otlpconfig.WithEndpoint(endpoint)}\n}", "func (c *Client) SetEndpoint(endpoint string) {\n\tif endpoint == \"\" {\n\t\tc.endpoint = DefaultEndpoint\n\t\treturn\n\t}\n\tc.endpoint = endpoint\n}", "func (clt *Client) SetEndpoint(endpoint string) {\n\tclt.endpoint = endpoint\n}", "func (options *CreateNotificationChannelOptions) SetEndpoint(endpoint string) *CreateNotificationChannelOptions {\n\toptions.Endpoint = core.StringPtr(endpoint)\n\treturn options\n}", "func Endpoint(rawurl string) Opt {\n\treturn func(c *Client) Opt {\n\t\told := c.url\n\t\tc.url = rawurl\n\t\treturn Endpoint(old)\n\t}\n}", "func WithEndpoint(endpoint string) CollectorEndpointOption {\n\treturn collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {\n\t\to.endpoint = endpoint\n\t})\n}", "func (options *UpdateNotificationChannelOptions) SetEndpoint(endpoint string) *UpdateNotificationChannelOptions {\n\toptions.Endpoint = core.StringPtr(endpoint)\n\treturn options\n}", "func NewClientWithEndpoint(endpoint string, token string, dryRun bool) *Client {\n\tbaseURL, err := url.Parse(endpoint)\n\tif err != nil {\n\t\tglog.Fatalf(\"invalid github endpoint %s: %s\", endpoint, err)\n\t}\n\tif !strings.HasSuffix(baseURL.Path, \"/\") {\n\t\tbaseURL.Path += \"/\"\n\t}\n\n\thttpClient := &http.Client{\n\t\tTransport: &oauth2.Transport{\n\t\t\tBase: http.DefaultTransport,\n\t\t\tSource: oauth2.ReuseTokenSource(nil, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})),\n\t\t},\n\t}\n\tclient := github.NewClient(httpClient)\n\tclient.BaseURL = baseURL\n\n\treturn &Client{\n\t\tissueService: client.Issues,\n\t\tprService: client.PullRequests,\n\t\trepoService: client.Repositories,\n\t\tuserService: client.Users,\n\t\tretries: 5,\n\t\tretryInitialBackoff: time.Second,\n\t\ttokenReserve: 50,\n\t\tdryRun: dryRun,\n\t}\n}", "func WithAPIEndpoint(endpoint string) Option {\n\treturn func(o *Options) {\n\t\to.APIEndpoint = endpoint\n\t}\n}", "func ExampleEndpointsClient_CreateOrUpdate_endpointPutExternalWithLocation() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().CreateOrUpdate(ctx, \"azuresdkfornetautoresttrafficmanager1421\", \"azsmnet6386\", armtrafficmanager.EndpointTypeExternalEndpoints, \"azsmnet7187\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"azsmnet7187\"),\n\t\tType: to.Ptr(\"Microsoft.network/TrafficManagerProfiles/ExternalEndpoints\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t\t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"azsmnet7187\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func ExampleEndpointsClient_CreateOrUpdate_endpointPutExternalWithAlwaysServe() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().CreateOrUpdate(ctx, \"azuresdkfornetautoresttrafficmanager1421\", \"azsmnet6386\", armtrafficmanager.EndpointTypeExternalEndpoints, \"azsmnet7187\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"azsmnet7187\"),\n\t\tType: to.Ptr(\"Microsoft.network/TrafficManagerProfiles/ExternalEndpoints\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tAlwaysServe: to.Ptr(armtrafficmanager.AlwaysServeEnabled),\n\t\t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t\t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"azsmnet7187\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tAlwaysServe: to.Ptr(armtrafficmanager.AlwaysServeEnabled),\n\t// \t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func (op *OperationRequest) setEndpoint(endpoint string) *OperationRequest {\n\tif endpoint == \"payments\" {\n\t\top.endpoint = endpoint\n\t} else {\n\t\t// default to operations\n\t\top.endpoint = \"operations\"\n\t}\n\treturn op\n}", "func (s *DescribeInferenceExperimentOutput) SetEndpointMetadata(v *EndpointMetadata) *DescribeInferenceExperimentOutput {\n\ts.EndpointMetadata = v\n\treturn s\n}", "func (a *DefaultApiService) UpdateEndpoint(ctx _context.Context, id string) ApiUpdateEndpointRequest {\n\treturn ApiUpdateEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func ExampleEndpointsClient_CreateOrUpdate_endpointPutExternalWithSubnetMapping() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().CreateOrUpdate(ctx, \"azuresdkfornetautoresttrafficmanager2191\", \"azuresdkfornetautoresttrafficmanager8224\", armtrafficmanager.EndpointTypeExternalEndpoints, \"My%20external%20endpoint\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"My external endpoint\"),\n\t\tType: to.Ptr(\"Microsoft.network/TrafficManagerProfiles/ExternalEndpoints\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t\t\tSubnets: []*armtrafficmanager.EndpointPropertiesSubnetsItem{\n\t\t\t\t{\n\t\t\t\t\tFirst: to.Ptr(\"1.2.3.0\"),\n\t\t\t\t\tScope: to.Ptr[int32](24),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tFirst: to.Ptr(\"25.26.27.28\"),\n\t\t\t\t\tLast: to.Ptr(\"29.30.31.32\"),\n\t\t\t\t}},\n\t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"My external endpoint\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager2191/providers/Microsoft.Network/trafficManagerProfiles/azuresdkfornetautoresttrafficmanager8224/externalEndpoints/My external endpoint\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tSubnets: []*armtrafficmanager.EndpointPropertiesSubnetsItem{\n\t// \t\t\t{\n\t// \t\t\t\tFirst: to.Ptr(\"1.2.3.0\"),\n\t// \t\t\t\tScope: to.Ptr[int32](24),\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tFirst: to.Ptr(\"25.26.27.28\"),\n\t// \t\t\t\tLast: to.Ptr(\"29.30.31.32\"),\n\t// \t\t}},\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func (c *Client) CustomEndpoint(e string) {\n\tc.Endpoint = e\n}", "func ExampleEndpointsClient_Update() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().Update(ctx, \"azuresdkfornetautoresttrafficmanager1421\", \"azsmnet6386\", armtrafficmanager.EndpointTypeExternalEndpoints, \"azsmnet7187\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"azsmnet7187\"),\n\t\tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t\tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tTarget: to.Ptr(\"another.foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"azsmnet7187\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tTarget: to.Ptr(\"another.foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func ExampleEndpointsClient_CreateOrUpdate_endpointPutExternalWithCustomHeaders() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().CreateOrUpdate(ctx, \"azuresdkfornetautoresttrafficmanager1421\", \"azsmnet6386\", armtrafficmanager.EndpointTypeExternalEndpoints, \"azsmnet7187\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"azsmnet7187\"),\n\t\tType: to.Ptr(\"Microsoft.network/TrafficManagerProfiles/ExternalEndpoints\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tCustomHeaders: []*armtrafficmanager.EndpointPropertiesCustomHeadersItem{\n\t\t\t\t{\n\t\t\t\t\tName: to.Ptr(\"header-1\"),\n\t\t\t\t\tValue: to.Ptr(\"value-1\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: to.Ptr(\"header-2\"),\n\t\t\t\t\tValue: to.Ptr(\"value-2\"),\n\t\t\t\t}},\n\t\t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t\t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"azsmnet7187\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tCustomHeaders: []*armtrafficmanager.EndpointPropertiesCustomHeadersItem{\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"header-1\"),\n\t// \t\t\t\tValue: to.Ptr(\"value-1\"),\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"header-2\"),\n\t// \t\t\t\tValue: to.Ptr(\"value-2\"),\n\t// \t\t}},\n\t// \t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func ExampleEndpointsClient_CreateOrUpdate_endpointPutExternalWithGeoMapping() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().CreateOrUpdate(ctx, \"azuresdkfornetautoresttrafficmanager2191\", \"azuresdkfornetautoresttrafficmanager8224\", armtrafficmanager.EndpointTypeExternalEndpoints, \"My%20external%20endpoint\", armtrafficmanager.Endpoint{\n\t\tName: to.Ptr(\"My external endpoint\"),\n\t\tType: to.Ptr(\"Microsoft.network/TrafficManagerProfiles/ExternalEndpoints\"),\n\t\tProperties: &armtrafficmanager.EndpointProperties{\n\t\t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t\t\tGeoMapping: []*string{\n\t\t\t\tto.Ptr(\"GEO-AS\"),\n\t\t\t\tto.Ptr(\"GEO-AF\")},\n\t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"My external endpoint\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager2191/providers/Microsoft.Network/trafficManagerProfiles/azuresdkfornetautoresttrafficmanager8224/externalEndpoints/My external endpoint\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tGeoMapping: []*string{\n\t// \t\t\tto.Ptr(\"GEO-AS\"),\n\t// \t\t\tto.Ptr(\"GEO-AF\")},\n\t// \t\t\tPriority: to.Ptr[int64](1),\n\t// \t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\t\tWeight: to.Ptr[int64](1),\n\t// \t\t},\n\t// \t}\n}", "func Endpoint(endpoint *url.URL) ServerOption {\n\treturn func(s *Server) {\n\t\ts.endpoint = endpoint\n\t}\n}", "func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata {\n\tif !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) {\n\t\t// If the http client is unmodified and this feature is not disabled\n\t\t// set custom timeouts for EC2Metadata requests.\n\t\tcfg.HTTPClient = &http.Client{\n\t\t\t// use a shorter timeout than default because the metadata\n\t\t\t// service is local if it is running, and to fail faster\n\t\t\t// if not running on an ec2 instance.\n\t\t\tTimeout: 1 * time.Second,\n\t\t}\n\t\t// max number of retries on the client operation\n\t\tcfg.MaxRetries = aws.Int(2)\n\t}\n\n\tif u, err := url.Parse(endpoint); err == nil {\n\t\t// Remove path from the endpoint since it will be added by requests.\n\t\t// This is an artifact of the SDK adding `/latest` to the endpoint for\n\t\t// EC2 IMDS, but this is now moved to the operation definition.\n\t\tu.Path = \"\"\n\t\tu.RawPath = \"\"\n\t\tendpoint = u.String()\n\t}\n\n\tsvc := &EC2Metadata{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceName,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"latest\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\t// token provider instance\n\ttp := newTokenProvider(svc, defaultTTL)\n\n\t// NamedHandler for fetching token\n\tsvc.Handlers.Sign.PushBackNamed(request.NamedHandler{\n\t\tName: fetchTokenHandlerName,\n\t\tFn: tp.fetchTokenHandler,\n\t})\n\t// NamedHandler for enabling token provider\n\tsvc.Handlers.Complete.PushBackNamed(request.NamedHandler{\n\t\tName: enableTokenProviderHandlerName,\n\t\tFn: tp.enableTokenProviderHandler,\n\t})\n\n\tsvc.Handlers.Unmarshal.PushBackNamed(unmarshalHandler)\n\tsvc.Handlers.UnmarshalError.PushBack(unmarshalError)\n\tsvc.Handlers.Validate.Clear()\n\tsvc.Handlers.Validate.PushBack(validateEndpointHandler)\n\n\t// Disable the EC2 Metadata service if the environment variable is set.\n\t// This short-circuits the service's functionality to always fail to send\n\t// requests.\n\tif strings.ToLower(os.Getenv(disableServiceEnvVar)) == \"true\" {\n\t\tsvc.Handlers.Send.SwapNamed(request.NamedHandler{\n\t\t\tName: corehandlers.SendHandler.Name,\n\t\t\tFn: func(r *request.Request) {\n\t\t\t\tr.HTTPResponse = &http.Response{\n\t\t\t\t\tHeader: http.Header{},\n\t\t\t\t}\n\t\t\t\tr.Error = awserr.New(\n\t\t\t\t\trequest.CanceledErrorCode,\n\t\t\t\t\t\"EC2 IMDS access disabled via \"+disableServiceEnvVar+\" env var\",\n\t\t\t\t\tnil)\n\t\t\t},\n\t\t})\n\t}\n\n\t// Add additional options to the service config\n\tfor _, option := range opts {\n\t\toption(svc.Client)\n\t}\n\treturn svc\n}", "func AzureEndpoint(endpoint string) func(az *TierAzure) error {\n\treturn func(az *TierAzure) error {\n\t\taz.Endpoint = endpoint\n\t\treturn nil\n\t}\n}", "func Endpoint(endpoints ...*url.URL) Option {\n\treturn func(o *options) { o.endpoints = endpoints }\n}", "func Endpoint(endpoints ...*url.URL) Option {\n\treturn func(o *options) { o.endpoints = endpoints }\n}", "func MetadataClient(config *Config) (metadata.ReadWriteClient, error) {\n\tif config.Metadata == constants.GrafeasMetadata {\n\t\treturn grafeas.New(config.Grafeas, config.Certs)\n\t}\n\tif config.Metadata == constants.ContainerAnalysisMetadata {\n\t\treturn containeranalysis.NewCache()\n\t}\n\treturn nil, fmt.Errorf(\"unsupported backend %v\", config.Metadata)\n}", "func New(endpoint string) BaseClient {\n\treturn NewWithoutDefaults(endpoint)\n}", "func WithMetricsEndpoint(endpoint string) Option {\n\treturn wrappedOption{otlpconfig.WithMetricsEndpoint(endpoint)}\n}", "func (u *UpYunForm) SetEndpoint(ed int) error {\n\tif ed >= Auto && ed <= Ctt {\n\t\tu.endpoint = fmt.Sprintf(\"v%d.api.upyun.com\", ed)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid endpoint, pick from Auto, Telecom, Cnc, Ctt\")\n}", "func (s *SearchRecord) SetEndpoint(v *Endpoint) *SearchRecord {\n\ts.Endpoint = v\n\treturn s\n}", "func (c *Client) Endpoint() endpoint.Endpoint {\n\treturn func(ctx context.Context, r interface{}) (interface{}, error) {\n\t\treturn nil, c.do(ctx, r)\n\t}\n}", "func SetMetadata(ctx context.Context, md metadata.Metadata) {\n\tif tr, ok := FromClientContext(ctx); ok {\n\t\ttr.WithMetadata(md)\n\t}\n}", "func (s *HttpsNotificationConfiguration) SetEndpoint(v string) *HttpsNotificationConfiguration {\n\ts.Endpoint = &v\n\treturn s\n}", "func (a *DefaultClient) SetMetadata(file vfs.File, metadata map[string]string) error {\n\tURL, err := url.Parse(file.Location().(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tblobURL := containerURL.NewBlockBlobURL(utils.RemoveLeadingSlash(file.Path()))\n\t_, err = blobURL.SetMetadata(context.Background(), metadata, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})\n\treturn err\n}", "func WithHTTPClient(client *http.Client) CollectorEndpointOption {\n\treturn collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {\n\t\to.httpClient = client\n\t})\n}", "func (x *XVerify) SetEndpoint(e string) {\n\tendpoint = e\n}", "func ExampleEndpointsClient_Get_endpointGetExternalWithLocation() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().Get(ctx, \"azuresdkfornetautoresttrafficmanager1421\", \"azsmnet6386\", armtrafficmanager.EndpointTypeExternalEndpoints, \"azsmnet7187\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"azsmnet7187\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager1421/providers/Microsoft.Network/trafficManagerProfiles/azsmnet6386/externalEndpoints/azsmnet7187\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointLocation: to.Ptr(\"North Europe\"),\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func (s *Workgroup) SetEndpoint(v *Endpoint) *Workgroup {\n\ts.Endpoint = v\n\treturn s\n}", "func New(endpoint string) *Client {\n\treturn &Client{\n\t\tendpoint: endpoint,\n\t}\n}", "func (s *Cluster) SetEndpoint(v string) *Cluster {\n\ts.Endpoint = &v\n\treturn s\n}", "func (s *GetEndpointAccessOutput) SetEndpoint(v *EndpointAccess) *GetEndpointAccessOutput {\n\ts.Endpoint = v\n\treturn s\n}", "func (policy *PolicySvc) augmentEndpoint(endpoint *common.Endpoint) error {\n\ttenantSvcUrl, err := policy.client.GetServiceUrl(\"tenant\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endpoint.Peer == common.Wildcard {\n\t\t// If a wildcard is specfied, there is nothing to augment\n\t\treturn nil\n\t}\n\tlog.Printf(\"Policy: Augmenting %#v\", endpoint)\n\n\t// Code below tries to resolve tenant name into tenant_network_id if possible.\n\t//\n\t// TODO this will have to be changed once we implement\n\t// https://paninetworks.kanbanize.com/ctrl_board/3/cards/319/details\n\tten := &tenant.Tenant{}\n\tif endpoint.TenantNetworkID == nil {\n\t\tif endpoint.TenantID != 0 {\n\t\t\ttenantIDToUse := strconv.FormatUint(endpoint.TenantID, 10)\n\t\t\ttenantsUrl := fmt.Sprintf(\"%s/tenants/%s\", tenantSvcUrl, tenantIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking tenant up at %s\", tenantsUrl)\n\t\t\terr = policy.client.Get(tenantsUrl, ten)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\n\t\t} else if endpoint.TenantExternalID != \"\" || endpoint.TenantName != \"\" {\n\t\t\tif endpoint.TenantExternalID != \"\" {\n\t\t\t\tten.ExternalID = endpoint.TenantExternalID\n\t\t\t}\n\t\t\tif endpoint.TenantName != \"\" {\n\t\t\t\tten.Name = endpoint.TenantName\n\t\t\t}\n\t\t\terr = policy.client.Find(ten, common.FindLast)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\t\t}\n\t}\n\n\tif endpoint.SegmentNetworkID == nil {\n\t\tif ten == nil && (endpoint.SegmentID != 0 || endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\") {\n\t\t\treturn common.NewError400(\"No tenant information specified, cannot look up segment.\")\n\t\t}\n\t\tsegment := &tenant.Segment{}\n\t\tif endpoint.SegmentID != 0 {\n\t\t\tsegmentIDToUse := strconv.FormatUint(endpoint.SegmentID, 10)\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/tenants/%d/segments/%s\", tenantSvcUrl, ten.ID, segmentIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking segment up at %s for %#v\", segmentsUrl, endpoint)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t} else if endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\" {\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/findLast/segments?tenant_id=%d&\", tenantSvcUrl, ten.ID)\n\t\t\tif endpoint.SegmentExternalID != \"\" {\n\t\t\t\tsegmentsUrl += \"external_id=\" + endpoint.TenantExternalID + \"&\"\n\t\t\t}\n\t\t\tif endpoint.SegmentName != \"\" {\n\t\t\t\tsegmentsUrl += \"name=\" + endpoint.SegmentName\n\t\t\t}\n\t\t\tlog.Printf(\"Policy: Finding segments at %s for %#v (Tenant %#v %t)\", segmentsUrl, endpoint, ten, ten == nil)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t}\n\t}\n\treturn nil\n}", "func (a *DefaultApiService) ShowEndpoint(ctx _context.Context, id string) ApiShowEndpointRequest {\n\treturn ApiShowEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func (c *MockRemoteWriteClient) Endpoint() string { return \"\" }", "func NewClient(endpoint string) *Client {\n\tc := &Client{\n\t\tendpoint: endpoint,\n\t}\n\n\tif c.httpClient == nil {\n\t\tc.httpClient = http.DefaultClient\n\t}\n\treturn c\n}", "func NewClient(endpoint string) *Client {\n\treturn &Client{\n\t\tendpoint: endpoint,\n\t}\n}", "func (ml *ManagedListener) SetEndpoint(ep *v1.Endpoints) {\n\tdefer ml.Monitor()()\n\tif InCluster() {\n\t\tif ml.Endpoints != nil && ep != nil {\n\t\t\tlhsPorts := EndpointIPs(ml.Endpoints)\n\t\t\tlhsIPs := EndpointSubsetPorts(ml.Endpoints)\n\t\t\trhsPorts := EndpointIPs(ep)\n\t\t\trhsIPs := EndpointSubsetPorts(ep)\n\t\t\tif !lhsPorts.Equal(rhsPorts) || !lhsIPs.Equal(rhsIPs) {\n\t\t\t\tml.EndpointsChanged = true\n\t\t\t\tml.Endpoints = ep\n\t\t\t}\n\t\t}\n\t}\n}", "func NewEndpointMiddleware() endpoint.Middleware {\n\treturn func(next endpoint.Endpoint) endpoint.Endpoint {\n\t\treturn func(ctx context.Context, req interface{}) (resp interface{}, err error) {\n\t\t\tctx = New().WithCtx(ctx)\n\t\t\treturn next(ctx, req)\n\t\t}\n\t}\n}", "func (c *Client) Endpoint() string {\n\treturn c.url\n}", "func (b *NutanixPrismElementEndpointApplyConfiguration) WithEndpoint(value *NutanixPrismEndpointApplyConfiguration) *NutanixPrismElementEndpointApplyConfiguration {\n\tb.Endpoint = value\n\treturn b\n}", "func (s *UpdateEndpointAccessOutput) SetEndpoint(v *EndpointAccess) *UpdateEndpointAccessOutput {\n\ts.Endpoint = v\n\treturn s\n}", "func (s *CreateEndpointAccessOutput) SetEndpoint(v *EndpointAccess) *CreateEndpointAccessOutput {\n\ts.Endpoint = v\n\treturn s\n}", "func (a *DefaultApiService) DeleteEndpoint(ctx _context.Context, id string) ApiDeleteEndpointRequest {\n\treturn ApiDeleteEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func TagEndpoint() Endpoint {\n\treturn func(u *url.URL) {\n\t\taddToURL(u, \"tags\")\n\t}\n}", "func ExampleEndpointsClient_Get_endpointGetExternalWithSubnetMapping() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().Get(ctx, \"azuresdkfornetautoresttrafficmanager2191\", \"azuresdkfornetautoresttrafficmanager8224\", armtrafficmanager.EndpointTypeExternalEndpoints, \"My%20external%20endpoint\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"My external endpoint\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager2191/providers/Microsoft.Network/trafficManagerProfiles/azuresdkfornetautoresttrafficmanager8224/externalEndpoints/My external endpoint\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tPriority: to.Ptr[int64](1),\n\t// \t\tSubnets: []*armtrafficmanager.EndpointPropertiesSubnetsItem{\n\t// \t\t\t{\n\t// \t\t\t\tFirst: to.Ptr(\"1.2.3.0\"),\n\t// \t\t\t\tScope: to.Ptr[int32](24),\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tFirst: to.Ptr(\"25.26.27.28\"),\n\t// \t\t\t\tLast: to.Ptr(\"29.30.31.32\"),\n\t// \t\t}},\n\t// \t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\tWeight: to.Ptr[int64](1),\n\t// \t},\n\t// }\n}", "func NewEndpoint(config *config.Configs, result *config.ReturnResult) Endpoint {\n\treturn &endpoint{\n\t\tconfig: config,\n\t\tresult: result,\n\t\tservice: NewService(config, result),\n\t}\n}", "func (plugin) WrapEndpoint(edp muxrpc.Endpoint) interface{} {\n\treturn endpoint{edp}\n}", "func (o AuthConfigAzureAdOutput) Endpoint() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AuthConfigAzureAd) pulumi.StringPtrOutput { return v.Endpoint }).(pulumi.StringPtrOutput)\n}", "func (s *ClusterEndpoint) SetEndpoint(v string) *ClusterEndpoint {\n\ts.Endpoint = &v\n\treturn s\n}", "func Init(endpoint string) error {\n\tdefaultHeaders := map[string]string{\"User-Agent\": \"cilium\"}\n\tc, err := client.NewClient(endpoint, \"v1.21\", nil, defaultHeaders)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdockerClient = c\n\n\treturn nil\n}", "func (s *DeleteEndpointAccessOutput) SetEndpoint(v *EndpointAccess) *DeleteEndpointAccessOutput {\n\ts.Endpoint = v\n\treturn s\n}", "func (m *Metadata) Client() (*Client, error) {\n\tif m.client == nil {\n\t\tclient, err := NewClient(m.Region)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.client = client\n\t}\n\treturn m.client, nil\n}", "func NewFromEndpoint(\n\te endpoint.Endpoint,\n\tdecoder goduck.EndpointBatchDecoder,\n\tmaxBatchSize int,\n\tmaxTimeout time.Duration,\n\tstream goduck.Stream,\n) *BatchEngine {\n\treturn New(\n\t\tgokithelper.MustNewEndpointBatchProcessor(e, decoder),\n\t\tmaxBatchSize,\n\t\tmaxTimeout,\n\t\tstream,\n\t)\n}", "func (s *DiscoverPollEndpointOutput) SetEndpoint(v string) *DiscoverPollEndpointOutput {\n\ts.Endpoint = &v\n\treturn s\n}", "func AboutEndpointInst() RestEndpointHandler {\n\treturn &aboutEndpoint{}\n}", "func (ec *ExtensionClient) UpdateEndpoint(endpoint *extension.ExtensionEndpoint) (res *extension.ExtensionEndpoint, err error) {\n\n\turl := url.QueryEscape(*endpoint.URL)\n\tendpoint.URL = &url\n\tresponse, err := ec.c.UpdateEndpoint()(context.Background(), endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response.(*extension.ExtensionEndpoint), nil\n}", "func NewClient(endpoint string, options ...Option) *Client {\n\tc := &Client{endpoint: endpoint}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tif c.httpClient == nil {\n\t\tc.httpClient = http.DefaultClient\n\t}\n\n\treturn c\n}", "func (sp *SessionProxy) SetEndpoint(sid string, ep Endpoint, timeout time.Duration) {\n\tsp.GetSession().SetEndpoint(sid, ep, timeout)\n}", "func (s *NASInstance) SetEndpoint(v *Endpoint) *NASInstance {\n\ts.Endpoint = v\n\treturn s\n}", "func NewClient(options ...ClientOption) *Client {\n\tclient := &Client{\n\t\tendpoint: Endpoint,\n\t\thttpClient: &http.Client{},\n\t\ttimeout: 5 * time.Second,\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\tclient.httpClient.Timeout = client.timeout\n\n\tif client.instrumentationRegistry != nil {\n\t\ti := instrumentation.New(\"metadata\", client.instrumentationRegistry)\n\t\tclient.httpClient.Transport = i.InstrumentedRoundTripper()\n\t}\n\treturn client\n}", "func NewClient(concat goa.Endpoint) *Client {\n\treturn &Client{\n\t\tConcatEndpoint: concat,\n\t}\n}", "func editEndpointInConfig(t *testing.T, configFilePath, endpoint string) {\n\tvar config cli.Config\n\tb, err := ioutil.ReadFile(configFilePath)\n\trequire.NoError(t, err)\n\n\terr = yaml.Unmarshal(b, &config)\n\trequire.NoError(t, err)\n\n\tconfig.Endpoint = endpoint\n\n\tb, err = yaml.Marshal(&config)\n\trequire.NoError(t, err)\n\n\terr = ioutil.WriteFile(configFilePath, b, 0655)\n\trequire.NoError(t, err)\n\n}", "func (ctr *TaxcodeModule) Endpoint(url *echo.Group) {\n\t// no middleware, there is no auth yet..\n\turl.GET(\"\", ctr.readAll)\n\turl.GET(\"/:id\", ctr.readOne)\n}", "func NewClient(getLicense, updateDeviceLicense, updateDeviceLicenseWithValue goa.Endpoint) *Client {\n\treturn &Client{\n\t\tGetLicenseEndpoint: getLicense,\n\t\tUpdateDeviceLicenseEndpoint: updateDeviceLicense,\n\t\tUpdateDeviceLicenseWithValueEndpoint: updateDeviceLicenseWithValue,\n\t}\n}", "func Endpoint(url string, configureFunc func()) {\n\touterCurrentMockHandler := currentMockHandler\n\tSwitch(extractor.ExtractMethod(), configureFunc)\n\tcurrentMockery.Handle(url, currentMockHandler)\n\tcurrentMockHandler = outerCurrentMockHandler\n}", "func ExampleEndpointsClient_Get_endpointGetExternalWithGeoMapping() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armtrafficmanager.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewEndpointsClient().Get(ctx, \"azuresdkfornetautoresttrafficmanager2191\", \"azuresdkfornetautoresttrafficmanager8224\", armtrafficmanager.EndpointTypeExternalEndpoints, \"My%20external%20endpoint\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Endpoint = armtrafficmanager.Endpoint{\n\t// \tName: to.Ptr(\"My external endpoint\"),\n\t// \tType: to.Ptr(\"Microsoft.Network/trafficManagerProfiles/externalEndpoints\"),\n\t// \tID: to.Ptr(\"/subscriptions/{subscription-id}/resourceGroups/azuresdkfornetautoresttrafficmanager2191/providers/Microsoft.Network/trafficManagerProfiles/azuresdkfornetautoresttrafficmanager8224/externalEndpoints/My external endpoint\"),\n\t// \tProperties: &armtrafficmanager.EndpointProperties{\n\t// \t\tEndpointMonitorStatus: to.Ptr(armtrafficmanager.EndpointMonitorStatusCheckingEndpoint),\n\t// \t\tEndpointStatus: to.Ptr(armtrafficmanager.EndpointStatusEnabled),\n\t// \t\tGeoMapping: []*string{\n\t// \t\t\tto.Ptr(\"GEO-AS\"),\n\t// \t\t\tto.Ptr(\"GEO-AF\")},\n\t// \t\t\tPriority: to.Ptr[int64](1),\n\t// \t\t\tTarget: to.Ptr(\"foobar.contoso.com\"),\n\t// \t\t\tWeight: to.Ptr[int64](1),\n\t// \t\t},\n\t// \t}\n}", "func NewClient(endpoint, token string) Client {\n\treturn Client{\n\t\tGraphQL: graphql.NewClient(fmt.Sprintf(\"%s/api/graphql\", endpoint)),\n\t\tEndpoint: endpoint,\n\t\tToken: token,\n\t}\n}", "func (p *SinglePartition) AddEndpoint(endpoint string) *SinglePartition {\n\tp.Endpoints = append(p.Endpoints, endpoint)\n\treturn p\n}", "func (c *Provider) EndpointConfig() fab.EndpointConfig {\n\treturn c.endpointConfig\n}", "func client(endpoint string) (*elasticsearch.Client, error) {\n\tconfig := elasticsearch.Config{\n\t\tAddresses: []string{endpoint},\n\t}\n\tes, err := elasticsearch.NewClient(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating elastic client\")\n\t}\n\treturn es, nil\n}", "func New(endpoint string) *Client {\n\treturn &Client{endpoint, &http.Client{}, \"\"}\n}", "func (o AuthConfigAzureAdOutput) GraphEndpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AuthConfigAzureAd) pulumi.StringOutput { return v.GraphEndpoint }).(pulumi.StringOutput)\n}", "func WithCollectorEndpoint(options ...CollectorEndpointOption) EndpointOption {\n\treturn endpointOptionFunc(func() (batchUploader, error) {\n\t\tcfg := &collectorEndpointConfig{\n\t\t\tendpoint: envOr(envEndpoint, \"http://localhost:14268/api/traces\"),\n\t\t\tusername: envOr(envUser, \"\"),\n\t\t\tpassword: envOr(envPassword, \"\"),\n\t\t\thttpClient: http.DefaultClient,\n\t\t}\n\n\t\tfor _, opt := range options {\n\t\t\topt.apply(cfg)\n\t\t}\n\n\t\treturn &collectorUploader{\n\t\t\tendpoint: cfg.endpoint,\n\t\t\tusername: cfg.username,\n\t\t\tpassword: cfg.password,\n\t\t\thttpClient: cfg.httpClient,\n\t\t}, nil\n\t})\n}", "func (a *DefaultApiService) CreateEndpoint(ctx _context.Context) ApiCreateEndpointRequest {\n\treturn ApiCreateEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (b *Builder) WithEndpoints(ep ...monitoringv1.Endpoint) *Builder {\n\tb.sm.Spec.Endpoints = append(b.sm.Spec.Endpoints, ep...)\n\treturn b\n}", "func (c *Client) setMetadata(metadata bmc.Metadata) {\n\t// a mutex is created with the NewClient func, in the case\n\t// where a user doesn't call NewClient we handle by checking if\n\t// the mutex is nil\n\tif c.mdLock != nil {\n\t\tc.mdLock.Lock()\n\t\tdefer c.mdLock.Unlock()\n\t}\n\tc.metadata = &metadata\n}", "func (c *Client) Endpoint() string {\n\treturn c.ep\n}", "func NewClient(endpoint string) *Client {\n\treturn &Client{gqlClient: graphql.NewClient(endpoint)}\n}", "func (c *Client) UpdateEndpoint(ctx context.Context, params *UpdateEndpointInput, optFns ...func(*Options)) (*UpdateEndpointOutput, error) {\n\tif params == nil {\n\t\tparams = &UpdateEndpointInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"UpdateEndpoint\", params, optFns, addOperationUpdateEndpointMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*UpdateEndpointOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func newInClusterClient(endpoint string) (*clientWrapper, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create in-cluster configuration: %w\", err)\n\t}\n\n\tif endpoint != \"\" {\n\t\tconfig.Host = endpoint\n\t}\n\n\treturn createClientFromConfig(config)\n}", "func setupFakeClient(url string) *Client {\n\treturn &Client{\n\t\tServiceEndpoint: ServiceEndpoint{\n\t\t\tRequestURL: url,\n\t\t\tDocsURL: \"some-docs-url\",\n\t\t},\n\t}\n}", "func (o AuthConfigAzureAdOutput) AuthEndpoint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AuthConfigAzureAd) pulumi.StringOutput { return v.AuthEndpoint }).(pulumi.StringOutput)\n}", "func NewClient(endpoint string, opts ...ClientOption) *Client {\n\tc := &Client{\n\t\tendpoint: endpoint,\n\t\tLog: func(string) {},\n\t}\n\tfor _, optionFunc := range opts {\n\t\toptionFunc(c)\n\t}\n\tif c.httpClient == nil {\n\t\tc.httpClient = http.DefaultClient\n\t}\n\treturn c\n}" ]
[ "0.7213937", "0.7078036", "0.706247", "0.64092034", "0.63478345", "0.6238432", "0.62370765", "0.6063342", "0.60488373", "0.5863534", "0.5841758", "0.57159245", "0.5684878", "0.56706935", "0.5634435", "0.561928", "0.56167644", "0.55879635", "0.5564246", "0.5520058", "0.5431407", "0.5372452", "0.53671795", "0.5366445", "0.53427804", "0.5330659", "0.5316513", "0.5245909", "0.5226781", "0.52253574", "0.5162501", "0.5162501", "0.5160062", "0.51594955", "0.5146229", "0.5139753", "0.51112807", "0.5098542", "0.5092391", "0.5076911", "0.5074444", "0.5067301", "0.50653833", "0.50421304", "0.5003425", "0.5000039", "0.4997902", "0.49794313", "0.4976005", "0.49744588", "0.4971419", "0.49385658", "0.4935212", "0.4898033", "0.4891561", "0.48905706", "0.48864233", "0.4885577", "0.48807466", "0.48475358", "0.48377046", "0.4829998", "0.48271933", "0.4826785", "0.48196733", "0.48195484", "0.4815943", "0.48153284", "0.47766456", "0.47728997", "0.476957", "0.47693634", "0.476095", "0.47554803", "0.47470054", "0.47323102", "0.4730382", "0.4721714", "0.47068816", "0.46930775", "0.46884274", "0.46810943", "0.46757686", "0.4675003", "0.46738693", "0.46664724", "0.46634734", "0.46568072", "0.46551198", "0.46519226", "0.46382225", "0.46265167", "0.4625505", "0.4625097", "0.46223858", "0.46221164", "0.4615831", "0.4614951", "0.46079606", "0.46072942" ]
0.6812357
3
WithHTTPClient configures a [Client] to perform HTTP requests with httpClient.
func WithHTTPClient(httpClient *http.Client) ClientOption { return func(client *Client) { client.httpClient = httpClient } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithHTTPClient(httpclient *http.Client) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.httpClient = httpclient\n\t}\n}", "func WithHTTPClient(client *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = httpClient\n\t}\n}", "func WithHTTPClient(hClient *http.Client) clientOption {\n\treturn func(c *client) {\n\t\tc.httpClient = hClient\n\t}\n}", "func WithHTTPClient(client HTTPClient) Option {\n\treturn func(opts *Client) {\n\t\topts.httpClient = client\n\t}\n}", "func WithHTTPClient(h *http.Client) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.httpClient = h\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(client *http.Client) func(c *Client) error {\n\treturn func(c *Client) error {\n\t\tif client == nil {\n\t\t\treturn errors.New(\"HTTP client is nil\")\n\t\t}\n\t\tc.client = client\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) Option {\n\treturn func(cfg *config) {\n\t\tcfg.httpClient = httpClient\n\t}\n}", "func WithHTTPClient(c *http.Client) Option {\n\treturn func(args *Client) {\n\t\targs.httpClient = c\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *client) error {\n\t\tif httpClient == nil {\n\t\t\treturn errors.InvalidParameterError{Parameter: \"httpClient\", Reason: \"cannot be empty\"}\n\t\t}\n\n\t\tc.requester.Client = httpClient\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(client *http.Client) Option {\n\treturn func(c *Client) error {\n\t\tif client == nil {\n\t\t\treturn errors.New(\"client cannot be nil\")\n\t\t}\n\n\t\tc.client = client\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.sling.Client(httpClient)\n\t}\n}", "func WithHTTPClient(client *http.Client) OptionFunc {\n\treturn func(c *Client) {\n\t\tc.client = client\n\t}\n}", "func WithHTTPClient(h HTTPClient) ClientOption {\n\treturn clientOptionFunc(func(c interface{}) {\n\t\tswitch c := c.(type) {\n\t\tcase *Client:\n\t\t\tc.httpClient = h\n\t\tdefault:\n\t\t\tpanic(\"unknown type\")\n\t\t}\n\t})\n}", "func (c *Client) WithHTTPClient(cl *http.Client) *Client {\n\tc.Client = cl\n\treturn c\n}", "func WithHTTPClient(c *http.Client) func(*Client) {\n\treturn func(mr *Client) {\n\t\tmr.client = c\n\t}\n}", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) error {\n\t\tif client != nil {\n\t\t\tc.client = client\n\t\t}\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(httpClient ops.HTTPClient) Option {\n\treturn func(o *clientOptions) {\n\t\to.httpClient = httpClient\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) ConfigOption {\n\treturn func(c *Config) {\n\t\tc.httpClient = httpClient\n\t}\n}", "func WithHTTPClient(client *http.Client) Option {\n\treturn func(o *Options) {\n\t\to.Client = client\n\t}\n}", "func SetHTTPClient(httpClient *http.Client) func(*Client) error {\n\treturn func(client *Client) error {\n\t\tclient.client = httpClient\n\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(h *http.Client) Opts {\n\treturn func(r *retryable) {\n\t\tr.httpClient = h\n\t}\n}", "func (c *Client) SetHTTPClient(httpClient HTTPClient) {\n\tif httpClient == nil {\n\t\tc.client = http.DefaultClient\n\t} else {\n\t\tc.client = httpClient\n\t}\n}", "func (c *Client) SetHTTPClient(httpClient HTTPClient) {\n\tc.httpClient = httpClient\n}", "func SetHTTPClient(client *http.Client) {\n\thttpClient = client\n}", "func (c *Client) SetHTTPClient(client *http.Client) {\n\tif client == nil {\n\t\tc.httpClient = http.DefaultClient\n\t\treturn\n\t}\n\tc.httpClient = client\n}", "func WithHTTPClient(httpClient *http.Client) ClientConfigOption {\n\treturn func(c *ClientConfig) {\n\t\tlog.Warn(nil,\n\t\t\tmap[string]interface{}{\"http_transport\": httpClient.Transport},\n\t\t\t\"configuring custom HTTP client for the auth client\")\n\t\tc.httpClient = httpClient\n\t}\n}", "func (c *Client) SetHTTPClient(client *http.Client) {\n\tc.client = client\n}", "func (c *Client) SetHTTPClient(client *http.Client) {\n\tc.client = client\n}", "func WithHTTPClient(hc *http.Client) Option {\n\treturn func(c *gate.Configuration) {\n\t\tc.HTTPClient = hc\n\t}\n}", "func (o *AddSubscriptionsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(client *http.Client) DialOption {\n\treturn optionFn(func(opts *dialOpts) {\n\t\topts.client = client\n\t})\n}", "func withHTTPClient(target *http.Client) ClientOption {\n\treturn func(subject *client) {\n\t\tsubject.client = target\n\t}\n}", "func NewClientWithHTTPClient(httpClient *http.Client) *Client {\n\treturn &Client{\n\t\tHTTPClient: httpClient,\n\t}\n}", "func (o *PostAsyncParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateCrossConnectParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (cb *ClientBuilder) HTTPClient(httpClient *http.Client) *ClientBuilder {\n\tcb.client.httpClient = httpClient\n\treturn cb\n}", "func (cb *ClientBuilder) HTTPClient(httpClient *http.Client) *ClientBuilder {\n\tcb.client.httpClient = httpClient\n\treturn cb\n}", "func (o *HandleGetAboutUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *TestEmailConfigurationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (sm *Manager) SetHTTPClient(c *http.Client) {\n\tsm.client = c\n}", "func (sm *Manager) SetHTTPClient(c *http.Client) {\n\tsm.client = c\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateCartUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *IntegrationsManualHTTPSCreateParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHttpClient(c *http.Client) Option {\n\treturn func(opts *clientOptions) {\n\t\topts.httpClient = c\n\t}\n}", "func WithHttpClient(httpClient HTTPClient) ClientOption {\n\treturn &withHttpClient{httpClient: httpClient}\n}", "func (o *GetItemByAppIDParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ChargeAddonInvoiceParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SendTransacSMSParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func NewWithHTTPClient(sess *session.Session, client *http.Client, endpoint string) Client {\n\treturn Client{\n\t\tsession: sess,\n\t\tendpoint: endpoint,\n\t\thttpClient: client,\n\t}\n}", "func (o *GetContentSourceUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetRequestDetailsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ConfigGetParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *RegisterApplicationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func SetHTTPClient(newClient *http.Client) {\n\thttpClient = newClient\n}", "func (o *OptionsTodoTodoidParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateFeaturesConfigurationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SayParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateGitWebhookUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AuthorizeV3Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AuthorizeV3Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *BudgetAddParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (c *ClientOptions) SetHTTPClient(client *http.Client) *ClientOptions {\n\tc.HTTPClient = client\n\treturn c\n}", "func (o *UpdateSettingsAclsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ConfigListParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateNetworkHTTPServerParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetReceiptsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(c *http.Client) Option {\n\treturn func(insta *Instagram) {\n\t\tinsta.c = c\n\t}\n}", "func (o *GetContentSourcesUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (c Client) WithHttpClient(client *http.Client) *Client {\n\tif client == nil {\n\t\tpanic(\"client must not be nil\")\n\t}\n\tc.httpClient = *client\n\treturn &c\n}", "func (o *PutParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *NearestUsingGET1Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ImportApplicationUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *BasicAuthParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ModifyProxyConfigInternalParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ProvisionNetworkClientsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetSellerServicesUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PayAllInvoicesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PayAllInvoicesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AddItemParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateOrganizationBillingAddressParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func HTTPClient(hc *http.Client) Option {\n\treturn func(c *Client) {\n\t\tc.httpClient = hc\n\t}\n}", "func (o *PostAutoDiscoveryPingsweepParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PostHAProxyConfigurationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *RecommendMultiClusterParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetSubscriptionsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (c *Config) WithHttpClient(client *http.Client) *Config {\n\tc.HTTPClient = client\n\treturn c\n}", "func (o *GetParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}" ]
[ "0.86127514", "0.85565746", "0.8535085", "0.85117996", "0.8440244", "0.8437279", "0.8412249", "0.8390642", "0.83892876", "0.83394164", "0.83181125", "0.83016264", "0.828993", "0.8283331", "0.82613873", "0.8250284", "0.8231563", "0.8224674", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.82111806", "0.8183652", "0.80365115", "0.79901147", "0.7876195", "0.7874432", "0.7868578", "0.77921313", "0.7786922", "0.7768716", "0.7748199", "0.7722947", "0.7722947", "0.77051467", "0.7683122", "0.76230085", "0.76218194", "0.75771207", "0.7554389", "0.75430745", "0.75341815", "0.75341815", "0.7517829", "0.7512439", "0.7509025", "0.7509025", "0.75081694", "0.7505666", "0.74996626", "0.74873793", "0.7479329", "0.7477221", "0.74723566", "0.74657047", "0.7462203", "0.7461502", "0.74565005", "0.74507385", "0.7448253", "0.74368536", "0.74357504", "0.74336565", "0.7417083", "0.74060297", "0.73910934", "0.73910934", "0.7389657", "0.7386947", "0.73781276", "0.7376558", "0.7375521", "0.73748636", "0.73718953", "0.73713577", "0.7364971", "0.7364804", "0.73593366", "0.73589647", "0.73576766", "0.7357593", "0.73571426", "0.73565334", "0.73558253", "0.73558253", "0.73527527", "0.7352573", "0.73411876", "0.7336827", "0.7334035", "0.7332605", "0.7324211", "0.732309", "0.7316422" ]
0.85616064
1
WithInstrumentation configures a [Client] to collect metrics about the performed HTTP requests.
func WithInstrumentation(registry *prometheus.Registry) ClientOption { return func(client *Client) { client.instrumentationRegistry = registry } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func InstrumentHTTPClient(hc *http.Client, n string) {\n\tl := prometheus.Labels{\"controller\": n}\n\n\trt := reqTotal.MustCurryWith(l)\n\trif := reqInFlight.With(l)\n\trl := reqLatency.MustCurryWith(l)\n\trbl := reqEventsLatency.MustCurryWith(l)\n\n\ttrace := &promhttp.InstrumentTrace{\n\t\tDNSStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"dns_start\").Observe(t)\n\t\t},\n\t\tDNSDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"dns_end\").Observe(t)\n\t\t},\n\t\tConnectStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"connect_start\").Observe(t)\n\t\t},\n\t\tConnectDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"connect_end\").Observe(t)\n\t\t},\n\t\tTLSHandshakeStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"tls_start\").Observe(t)\n\t\t},\n\t\tTLSHandshakeDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"tls_end\").Observe(t)\n\t\t},\n\t\tGotFirstResponseByte: func(t float64) {\n\t\t\trbl.WithLabelValues(\"ttfb\").Observe(t)\n\t\t},\n\t}\n\n\thc.Transport = promhttp.InstrumentRoundTripperInFlight(rif,\n\t\tpromhttp.InstrumentRoundTripperCounter(rt,\n\t\t\tpromhttp.InstrumentRoundTripperTrace(trace,\n\t\t\t\tpromhttp.InstrumentRoundTripperDuration(rl, http.DefaultTransport),\n\t\t\t),\n\t\t),\n\t)\n}", "func WithConnectInstrumentation(enabled bool) Option {\n\treturn optionFunc(func(cfg *config) {\n\t\tcfg.instrumentConnect = enabled\n\t})\n}", "func Instrument(router *gin.Engine, appName string) {\n\tsanitizedServiceName := strings.ReplaceAll(appName, \"-\", \"_\")\n\n\t// http localhost:3000/metrics\n\trouter.GET(\"/metrics\", gin.WrapH(promhttp.Handler()))\n\n\trouter.Use(requestMiddleware(sanitizedServiceName))\n}", "func WithHTTPClient(client *http.Client) CollectorEndpointOption {\n\treturn collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {\n\t\to.httpClient = client\n\t})\n}", "func WithBatchInstrumentation(enabled bool) Option {\n\treturn optionFunc(func(cfg *config) {\n\t\tcfg.instrumentBatch = enabled\n\t})\n}", "func WithClient(ctx context.Context, client Client) context.Context {\n\tif client == nil {\n\t\treturn ctx\n\t}\n\treturn context.WithValue(ctx, rfcontext.MetricsClientKey, client)\n}", "func WithQueryInstrumentation(enabled bool) Option {\n\treturn optionFunc(func(cfg *config) {\n\t\tcfg.instrumentQuery = enabled\n\t})\n}", "func (t *Tapa) WithClient(client *http.Client) {\n\tt.client = client\n}", "func WithHTTPClient(c *http.Client) func(*Client) {\n\treturn func(mr *Client) {\n\t\tmr.client = c\n\t}\n}", "func NewMetricsClient(baseURL string) (*MetricsClient, error) {\n\tif baseURL == \"\" {\n\t\treturn nil, errors.New(\"invalid base url\")\n\t}\n\t//if baseURL does not end with an \"/\" it has to be added to the string\n\tif lastChar := baseURL[len(baseURL)-1:]; lastChar != \"/\" {\n\t\tbaseURL += \"/\"\n\t}\n\tclientData := clientData{baseURL: baseURL, resty: resty.New(), useAuth: false}\n\tnewClient := client{&clientData}\n\treturn &MetricsClient{newClient}, nil\n}", "func (t *TestRuntime) CompileRequestWithInstrumentation(req types.CompileRequestV1) (*types.CompileResponseV1, error) {\n\treturn t.compileRequest(req, true)\n}", "func Instrument(\n\tmethod,\n\tpath string,\n\taction func(*models.ReqContext) response.Response,\n\tmetrics *API,\n) web.Handler {\n\tnormalizedPath := MakeLabelValue(path)\n\n\treturn func(c *models.ReqContext) {\n\t\tstart := time.Now()\n\t\tres := action(c)\n\n\t\t// TODO: We could look up the datasource type via our datasource service\n\t\tvar backend string\n\t\tdatasourceID := web.Params(c.Req)[\":DatasourceID\"]\n\t\tif datasourceID == apimodels.GrafanaBackend.String() || datasourceID == \"\" {\n\t\t\tbackend = GrafanaBackend\n\t\t} else {\n\t\t\tbackend = ProxyBackend\n\t\t}\n\n\t\tls := prometheus.Labels{\n\t\t\t\"method\": method,\n\t\t\t\"route\": normalizedPath,\n\t\t\t\"status_code\": fmt.Sprint(res.Status()),\n\t\t\t\"backend\": backend,\n\t\t}\n\t\tres.WriteTo(c)\n\t\tmetrics.RequestDuration.With(ls).Observe(time.Since(start).Seconds())\n\t}\n}", "func newInstruments(registerer prometheus.Registerer) (*instruments, error) {\n\tapiCallsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallsTotal,\n\t\tHelp: \"Total number of SDK API calls from the customer's code to AWS services\",\n\t}, []string{labelService, labelOperation, labelStatusCode, labelErrorCode})\n\tapiCallDurationSeconds := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallDurationSeconds,\n\t\tHelp: \"Perceived latency from when your code makes an SDK call, includes retries\",\n\t}, []string{labelService, labelOperation})\n\tapiCallRetries := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPICallRetries,\n\t\tHelp: \"Number of times the SDK retried requests to AWS services for SDK API calls\",\n\t\tBuckets: []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},\n\t}, []string{labelService, labelOperation})\n\n\tapiRequestsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPIRequestsTotal,\n\t\tHelp: \"Total number of HTTP requests that the SDK made\",\n\t}, []string{labelService, labelOperation, labelStatusCode, labelErrorCode})\n\tapiRequestDurationSecond := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tSubsystem: metricSubsystemAWS,\n\t\tName: metricAPIRequestDurationSeconds,\n\t\tHelp: \"Latency of an individual HTTP request to the service endpoint\",\n\t}, []string{labelService, labelOperation})\n\n\tif err := registerer.Register(apiCallsTotal); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiCallDurationSeconds); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiCallRetries); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiRequestsTotal); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := registerer.Register(apiRequestDurationSecond); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &instruments{\n\t\tapiCallsTotal: apiCallsTotal,\n\t\tapiCallDurationSeconds: apiCallDurationSeconds,\n\t\tapiCallRetries: apiCallRetries,\n\t\tapiRequestsTotal: apiRequestsTotal,\n\t\tapiRequestDurationSecond: apiRequestDurationSecond,\n\t}, nil\n}", "func Instrument(app *echo.Echo) {\n\tapp.Use(middleware)\n}", "func NewInstrumentedHTTPClient(n string) *http.Client {\n\tc := http.Client{}\n\tInstrumentHTTPClient(&c, n)\n\treturn &c\n}", "func (c *HTTPClientMock) With(headers map[string]string) HTTPClientInterface {\n\tc.headers = headers\n\treturn c\n}", "func NewClientMetrics(scope tally.Scope) *ClientMetrics {\n\tclientAPIScope := scope.SubScope(\"api\")\n\tclientSuccessScope := scope.Tagged(map[string]string{\"result\": \"success\"})\n\tclientFailScope := scope.Tagged(map[string]string{\"result\": \"fail\"})\n\treturn &ClientMetrics{\n\t\tEventsConsumed: scope.Counter(\"eventsConsumed\"),\n\t\tStreamIDChange: scope.Counter(\"streamIdChange\"),\n\t\tPurgeOffset: scope.Gauge(\"purgeOffset\"),\n\t\tInitStreamAPI: clientAPIScope.Counter(\"initStream\"),\n\t\tInitStreamSuccess: clientSuccessScope.Counter(\"initStream\"),\n\t\tInitStreamFail: clientFailScope.Counter(\"initStream\"),\n\t\tWaitForEventsAPI: clientAPIScope.Counter(\"waitForEvents\"),\n\t\tWaitForEventsSuccess: clientSuccessScope.Counter(\"waitForEvents\"),\n\t\tWaitForEventsFailed: clientFailScope.Counter(\"waitForEvents\"),\n\t}\n}", "func withHTTPClient(target *http.Client) ClientOption {\n\treturn func(subject *client) {\n\t\tsubject.client = target\n\t}\n}", "func Setup(k8sClient *k8s.Client, prometheusURL *string, watchInterval time.Duration) *Client {\n\tclient := &Client{\n\t\tmetrics: setupMetrics(),\n\t\tservices: []k8s.FunctionStatus{},\n\t\twatchInterval: watchInterval,\n\t\tk8sClient: k8sClient,\n\t}\n\n\tif prometheusURL != nil {\n\t\tclient.promrc = resty.New().\n\t\t\tSetHostURL(*prometheusURL + \"/api/v1\").\n\t\t\tSetLogger(ioutil.Discard).\n\t\t\tSetRetryCount(3).\n\t\t\tSetTimeout(10 * time.Second)\n\t}\n\n\tprometheus.MustRegister(client)\n\treturn client\n}", "func MetricsMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tmetrics.HTTPRequestCount.With(prometheus.Labels{\n\t\t\t\"method\": c.Request.Method,\n\t\t\t\"path\": c.Request.URL.Path,\n\t\t}).Inc()\n\t\tbegin := time.Now()\n\t\tc.Next()\n\t\tmetrics.HTTPRequestLatencyHistogramMilliseconds.With(prometheus.Labels{\n\t\t\t\"method\": c.Request.Method,\n\t\t\t\"path\": c.Request.URL.Path,\n\t\t}).Observe(float64(time.Now().Sub(begin).Milliseconds()))\n\t\tmetrics.HTTPRequestLatencySummaryMilliseconds.With(prometheus.Labels{\n\t\t\t\"method\": c.Request.Method,\n\t\t\t\"path\": c.Request.URL.Path,\n\t\t}).Observe(float64(time.Now().Sub(begin).Milliseconds()))\n\t}\n}", "func WithCollector(coll Collector) ClientOption {\n\treturn func(c *Client) {\n\t\tc.collector = coll\n\t}\n}", "func Middleware(client Client) gin.HandlerFunc {\n\t// Initialize and configure the client and set options if given.\n\tcc := newConfiguredClient(client)\n\n\treturn func(c *gin.Context) {\n\t\tlog.Debug(\"Starting Statsd middleware\")\n\t\tstart := time.Now()\n\t\tc.Next()\n\n\t\thandler := c.HandlerName()\n\t\tcc.IncrThroughput(handler)\n\t\tcc.IncrStatusCode(c.Writer.Status(), handler)\n\t\tcc.IncrSuccess(c.Errors, handler)\n\t\tcc.IncrError(c.Errors, handler)\n\t\tcc.Timing(start, handler)\n\t}\n}", "func WithClientTracing(client *http.Client) error {\n\tprev := client.Transport\n\tclient.Transport = &ochttp.Transport{\n\t\tBase: prev,\n\t\tPropagation: tracecontextb3.TraceContextEgress,\n\t}\n\treturn nil\n}", "func InstrumentingMiddleware(metrics *Metrics) Middleware {\n\treturn func(next Service) Service {\n\t\treturn Metrics{\n\t\t\tInts: metrics.Ints,\n\t\t\tChars: metrics.Chars,\n\t\t\tRefs: metrics.Refs,\n\t\t\tBeats: metrics.Beats,\n\t\t\tDuration: metrics.Duration,\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func (h Metrics) Instrument(rw http.ResponseWriter, next http.HandlerFunc, endpoint string) http.HandlerFunc {\n\tlabels := prometheus.Labels{}\n\tlabelsWithEndpoint := prometheus.Labels{\"endpoint\": endpoint}\n\tif status, _ := httpx.GetResponseMeta(rw); status != 0 {\n\t\tlabels = prometheus.Labels{\"code\": strconv.Itoa(status)}\n\t\tlabelsWithEndpoint[\"code\"] = labels[\"code\"]\n\t}\n\twrapped := promhttp.InstrumentHandlerResponseSize(h.responseSize.MustCurryWith(labels), next)\n\twrapped = promhttp.InstrumentHandlerCounter(h.totalRequests.MustCurryWith(labelsWithEndpoint), wrapped)\n\twrapped = promhttp.InstrumentHandlerDuration(h.duration.MustCurryWith(labelsWithEndpoint), wrapped)\n\twrapped = promhttp.InstrumentHandlerDuration(h.responseTime.MustCurryWith(prometheus.Labels{\"endpoint\": endpoint}), wrapped)\n\twrapped = promhttp.InstrumentHandlerRequestSize(h.requestSize.MustCurryWith(labels), wrapped)\n\twrapped = h.instrumentHandlerStatusBucket(wrapped)\n\n\treturn wrapped.ServeHTTP\n}", "func WithHTTPClient(client *http.Client) func(c *Client) error {\n\treturn func(c *Client) error {\n\t\tif client == nil {\n\t\t\treturn errors.New(\"HTTP client is nil\")\n\t\t}\n\t\tc.client = client\n\t\treturn nil\n\t}\n}", "func WithInstrumentation(tp trace.TracerProvider, mp metric.MeterProvider, log logr.Logger) CompositeOperatorOption {\n\treturn func(c *CompositeOperator) {\n\t\tc.inst = telemetry.NewInstrumentationWithProviders(instrumentationName, tp, mp, log)\n\t}\n}", "func setupMetrics() *Metrics {\n\t// Requests duration\n\tduration := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"http_request_duration\",\n\t\tHelp: \"Duration of the http requests processed.\",\n\t},\n\t\t[]string{\"status\", \"method\", \"path\"},\n\t)\n\tprometheus.MustRegister(duration)\n\n\treturn &Metrics{\n\t\tduration: duration,\n\t}\n}", "func NewInstrumentationInitializer(configuration *InstrumentationConfiguration) *InstrumentationInitializer {\n\treturn &InstrumentationInitializer{\n\t\tconfiguration: configuration,\n\t}\n}", "func WithMetrics(m metrics.Metrics) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\ttimer := m.Timer(\"grpc.request_duration\")\n\t\ttimer.Start()\n\n\t\tresp, err := handler(ctx, req)\n\t\ttimer.\n\t\t\tWithTag(\"rpc_method\", info.FullMethod).\n\t\t\tWithTag(\"success\", err == nil).\n\t\t\tStop()\n\n\t\treturn resp, err\n\t}\n}", "func InstrumentingMiddleware(label string) mux.MiddlewareFunc {\n\n\thttpTotal := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.total\", label))\n\thttp2xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.2xx\", label))\n\thttp3xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.3xx\", label))\n\thttp4xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.4xx\", label))\n\thttp5xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.5xx\", label))\n\thttpLatency := kitexpvar.NewHistogram(fmt.Sprintf(\"%s.http.latency\", label), 50)\n\n\treturn mux.MiddlewareFunc(func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\thttpTotal.Add(1)\n\t\t\tiw := &interceptingHttpWriter{delegate: w}\n\t\t\tdefer func(begin time.Time) {\n\t\t\t\tswitch sc := iw.statusCode; {\n\t\t\t\tcase sc >= 200 && sc < 300:\n\t\t\t\t\thttp2xx.Add(1)\n\t\t\t\tcase sc >= 300 && sc < 400:\n\t\t\t\t\thttp3xx.Add(1)\n\t\t\t\tcase sc >= 400 && sc < 500:\n\t\t\t\t\thttp4xx.Add(1)\n\t\t\t\tcase sc >= 500 && sc < 600:\n\t\t\t\t\thttp5xx.Add(1)\n\t\t\t\t}\n\t\t\t\thttpLatency.Observe(time.Since(begin).Seconds() * 1000)\n\n\t\t\t}(time.Now())\n\n\t\t\tnext.ServeHTTP(iw, r)\n\t\t})\n\t})\n}", "func (c *Client) WithHTTPClient(cl *http.Client) *Client {\n\tc.Client = cl\n\treturn c\n}", "func InitMetrics(client kubernetes.Interface, scrapeInterval time.Duration) http.Handler {\n\tm := metrics{\n\t\tk8sGardenClient: client,\n\t\tinterval: scrapeInterval,\n\t}\n\tm.initShootMetrics()\n\tm.initProjectCountMetric()\n\tm.initUserCountMetric()\n\treturn promhttp.Handler()\n}", "func WithHTTPClient(hClient *http.Client) clientOption {\n\treturn func(c *client) {\n\t\tc.httpClient = hClient\n\t}\n}", "func WithHTTPClient(httpclient *http.Client) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.httpClient = httpclient\n\t}\n}", "func withClient(cassetteName string, f func(*Client)) {\n\twithCassette(cassetteName, func(r *recorder.Recorder) {\n\t\tc := NewClient(DynCustomerName)\n\t\tc.SetTransport(r)\n\t\tc.Verbose(true)\n\n\t\tf(c)\n\t})\n}", "func MetricsMiddleware(svc exapp.Service, counter metrics.Counter, latency metrics.Histogram) exapp.Service {\n\treturn &metricsMiddleware{\n\t\tcounter: counter,\n\t\tlatency: latency,\n\t\tsvc: svc,\n\t}\n}", "func NewInstrumentedClient(c *rpc.Client, m *metrics.Metrics) *InstrumentedClient {\n\treturn &InstrumentedClient{\n\t\tc: ethclient.NewClient(c),\n\t\tm: m,\n\t}\n}", "func (o *GetMetricsParams) WithHTTPClient(client *http.Client) *GetMetricsParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func WithHTTPClient(client *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func WithMetricsResponderMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodGet && r.URL.Path == \"/metrics\" {\n\t\t\tpromhttp.Handler().ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (it *IssueTracker) InstrumentMiddleware(r *http.Request) error {\n\tif it.AuthCfg == nil || it.AuthCfg.Type == config.AuthTypeNone {\n\t\treturn nil\n\t} else if it.AuthCfg.Type != config.AuthTypeOffline {\n\t\treturn fmt.Errorf(\"unsupported authentication token type for jira: %s\", it.AuthCfg.Type)\n\t}\n\n\tcommon.Assert(it.AuthCfg.Token != \"\", \"authentication token is empty\")\n\tr.Header.Add(\"Authorization\", \"Bearer \"+it.AuthCfg.Token)\n\treturn nil\n}", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func WithHTTPClient(hc *http.Client) Option {\n\treturn func(c *gate.Configuration) {\n\t\tc.HTTPClient = hc\n\t}\n}", "func NewInstrumentationSvc(db *db.Datastore, settings earthworks.Settings) *InstrumentationSvc {\n\trepo := instrRepo.NewInstrumentationRepo(db)\n\n\tsvc := &InstrumentationSvc{\n\t\tRepo: repo,\n\t\tSettings: settings,\n\t}\n\treturn svc\n}", "func WithHTTPClient(client HTTPClient) Option {\n\treturn func(opts *Client) {\n\t\topts.httpClient = client\n\t}\n}", "func WithHTTPClient(h *http.Client) Opts {\n\treturn func(r *retryable) {\n\t\tr.httpClient = h\n\t}\n}", "func WithAnalytics(on bool) ClientOption {\n\treturn func(cfg *clientConfig) {\n\t\tif on {\n\t\t\tcfg.analyticsRate = 1.0\n\t\t} else {\n\t\t\tcfg.analyticsRate = math.NaN()\n\t\t}\n\t}\n}", "func NewInstrumentingService(counter metrics.Counter, latency metrics.Histogram, countResult metrics.Histogram, s Service) Service {\n\treturn &instrumentingMiddleware{\n\t\trequestCount: counter,\n\t\trequestLatency: latency,\n\t\tcountResult: countResult,\n\t\tnext: s,\n\t}\n}", "func WithHTTPClient(cli *http.Client) OptFunc {\n\treturn func(c *DNS1Cloud) {\n\t\tc.client = cli\n\t}\n}", "func WithHTTPClient(h HTTPClient) ClientOption {\n\treturn clientOptionFunc(func(c interface{}) {\n\t\tswitch c := c.(type) {\n\t\tcase *Client:\n\t\t\tc.httpClient = h\n\t\tdefault:\n\t\t\tpanic(\"unknown type\")\n\t\t}\n\t})\n}", "func TestAget_Client_TelemetryConfiguration(t *testing.T) {\n\tassert := assert.New(t)\n\n\tconf := DefaultConfig()\n\tconf.DevMode = true\n\tconf.Telemetry.DisableTaggedMetrics = true\n\tconf.Telemetry.BackwardsCompatibleMetrics = true\n\n\ta := &Agent{config: conf}\n\n\tc, err := a.clientConfig()\n\tassert.Nil(err)\n\n\ttelemetry := conf.Telemetry\n\n\tassert.Equal(c.StatsCollectionInterval, telemetry.collectionInterval)\n\tassert.Equal(c.PublishNodeMetrics, telemetry.PublishNodeMetrics)\n\tassert.Equal(c.PublishAllocationMetrics, telemetry.PublishAllocationMetrics)\n\tassert.Equal(c.DisableTaggedMetrics, telemetry.DisableTaggedMetrics)\n\tassert.Equal(c.BackwardsCompatibleMetrics, telemetry.BackwardsCompatibleMetrics)\n}", "func NewInstrumentation(component component.Component, logger log.Logger, reg prometheus.Registerer) *InstrumentationProbe {\n\tp := InstrumentationProbe{\n\t\tcomponent: component,\n\t\tlogger: logger,\n\t\tstatusMetric: promauto.With(reg).NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tName: \"status\",\n\t\t\tHelp: \"Represents status (0 indicates failure, 1 indicates success) of the component.\",\n\t\t\tConstLabels: map[string]string{\"component\": component.String()},\n\t\t},\n\t\t\t[]string{\"check\"},\n\t\t),\n\t}\n\treturn &p\n}", "func (o *GetMetricsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(c *http.Client) Option {\n\treturn func(insta *Instagram) {\n\t\tinsta.c = c\n\t}\n}", "func NewVMInsightsClient(con *armcore.Connection) *VMInsightsClient {\n\treturn &VMInsightsClient{con: con}\n}", "func HTTPClient(client *http.Client) HTTPOption {\n\treturn func(c *HTTPCollector) { c.client = client }\n}", "func WithClientMiddleware(middleware ...ClientMiddleware) ClientOption {\n\treturn func(c *clientCreator) {\n\t\tc.middleware = middleware\n\t}\n}", "func WithHTTPClient(client *http.Client) OptionFunc {\n\treturn func(c *Client) {\n\t\tc.client = client\n\t}\n}", "func (im *instrumentingMiddleware) instrumenting(begin time.Time, method string, err error) {\n\tim.requestCount.With(\"method\", method).Add(1)\n\tif err != nil {\n\t\tim.requestError.With(\"method\", method).Add(1)\n\t}\n\tim.requestLatency.With(\"method\", method).Observe(time.Since(begin).Seconds())\n}", "func WithClient(c *http.Client) TransportOption {\n\treturn func(tr *Transport) {\n\t\ttr.client = c\n\t}\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.httpClient = httpClient\n\t}\n}", "func WithHTTPClient(h *http.Client) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.httpClient = h\n\t\treturn nil\n\t}\n}", "func NewMetricsClient(credential azcore.TokenCredential, options *MetricsClientOptions) (*MetricsClient, error) {\n\tif options == nil {\n\t\toptions = &MetricsClientOptions{}\n\t}\n\tif reflect.ValueOf(options.Cloud).IsZero() {\n\t\toptions.Cloud = cloud.AzurePublic\n\t}\n\tc, ok := options.Cloud.Services[ServiceNameMetrics]\n\tif !ok || c.Audience == \"\" || c.Endpoint == \"\" {\n\t\treturn nil, errors.New(\"provided Cloud field is missing Azure Monitor Metrics configuration\")\n\t}\n\n\tauthPolicy := runtime.NewBearerTokenPolicy(credential, []string{c.Audience + \"/.default\"}, nil)\n\tpl := runtime.NewPipeline(moduleName, version, runtime.PipelineOptions{PerRetry: []policy.Policy{authPolicy}}, &options.ClientOptions)\n\treturn &MetricsClient{host: c.Endpoint, pl: pl}, nil\n}", "func New(prometheusURL string) *Client {\n\treturn &Client{\n\t\trc: resty.New().\n\t\t\tSetHostURL(prometheusURL + \"/api/v1\").\n\t\t\tSetLogger(ioutil.Discard).\n\t\t\tSetRetryCount(3).\n\t\t\tSetTimeout(10 * time.Second),\n\t}\n}", "func Instrument(opts flagutil.InstrumentationOptions) {\n\tServe(opts.PProfPort)\n\tif opts.ProfileMemory {\n\t\tWriteMemoryProfiles(opts.MemoryProfileInterval)\n\t}\n}", "func TestDo_TelemetryEnabled(t *testing.T) {\n\ttype testServerResponse struct {\n\t\tAPIResource\n\t\tMessage string `json:\"message\"`\n\t}\n\n\ttype requestMetrics struct {\n\t\tRequestDurationMS int `json:\"request_duration_ms\"`\n\t\tRequestID string `json:\"request_id\"`\n\t}\n\n\ttype requestTelemetry struct {\n\t\tLastRequestMetrics requestMetrics `json:\"last_request_metrics\"`\n\t}\n\n\tmessage := \"Hello, client.\"\n\trequestNum := 0\n\n\ttestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trequestNum++\n\n\t\ttelemetryStr := r.Header.Get(\"X-Stripe-Client-Telemetry\")\n\t\tswitch requestNum {\n\t\tcase 1:\n\t\t\t// the first request should not receive any metrics\n\t\t\tassert.Equal(t, telemetryStr, \"\")\n\t\t\ttime.Sleep(21 * time.Millisecond)\n\t\tcase 2:\n\t\t\tassert.True(t, len(telemetryStr) > 0, \"telemetryStr should not be empty\")\n\n\t\t\t// the telemetry should properly unmarshal into RequestTelemetry\n\t\t\tvar telemetry requestTelemetry\n\t\t\terr := json.Unmarshal([]byte(telemetryStr), &telemetry)\n\t\t\tassert.NoError(t, err)\n\n\t\t\t// the second request should include the metrics for the first request\n\t\t\tassert.Equal(t, telemetry.LastRequestMetrics.RequestID, \"req_1\")\n\t\t\tassert.True(t, telemetry.LastRequestMetrics.RequestDurationMS > 20,\n\t\t\t\t\"request_duration_ms should be > 20ms\")\n\t\tdefault:\n\t\t\tassert.Fail(t, \"Should not have reached request %v\", requestNum)\n\t\t}\n\n\t\tw.Header().Set(\"Request-Id\", fmt.Sprintf(\"req_%d\", requestNum))\n\t\tresponse := testServerResponse{Message: message}\n\n\t\tdata, err := json.Marshal(response)\n\t\tassert.NoError(t, err)\n\n\t\t_, err = w.Write(data)\n\t\tassert.NoError(t, err)\n\t}))\n\tdefer testServer.Close()\n\n\tbackend := GetBackendWithConfig(\n\t\tAPIBackend,\n\t\t&BackendConfig{\n\t\t\tEnableTelemetry: Bool(true),\n\t\t\tLeveledLogger: debugLeveledLogger,\n\t\t\tMaxNetworkRetries: Int64(0),\n\t\t\tURL: String(testServer.URL),\n\t\t},\n\t).(*BackendImplementation)\n\n\tfor i := 0; i < 2; i++ {\n\t\trequest, err := backend.NewRequest(\n\t\t\thttp.MethodGet,\n\t\t\t\"/hello\",\n\t\t\t\"sk_test_123\",\n\t\t\t\"application/x-www-form-urlencoded\",\n\t\t\tnil,\n\t\t)\n\t\tassert.NoError(t, err)\n\n\t\tvar response testServerResponse\n\t\terr = backend.Do(request, nil, &response)\n\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, message, response.Message)\n\t}\n\n\t// We should have seen exactly two requests.\n\tassert.Equal(t, 2, requestNum)\n}", "func NewMetricsClient(client ClientInterface) *MetricsClient {\n\treturn &MetricsClient{\n\t\tclient: client,\n\t}\n}", "func NewClient(options ...ClientOption) *Client {\n\tclient := &Client{\n\t\tendpoint: Endpoint,\n\t\thttpClient: &http.Client{},\n\t\ttimeout: 5 * time.Second,\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\tclient.httpClient.Timeout = client.timeout\n\n\tif client.instrumentationRegistry != nil {\n\t\ti := instrumentation.New(\"metadata\", client.instrumentationRegistry)\n\t\tclient.httpClient.Transport = i.InstrumentedRoundTripper()\n\t}\n\treturn client\n}", "func WithClient(client *http.Client) Option {\n\treturn func(o *Options) {\n\t\to.HTTPClient = client\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(doer HttpRequestDoer) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.Client = doer\n\t\treturn nil\n\t}\n}", "func TelemetryHarvesterWithMetricsURL(url string) TelemetryHarvesterOpt {\n\treturn func(config *telemetry.Config) {\n\t\tconfig.MetricsURLOverride = url\n\t}\n}", "func TelemetryHarvesterWithMetricsURL(url string) TelemetryHarvesterOpt {\n\treturn func(config *telemetry.Config) {\n\t\tconfig.MetricsURLOverride = url\n\t}\n}", "func (o *GetCountersParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(c *http.Client) Option {\n\treturn func(args *Client) {\n\t\targs.httpClient = c\n\t}\n}", "func Setup(ctx context.Context, logger *logging.BaseLogger, promReqd bool) (*PerformanceClient, error) {\n\tclients, err := test.NewClients(pkgTest.Flags.Kubeconfig, pkgTest.Flags.Cluster, test.ServingNamespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p *prometheus.PromProxy\n\tif promReqd {\n\t\tlogger.Infof(\"Creating prometheus proxy client\")\n\t\tp = &prometheus.PromProxy{Namespace: monitoringNS}\n\t\tp.Setup(ctx, logger)\n\t}\n\treturn &PerformanceClient{E2EClients: clients, PromClient: p}, nil\n}", "func DefaultInstrumentationConfig() *cfg.InstrumentationConfig {\n\treturn &cfg.InstrumentationConfig{\n\t\tPrometheus: true,\n\t\tPrometheusListenAddr: \":26660\",\n\t\tMaxOpenConnections: 3,\n\t\tNamespace: \"tendermint\",\n\t}\n}", "func WithMetricsTLSClientConfig(tlsCfg *tls.Config) Option {\n\treturn wrappedOption{otlpconfig.WithMetricsTLSClientConfig(tlsCfg)}\n}", "func (o *MultipleMetricsParams) WithHTTPClient(client *http.Client) *MultipleMetricsParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.sling.Client(httpClient)\n\t}\n}", "func NewWithClient(chainID string, client SignStatusClient) provider.Provider {\n\treturn &http{\n\t\tchainID: chainID,\n\t\tclient: client,\n\t}\n}", "func MetricsMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := time.Now()\n\n\t\t// Call next to jump into the next handler.\n\t\tc.Next()\n\n\t\ttook := time.Since(t).String()\n\n\t\tlog.\n\t\t\tWith(\n\t\t\t\tzap.String(\"path\", c.Request.RequestURI),\n\t\t\t\tzap.String(\"took\", took),\n\t\t\t).\n\t\t\tDebug(\"request end\")\n\t}\n}", "func (htpc *HttpProcessorConfig) Client(httpClient *http.Client) *HttpProcessorConfig {\n\thtpc.customClient = httpClient\n\treturn htpc\n}", "func WithHTTPClient(cli *http.Client) EnforcerOption {\n\treturn func(e *Enforcer) {\n\t\te.cli = cli\n\t}\n}", "func WithClientTrace(ctx context.Context, trace *httptrace.ClientTrace,) context.Context", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) error {\n\t\tif client != nil {\n\t\t\tc.client = client\n\t\t}\n\t\treturn nil\n\t}\n}", "func NewInsightsAnnotator(version string, refBaseURL string) *InsightsAnnotator {\n\n\ta := &InsightsAnnotator{\n\t\tversion: version,\n\t\trefBaseURL: refBaseURL,\n\t}\n\treturn a\n}", "func WithHystrixClient(client *hystrix.Client) Option {\n\treturn func(c *Client) {\n\t\tc.client = client\n\t}\n}", "func NewMetricsMiddleware(metricsReporter MetricsReporter) endpoint.Middleware {\n\treturn func(next endpoint.Endpoint) endpoint.Endpoint {\n\t\treturn func(ctx context.Context, request interface{}) (resp interface{}, err error) {\n\t\t\tdefer func(startTime time.Time) {\n\t\t\t\tmetricsReporter.ReportRequest(ctx, startTime, ctxRequestPath(ctx), err)\n\t\t\t}(time.Now())\n\t\t\treturn next(ctx, request)\n\t\t}\n\t}\n}", "func ConfigureClient(g *backpressure.Backpressure, c *autorest.Client) {\n\tc.SendDecorators = append([]autorest.SendDecorator{\n\t\t// NOTE: Order matters here since these decorators are executed in\n\t\t// order. See: https://godoc.org/github.com/Azure/go-autorest/autorest#Client\n\t\tRateLimitCircuitBreaker(g),\n\t}, c.SendDecorators...)\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = httpClient\n\t}\n}" ]
[ "0.66450715", "0.57776076", "0.5625743", "0.5623829", "0.55426776", "0.54963595", "0.5488912", "0.53573555", "0.5343014", "0.533868", "0.5337256", "0.5327033", "0.5325875", "0.5289972", "0.52883774", "0.52568847", "0.5230205", "0.52299607", "0.52267617", "0.52261263", "0.5195995", "0.5189046", "0.5169497", "0.515516", "0.51464254", "0.5111504", "0.5084847", "0.5074409", "0.5061838", "0.5051865", "0.5049406", "0.5045399", "0.5045254", "0.50389487", "0.5029674", "0.5015135", "0.50096965", "0.49927318", "0.4980811", "0.49773592", "0.49605656", "0.4960028", "0.49523586", "0.4947146", "0.492837", "0.49239236", "0.49238187", "0.4916798", "0.49073416", "0.4902052", "0.49006736", "0.48977223", "0.4886697", "0.4885565", "0.48848903", "0.48778412", "0.48730338", "0.48573744", "0.48545155", "0.4854344", "0.4853452", "0.48472053", "0.4846406", "0.4842285", "0.4830865", "0.48303103", "0.48279876", "0.48259833", "0.48243052", "0.48199406", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.4816536", "0.48133227", "0.48133227", "0.48002478", "0.47983524", "0.47956586", "0.47916436", "0.47913054", "0.47902724", "0.47888973", "0.4785154", "0.47819304", "0.47797593", "0.47776106", "0.4772503", "0.4770785", "0.47688413", "0.47624153", "0.47583473", "0.47582492", "0.47527772" ]
0.7786068
0
WithTimeout specifies a time limit for requests made by this [Client]. Defaults to 5 seconds.
func WithTimeout(timeout time.Duration) ClientOption { return func(client *Client) { client.timeout = timeout } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithTimeout(t time.Duration) Option {\n\treturn func(c *Client) { c.httpClient.Timeout = t }\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(c *Client) {\n\t\tc.client.Timeout = timeout\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(c *Client) {\n\t\tc.client.Timeout = timeout\n\t}\n}", "func WithTimeout(timeout time.Duration) Opt {\n\treturn func(c *Client) error {\n\t\tc.client.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func WithTimeout(timeout time.Duration) ClientOption {\n\treturn withTimeout{timeout}\n}", "func (c *Client) Timeout(t time.Duration) *Client {\n\tc.client.Timeout = t\n\treturn c\n}", "func WithTimeout(timeout time.Duration) ClientOption {\n\treturn optionFunc(func(c *Client) {\n\t\tc.WithTimeout(timeout)\n\t})\n}", "func Timeout(timeout time.Duration) Option {\n\treturn func(client *http.Client) {\n\t\tclient.Timeout = timeout\n\t}\n}", "func Timeout(timeout time.Duration) Option {\n\treturn func(client *http.Client) {\n\t\tclient.Timeout = timeout\n\t}\n}", "func Timeout(t time.Duration) ClientOpt {\n\treturn func(c *Client) {\n\t\tc.HTTPClient.Timeout = t\n\t}\n}", "func (c *Client) WithTimeout(timeout time.Duration) *Client {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tc.httpClient.Timeout = timeout\n\treturn c\n}", "func WithTimeout(timeout time.Duration) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.timeout = timeout\n\t\treturn nil\n\t}\n}", "func RequestTimeout(x time.Duration) func(*Client) {\n\treturn func(client *Client) {\n\t\tclient.HttpClient.Timeout = x * time.Second\n\t}\n}", "func clientWithTimeout(timeout time.Duration) *http.Client {\n tr := &http.Transport{\n ResponseHeaderTimeout: timeout,\n Dial: (&net.Dialer{\n Timeout: timeout,\n KeepAlive: time.Second,\n }).Dial,\n TLSHandshakeTimeout: timeout,\n MaxIdleConnsPerHost: 100,\n }\n return &http.Client{\n Timeout: timeout,\n Transport: tr,\n }\n}", "func SetTimeout(timeout time.Duration) {\n\tclient.SetTimeout(timeout)\n}", "func (c *Client) SetTimeout(timeout time.Duration) {\n\tif timeout.Seconds() <= 0 || timeout.Seconds() > 3600 {\n\t\ttimeout = 60 * time.Second\n\t}\n\n\tc.timeout = timeout\n\tc.newHttpClient()\n}", "func OptTimeout(d time.Duration) Option {\n\treturn func(r *Request) error {\n\t\tif r.Client == nil {\n\t\t\tr.Client = &http.Client{}\n\t\t}\n\t\tr.Client.Timeout = d\n\t\treturn nil\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(opts *VDRI) {\n\t\topts.client.Timeout = timeout\n\t}\n}", "func (r *Request) Timeout(t time.Duration) *Request {\n\tr.timeout = t\n\treturn r\n}", "func (o *Request) WithTimeout(timeout time.Duration) *Request {\n\to.ensureClient()\n\n\to.Client.Timeout = timeout\n\treturn o\n}", "func (c *Client) SetTimeout(timeout time.Duration) {\n\tif c.HTTPClient == nil {\n\t\tc.HTTPClient = defaultHTTPClient()\n\t}\n\tc.HTTPClient.Timeout = timeout\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(o *options) {\n\t\to.timeout = timeout\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(o *options) {\n\t\to.timeout = timeout\n\t}\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(opts *Options) {\n\t\topts.Timeout = timeout\n\t}\n}", "func Timeout(t time.Duration) RequestOption {\n\treturn func(o *RequestOptions) {\n\t\to.Timeout = t\n\t}\n}", "func WithTimeout(timeout time.Duration) configF {\n\treturn func(c *config) *config {\n\t\tc.defaultTimeout = timeout\n\t\treturn c\n\t}\n}", "func Timeout(timeout time.Duration) OptionFunc {\n\treturn func(tc *TracedClient) error {\n\t\tif timeout <= 0 {\n\t\t\treturn errors.New(\"timeout must be positive\")\n\t\t}\n\t\ttc.cl.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func Timeout(d time.Duration) ConfigOpt {\n\treturn func(c *Config) {\n\t\tc.transport.ResponseHeaderTimeout = d\n\t\tc.transport.TLSHandshakeTimeout = d\n\t\tc.dialer.Timeout = d\n\t}\n}", "func WithTimeout(t time.Duration) OptFunc {\n\treturn func(d *Downloader) {\n\t\td.timeout = t\n\t}\n}", "func WithTimeout(timeoutType fab.TimeoutType, timeout time.Duration) RequestOption {\n\treturn func(ctx context.Client, o *requestOptions) error {\n\t\tif o.Timeouts == nil {\n\t\t\to.Timeouts = make(map[fab.TimeoutType]time.Duration)\n\t\t}\n\t\to.Timeouts[timeoutType] = timeout\n\t\treturn nil\n\t}\n}", "func (c *Client) withConfiguredTimeout(ctx context.Context) (context.Context, context.CancelFunc) {\n\ttimeout := c.ClientTimeout()\n\n\tif timeout > 0 {\n\t\treturn context.WithTimeout(ctx, timeout)\n\t}\n\n\treturn ctx, func() {}\n}", "func (p *MockProvisionerClient) Timeout() time.Duration {\n\treturn 30 * time.Second\n}", "func WithTimeout(t time.Duration) apiOption {\n\treturn func(m *Management) {\n\t\tm.timeout = t\n\t}\n}", "func (r *Request) Timeout(d time.Duration) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\n\tr.timeout = d\n\n\treturn r\n}", "func WithTimeout(timeout time.Duration) Option {\n\treturn func(opts *Opts) error {\n\t\topts.Timeout = timeout\n\t\treturn nil\n\t}\n}", "func (o *NearestUsingGET1Params) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (r *Search) Timeout(timeout string) *Search {\n\n\tr.req.Timeout = &timeout\n\n\treturn r\n}", "func WithTimeout(d time.Duration) DialOption {\n\treturn func(o *DialOptions) {\n\t\to.Timeout = d\n\t}\n}", "func WithTimeout(d time.Duration) DialOption {\n\treturn func(o *DialOptions) {\n\t\to.Timeout = d\n\t}\n}", "func (o *HandleGetAboutUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (c *Client) SetTimeout(duration time.Duration) {\n\tc.httpclient.Timeout = duration\n}", "func (f Reindex) WithTimeout(v time.Duration) func(*ReindexRequest) {\n\treturn func(r *ReindexRequest) {\n\t\tr.Timeout = v\n\t}\n}", "func (r *Request) Timeout(d time.Duration) *Request {\n\tpanic(\"TODO\")\n\treturn r\n}", "func WithTimeout(timeout time.Duration) BuilderOptionFunc {\n\treturn func(b *Builder) error {\n\t\tb.timeout = timeout\n\t\treturn nil\n\t}\n}", "func (client *BaseClient) SetTimeout(value time.Duration) {\n\tclient.timeout = value\n}", "func WithTimeout(t time.Duration) APIOption {\n\treturn newAPIOption(func(o *Options) {\n\t\to.Timeout = t\n\t})\n}", "func WithTimeout(ctx context.Context) (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(ctx, RetryAttempts*RetryInterval)\n}", "func NewHTTPClientWithTimeout(t time.Duration) *http.Client {\n\ttr := &http.Transport{\n\t\t// Added IdleConnTimeout to reduce the time of idle connections which\n\t\t// could potentially slow macOS reconnection when there is a sudden\n\t\t// network disconnection/issue\n\t\tIdleConnTimeout: t,\n\t\tProxy: http.ProxyFromEnvironment,\n\t}\n\th := &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: t}\n\treturn h\n}", "func HTTPTimeout(duration time.Duration) HTTPOption {\n\treturn func(c *HTTPCollector) { c.client.Timeout = duration }\n}", "func (o *GetSellerServicesUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (c *Client) SetTimeout(timeout time.Duration) {\n\tc.Timeout = timeout\n}", "func (client *BaseClient) Timeout() time.Duration {\n\treturn client.timeout\n}", "func WithTimeout(duration time.Duration) Option {\n\treturn wrappedOption{oconf.WithTimeout(duration)}\n}", "func Timeout(d time.Duration) func(*Attacker) {\n\treturn func(a *Attacker) {\n\t\ta.client.Timeout = d\n\t}\n}", "func (c *Connection) SetTimeout(to time.Duration) {\n\tc.client.SetTimeout(to)\n}", "func WithTimeout(duration time.Duration) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.timeout = duration\n\t}\n}", "func ClientTimeout(duration time.Duration) ClientOpt {\n\treturn func(client *Client) {\n\t\tclient.timeout = duration\n\t}\n}", "func WithRequestTimeout(t time.Duration) ConfigOption {\n\treturn func(c *Config) {\n\t\tc.RequestTimeoutTime = t\n\t}\n}", "func WithTimeout(timeout time.Duration) ReqContextOptions {\n\treturn func(ctx *requestContextOpts) {\n\t\tctx.timeout = timeout\n\t}\n}", "func (x Go) Timeout(timeout time.Duration) Go {\n\tx.timeout = timeout\n\treturn x\n}", "func WithDialTimeout(timeout time.Duration) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.dialTimeout = timeout\n\t\treturn nil\n\t}\n}", "func (o *GetContentSourceUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func WithTimeout(duration time.Duration) Option {\n\treturn wrappedOption{otlpconfig.WithTimeout(duration)}\n}", "func WithHeaderTimeout(headerTimeout int) configurer {\n\treturn func(conf *config) {\n\t\tconf.headerTimeout = headerTimeout\n\t}\n}", "func (r *Request) Timeout() {\n\tr.SendError(mq.ErrRequestTimeout)\n}", "func (r *Responder) RequestTimeout() { r.write(http.StatusRequestTimeout) }", "func WithTimeout(t time.Duration) Option {\n\treturn func(o *Manager) {\n\t\to.timeout = t\n\t}\n}", "func (o *GetPageDataUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *ExportUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func ClientTimeout(w http.ResponseWriter, message ...interface{}) {\n\tboom(w, 408, message...)\n}", "func (c *Client) SetTimeout(timeout time.Duration) *Client {\n\tc.client.Timeout = timeout\n\treturn c\n}", "func (o *SyncStatusUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func WithConnectTimeout(connectTimeout int) configurer {\n\treturn func(conf *config) {\n\t\tconf.connectTimeout = connectTimeout\n\t}\n}", "func CloseWithTimeout(close func(ctx context.Context) error, timeout time.Duration) {\n\tClose(&timeoutCloser{close: close, timeout: timeout})\n}", "func NewClientWithTimeout(timeout time.Duration) (*clientv1.Client, error) {\n\tdeadline := time.Now().Add(timeout)\n\tsleep := time.Millisecond * 100\n\titerations := 0\n\tvar c *clientv1.Client\n\tvar err error\n\n\thasTimedout := func() bool {\n\t\treturn time.Now().After(deadline)\n\t}\n\n\tfor !hasTimedout() {\n\t\titerations++\n\n\t\tif iterations > 1 {\n\t\t\tlog.Errorf(\"action=sleeping duration=%v\", sleep)\n\t\t\ttime.Sleep(sleep)\n\t\t}\n\n\t\tcfg := Settings.Config\n\n\t\tc, err = clientv1.NewClient(cfg)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"action=create_client err=%v\", err)\n\t\t\tif hasTimedout() {\n\t\t\t\treturn nil, fmt.Errorf(\"Could not create client %s\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tduration, v, err := c.Ping()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"action=ping t=%v version=%s err=%v\", duration, v, err)\n\t\t\tif hasTimedout() {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to connect to %s: %v\", cfg.URL.String(), err.Error())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// If we made it this far everything is working\n\t\tbreak\n\t}\n\n\treturn c, err\n}", "func (c *ReplicaClient) SetTimeout(timeout time.Duration) {\n\tif c.httpClient != nil {\n\t\tc.httpClient.Timeout = timeout\n\t}\n}", "func NewWithCustomTimeout(apiKey, apiSecret string, timeout time.Duration) *Poloniex {\n\tclient := NewClientWithCustomTimeout(apiKey, apiSecret, timeout)\n\treturn &Poloniex{client}\n}", "func (o *ExportProductsUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetContentSourcesUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (o *GetAllPublicIPUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func UseHttpClientWithTimeout(timeout time.Duration) {\n\tdialTimeout := func(network, addr string) (net.Conn, error) {\n\t\treturn net.DialTimeout(network, addr, timeout)\n\t}\n\n\ttransport := http.Transport{\n\t\tDial: dialTimeout,\n\t}\n\tclient := http.Client{\n\t\tTransport: &transport,\n\t}\n\n\tdefaultHttpClient = &client\n}", "func (c *Ctx) WithTimeout(timeout time.Duration) (cf context.CancelFunc) {\n\tc.netContext, cf = context.WithTimeout(c.netContext, timeout)\n\treturn\n}", "func Timeout(t time.Duration) Option {\n\treturn func(c *Config) Option {\n\t\tprevious := c.Timeout\n\t\tc.Timeout = t\n\t\treturn Timeout(previous)\n\t}\n}", "func Timeout(timeout int64) Option {\n\treturn func(opts *options) {\n\t\topts.timeout = time.Duration(timeout) * time.Second\n\t}\n}", "func (o *GetItemByAppIDParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func (mc *Client) SetTimeout(timeout time.Duration) {\n\n\tmc.timeout = timeout\n\tmc.Session.SetClientTimeout(mc.timeout)\n}", "func (htpc *HttpProcessorConfig) Timeout(connectionTimeout time.Duration) *HttpProcessorConfig {\n\thtpc.connectionTimeout = connectionTimeout\n\treturn htpc\n}", "func WithTimeoutConnection() DialOption {\n\treturn func(cfg *dialConfig) {\n\t\tcfg.connectionType = connectionTypeWithTimeout\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func Timeout(t time.Duration) Option {\n\treturn func(o *Options) {\n\t\to.Timeout = t\n\t}\n}", "func WithTimeout(ctx context.Context, time time.Duration) (ret context.Context) {\n\tret = context.WithValue(ctx, liverpc.KeyTimeout, time)\n\treturn\n}", "func Timeout(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif config.V.BasicTimeout.Duration > 0 {\n\t\t\tc, cancel := context.WithTimeout(r.Context(), config.V.BasicTimeout.Duration)\n\t\t\tdefer cancel()\n\t\t\tr = r.WithContext(c)\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (o *IntegrationsManualHTTPSCreateParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}", "func NewClientTimeout(baseURL string, defaultHeaders map[string]string, timeout time.Duration) *Client {\n\turl, _ := url.Parse(baseURL)\n\tif defaultHeaders == nil {\n\t\tdefaultHeaders = make(map[string]string)\n\t}\n\treturn &Client{httpClient: &http.Client{\n\t\tTimeout: timeout,\n\t}, baseURL: url, defaultHeaders: defaultHeaders}\n}", "func (c *Client) SetTimeout(timeout time.Duration) error {\n\tif timeout.Seconds() < 0 {\n\t\treturn fmt.Errorf(\"Invalid timeout: %v\", timeout)\n\t}\n\tc.timeout = timeout\n\treturn nil\n}", "func SetHTTPClientWithTimeout(t time.Duration) error {\n\tif t <= 0 {\n\t\treturn errCannotSetInvalidTimeout\n\t}\n\tm.Lock()\n\t_HTTPClient = NewHTTPClientWithTimeout(t)\n\tm.Unlock()\n\treturn nil\n}", "func (cl *Client) SetTimeout(secs int) {\n\tif secs <= 0 {\n\t\tsecs = clientDefaultTimeoutSecs\n\t}\n\tcl.Timeout = time.Duration(secs) * time.Second\n}", "func (o *GetProductUpgradeURLUsingGETParams) SetTimeout(timeout time.Duration) {\n\to.timeout = timeout\n}" ]
[ "0.7700649", "0.73777956", "0.73777956", "0.735907", "0.7320129", "0.7181315", "0.7126675", "0.7080921", "0.7080921", "0.7078603", "0.70687425", "0.69709677", "0.68245816", "0.6792751", "0.6700478", "0.6685603", "0.66592014", "0.6598578", "0.6587147", "0.65838987", "0.65464914", "0.65182865", "0.65182865", "0.64954346", "0.6443429", "0.6400277", "0.6376391", "0.6373315", "0.63718945", "0.6349498", "0.6335515", "0.6298136", "0.6286627", "0.628059", "0.62781566", "0.62636894", "0.62372273", "0.62332696", "0.62332696", "0.62309885", "0.6207525", "0.62005764", "0.616914", "0.61661816", "0.61644274", "0.6125879", "0.6120715", "0.6108282", "0.6102937", "0.6078565", "0.6063815", "0.6054427", "0.6053708", "0.6049578", "0.6044974", "0.6033638", "0.6030926", "0.60155845", "0.601466", "0.59856105", "0.59738797", "0.59599316", "0.59591836", "0.5957494", "0.59512216", "0.59440076", "0.59325457", "0.5918538", "0.59136987", "0.5913121", "0.59028274", "0.5893401", "0.5865014", "0.585513", "0.5844194", "0.5828016", "0.5825979", "0.58049226", "0.5792778", "0.5777846", "0.576684", "0.5764444", "0.5761848", "0.575871", "0.57576454", "0.57520634", "0.5745881", "0.5731053", "0.57302254", "0.57302254", "0.57302254", "0.57302254", "0.5718124", "0.5714462", "0.57069147", "0.5697763", "0.5693864", "0.5684888", "0.5684357", "0.5680419" ]
0.70642173
11
NewClient creates a new [Client] with the options applied.
func NewClient(options ...ClientOption) *Client { client := &Client{ endpoint: Endpoint, httpClient: &http.Client{}, timeout: 5 * time.Second, } for _, option := range options { option(client) } client.httpClient.Timeout = client.timeout if client.instrumentationRegistry != nil { i := instrumentation.New("metadata", client.instrumentationRegistry) client.httpClient.Transport = i.InstrumentedRoundTripper() } return client }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClient(\n\thost string,\n\tapplicationName string,\n\toptions ...Option,\n) (*Client, error) {\n\tc := &Client{\n\t\thost: host,\n\t\tapplicationName: applicationName,\n\t}\n\n\tfor _, o := range options {\n\t\terr := o(c)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"client.NewClient failed to apply option: %s\", err)\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func NewClient(options Options) *Client {\n\treturn &Client{Options: options}\n}", "func New(opts ...Option) Client {\n\treturn newClient(opts...)\n}", "func New(opts ...ClientOption) *Client {\n\tcl := newDefaultClient()\n\tcl.opts = opts\n\treturn cl\n}", "func NewClient(o *Option) Client {\n\treturn &client{\n\t\to: o,\n\t}\n}", "func NewClient(options ...ClientOptionFunc) (*Client, error) {\n\tc := &Client{\n\t\t// client: client(false),\n\t\tremote: DefaultRemote,\n\t\turl: DefaultURL,\n\t\tverbose: DefaultVerbose,\n\t}\n\tfor _, option := range options {\n\t\tif err := option(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}", "func NewClient(options Options) (*Client, error) {\n\tc := &Client{\n\t\tserver: options.Server,\n\t\tappCode: options.AppCode,\n\t\tappSecret: options.AppSecret,\n\t\tbkUserName: options.BKUserName,\n\t\tserverDebug: options.Debug,\n\t}\n\n\treturn c, nil\n}", "func NewClient(apiKey string, serverID string, options ...clientOption) *Client {\n\tc := &Client{\n\t\tapiKey: apiKey,\n\t\tserverID: serverID,\n\t\tserviceURL: ServiceURL,\n\t}\n\tfor _, opt := range options {\n\t\topt(c)\n\t}\n\treturn c\n}", "func NewClient(config *Config) *Client {\n\tc := &Client{config: defaultConfig.Merge(config)}\n\n\treturn c\n}", "func newClient(configuration *Configuration, options ...ClientOption) (Client, error) {\n\tclientCfg, err := newTLSClientConfig(configuration)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading and/or parsing the certification files. Cause: %w\", err)\n\t}\n\n\tnetClient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: clientCfg,\n\t\t},\n\t}\n\n\tinstance := &client{client: &netClient, configuration: configuration, encoder: newJSONEncoder(), decoder: newJSONDecoder()}\n\n\t// Apply options if there are any, can overwrite default\n\tfor _, option := range options {\n\t\toption(instance)\n\t}\n\n\treturn instance, nil\n}", "func NewClient(options ...Option) (*Client, error) {\n\tclient := &Client{\n\t\tbaseURL: DefaultBaseURL,\n\t\tclient: http.DefaultClient,\n\t\tworkers: DefaultWorkers,\n\t}\n\n\tfor _, option := range options {\n\t\tif err := option(client); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create client: %v\", err)\n\t\t}\n\t}\n\n\treturn client, nil\n}", "func NewClient(options *ClientOptions) *Client {\n\tclient := &Client{\n\t\tappID: options.AppID,\n\t\tappKey: options.AppKey,\n\t\tmasterKey: options.MasterKey,\n\t\tserverURL: options.ServerURL,\n\t}\n\n\tif !strings.HasSuffix(options.AppID, \"MdYXbMMI\") {\n\t\tif client.serverURL == \"\" {\n\t\t\tpanic(fmt.Errorf(\"please set API's serverURL\"))\n\t\t}\n\t}\n\n\t_, debugEnabled := os.LookupEnv(\"LEANCLOUD_DEBUG\")\n\n\tif debugEnabled {\n\t\tclient.requestLogger = log.New(os.Stdout, \"\", log.LstdFlags)\n\t}\n\n\tclient.Users.c = client\n\tclient.Files.c = client\n\tclient.Roles.c = client\n\treturn client\n}", "func NewClient(cfg *Config) *Client {\n\treturn &Client{\n\t\tcfg: cfg,\n\t}\n}", "func NewClient(ctx *pulumi.Context,\n\tname string, args *ClientArgs, opts ...pulumi.ResourceOption) (*Client, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Brand == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Brand'\")\n\t}\n\tif args.DisplayName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DisplayName'\")\n\t}\n\tsecrets := pulumi.AdditionalSecretOutputs([]string{\n\t\t\"secret\",\n\t})\n\topts = append(opts, secrets)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Client\n\terr := ctx.RegisterResource(\"gcp:iap/client:Client\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewClient(list, create, show, update, delete_ goa.Endpoint) *Client {\n\treturn &Client{\n\t\tListEndpoint: list,\n\t\tCreateEndpoint: create,\n\t\tShowEndpoint: show,\n\t\tUpdateEndpoint: update,\n\t\tDeleteEndpoint: delete_,\n\t}\n}", "func NewClient(ctx context.Context, options ...func(Party) error) (Client, error) {\n\tinfo, dbg := buildInfoDebugLogger(log.NewLogfmtLogger(os.Stderr), true)\n\tc := &client{\n\t\tstate: ClientCreated,\n\t\tstateChangeChans: make([]chan<- struct{}, 0),\n\t\tformat: \"json\",\n\t\tpartyBase: newPartyBase(ctx, info, dbg),\n\t\tlastID: -1,\n\t}\n\tfor _, option := range options {\n\t\tif option != nil {\n\t\t\tif err := option(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tif c.conn == nil && c.connectionFactory == nil {\n\t\treturn nil, errors.New(\"neither WithConnection nor WithAutoReconnect option was given\")\n\t}\n\treturn c, nil\n}", "func New(opts ...Option) *Client {\n\tc := defaultCfg()\n\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\n\treturn &Client{\n\t\tcfg: c,\n\t}\n}", "func NewClient(transportFactory TransportFactory, options ...ClientOption) *Client {\n\tclient := &Client{\n\t\tTransportFactory: transportFactory,\n\t\tRetrier: retry.NewRetrier(),\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\treturn client\n}", "func New(o *Opt) *Client {\n\treturn &Client{\n\t\to: o,\n\t}\n}", "func NewClient() Client {\n\treturn Client{}\n}", "func NewClient() Client {\n\treturn Client{}\n}", "func NewClient() Client {\n\treturn Client{}\n}", "func NewClient(options Options) (client Client) {\n\tmergo.Merge(&options, defaultClientOptions)\n\n\tclient = Client{newDefaultClient(options)}\n\n\tif options.Proxy != \"\" {\n\t\tclient.setProxy(options.Proxy, options.ProxyConnectHeaders)\n\t}\n\n\tif options.MaxRedirects > 0 {\n\t\tclient.setLimitRedirect(options.MaxRedirects)\n\t}\n\n\treturn client\n}", "func New(opts ...ClientOpt) (*Client, error) {\n\tc := NewClient()\n\tfor _, opt := range opts {\n\t\tif err := opt(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func NewClient(config *Config) *Client {\n\treturn &Client{\n\t\tconfig: config,\n\t}\n}", "func New(opt ...Option) Client {\n\n\topts := &Options{}\n\tfor _, o := range opt {\n\t\to(opts)\n\t}\n\n\treturn &defaultClient {\n\t\topts: opts,\n\t\tTransport: transport.DefaultClientTransport,\n\t}\n}", "func NewClient(cfg *api.Config, address, name string, port int) (Client, error) {\n\n\tc, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(\">>> Started a new Consul client.\")\n\treturn &client{\n\t\tclient: c,\n\t\tname: name,\n\t\taddress: address,\n\t\tport: port,\n\t}, nil\n}", "func NewClient(list, show, add, remove, rate, multiAdd, multiUpdate goa.Endpoint) *Client {\n\treturn &Client{\n\t\tListEndpoint: list,\n\t\tShowEndpoint: show,\n\t\tAddEndpoint: add,\n\t\tRemoveEndpoint: remove,\n\t\tRateEndpoint: rate,\n\t\tMultiAddEndpoint: multiAdd,\n\t\tMultiUpdateEndpoint: multiUpdate,\n\t}\n}", "func New(client *client.Client) *Client {\n\treturn &Client{\n\t\tclient: client,\n\t}\n}", "func New(client *client.Client) *Client {\n\treturn &Client{\n\t\tclient: client,\n\t}\n}", "func New(client *client.Client) *Client {\n\treturn &Client{\n\t\tclient: client,\n\t}\n}", "func New(conf *Configuration) *Client {\n\tcli = &Client{\n\t\tConf: conf,\n\t\tsigs: make(chan os.Signal, 1),\n\t}\n\n\treturn cli\n}", "func NewClient(o *Options) (*Client, error) {\n\tconn, err := o.getDialer()()\n\treturn &Client{\n\t\tconn: conn,\n\t}, err\n}", "func NewClient(config Config) Client {\n\treturn DefaultClient{\n\t\tconfig: config,\n\t}\n}", "func NewClient(options ...ConfigOption) *Client {\n\tc := Client{\n\t\tconfig: Config{\n\t\t\thttpClient: http.DefaultClient,\n\t\t\tbaseURL: defaultBaseURL,\n\t\t\tcoin: defaultCoin,\n\t\t\tlogger: &NoopLogger{},\n\t\t},\n\t}\n\n\tc.Wallet = &walletService{client: &c}\n\n\tfor _, opt := range options {\n\t\topt(&c.config)\n\t}\n\treturn &c\n}", "func NewClient(confs ...ClientConfiguration) *Client {\n\tq := setupClient()\n\n\t// Loop through the configurations and apply them to the client.\n\tfor _, c := range confs {\n\t\tc(q)\n\t}\n\n\treturn q\n}", "func New(cfg *Config) *Client {\n\treturn &Client{\n\t\tcfg: cfg,\n\t}\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient(opts ...Option) *Client {\n\tcfg := config{log: log.Println, hooks: &hooks{}}\n\tcfg.options(opts...)\n\tclient := &Client{config: cfg}\n\tclient.init()\n\treturn client\n}", "func NewClient() *Client {\n\tclient := &Client{\n\t\tapi: C.Create(),\n\t\tVariables: map[SettableVariable]string{},\n\t\tTrim: true,\n\t\tshouldInit: true,\n\t\tLanguages: []string{\"eng\"},\n\t}\n\treturn client\n}", "func New() *Client {\n\treturn &Client{}\n}", "func New() *Client {\n\treturn &Client{}\n}", "func New(options ...Option) (*Client, error) {\n\tc := &Client{\n\t\thttpHost: \"http://localhost:8080\",\n\t\twsHost: \"ws://localhost:8080\",\n\t}\n\n\t// apply options\n\tfor _, option := range options {\n\t\tif err := option(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func NewClient(opt ...requests.Option) Client {\n\treturn opt\n}", "func NewClient() *Client{\n\treturn &Client{}\n}", "func NewClient(opts *ClientOptions) *Client {\n\treturn &Client{options: opts}\n}", "func NewClient(key string, options ...clientOption) (*client, error) {\n\tvar url string\n\tif url = os.Getenv(\"TAPPAY_SERVER\"); url == \"\" {\n\t\turl = APIURL\n\t}\n\n\t// defaultTimeout is the default timeout on the http.Client used the by the library\n\t// This is chosen according to the document\n\t// https://docs.tappaysdk.com/tutorial/zh/back.html\n\tconst defaultTimeout = 30 * time.Second\n\thttpClient := &http.Client{\n\t\tTimeout: defaultTimeout,\n\t}\n\n\tcli := &client{\n\t\tpartnerKey: key,\n\t\thttpClient: httpClient,\n\t\turl: url,\n\t}\n\n\tfor _, option := range options {\n\t\toption(cli)\n\t}\n\tu, err := sanitizeURL(cli.url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied server %q is not valid: %v\", cli.url, err)\n\t}\n\tcli.url = u.String()\n\treturn cli, nil\n}", "func New() (*Client, error) {\n\treturn NewForConfig(nil)\n}", "func NewClient(opts *Options) Client {\n\treturn &client{\n\t\topts: opts,\n\t}\n}", "func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (*Client, error) {\n\tclient, err := NewClientWithDatabase(ctx, projectID, DefaultDatabaseID, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func New() Client {\n\treturn &client{}\n}", "func NewClient(add, get, transfer, defaultPhoto, update, listMine, listProject, listAssociated, listProjectAssociated, downloadPhoto, listAll, delete_, adminSearch, progress, updateModule goa.Endpoint) *Client {\n\treturn &Client{\n\t\tAddEndpoint: add,\n\t\tGetEndpoint: get,\n\t\tTransferEndpoint: transfer,\n\t\tDefaultPhotoEndpoint: defaultPhoto,\n\t\tUpdateEndpoint: update,\n\t\tListMineEndpoint: listMine,\n\t\tListProjectEndpoint: listProject,\n\t\tListAssociatedEndpoint: listAssociated,\n\t\tListProjectAssociatedEndpoint: listProjectAssociated,\n\t\tDownloadPhotoEndpoint: downloadPhoto,\n\t\tListAllEndpoint: listAll,\n\t\tDeleteEndpoint: delete_,\n\t\tAdminSearchEndpoint: adminSearch,\n\t\tProgressEndpoint: progress,\n\t\tUpdateModuleEndpoint: updateModule,\n\t}\n}", "func New(cfg client.Config) (client.Client, error) {\n\treturn client.New(cfg)\n}", "func NewClient(config Config) *Client {\n\treturn &Client{Config: config}\n}", "func New() *Client {\n\treturn &Client{\n\t\tDebug: false,\n\t\tparser: &parser{},\n\t}\n}", "func NewClient(opts ...ClientOps) ClientInterface {\n\n\t// Create a client with defaults\n\tc := &Client{\n\t\toptions: &ClientOptions{\n\t\t\thttpOptions: DefaultHTTPOptions(),\n\t\t\tsearchOptions: DefaultSearchOptions(),\n\t\t\tuserAgent: defaultUserAgent,\n\t\t},\n\t}\n\n\t// Overwrite defaults with any set by user\n\tfor _, opt := range opts {\n\t\topt(c.options)\n\t}\n\n\t// Set a default http client if one does not exist\n\tif c.options.httpClient == nil {\n\t\tc.options.httpClient = createDefaultHTTPClient(c)\n\t}\n\n\treturn c\n}", "func (o *ClientConfig) NewClient(options ...ClientOption) (Client, error) {\n\n\t// Run provided ClientOption configuration options.\n\tfor _, opt := range options {\n\t\terr := opt(o)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed applying functional option: %w\", err)\n\t\t}\n\t}\n\n\t// Check mandatory option is provided.\n\tif o.githubUserClient == nil {\n\t\treturn nil, fmt.Errorf(\"github client not provided\")\n\t}\n\n\ttokenGenerator := secret.GetTokenGenerator(o.tokenPath)\n\n\tgitFactory, err := o.GitClient(o.githubUserClient, tokenGenerator, secret.Censor, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgitClient := &client{}\n\t// Initialize map to enable writing to it in methods.\n\tgitClient.clonedRepos = make(map[string]string)\n\tgitClient.ClientFactory = gitFactory\n\treturn gitClient, err\n}", "func NewClient(options ...ClientOptionFunc) (c *Client, err error) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tc = &Client{\n\t\tc: &http.Client{Transport: tr},\n\t}\n\n\tfor _, option := range options {\n\t\tif err := option(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn c, err\n}", "func NewClient(opts ...Option) *Client {\n\tc := config{log: log.Println}\n\tc.options(opts...)\n\treturn &Client{\n\t\tconfig: c,\n\t\tSchema: migrate.NewSchema(c.driver),\n\t\tModule: NewModuleClient(c),\n\t\tModuleVersion: NewModuleVersionClient(c),\n\t}\n}", "func NewClient(id int64) Client {\n\treturn Client{\n\t\tID: id,\n\t}\n}", "func NewClient(with ...ClientOption) *Client {\n\ttimeout := DefaultTimeout\n\n\tclient := &Client{\n\t\tclient: &http.Client{\n\t\t\tTimeout: timeout,\n\t\t},\n\t\tbase: getBaseURL(url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"api.secrethub.io\",\n\t\t}),\n\t\tuserAgent: DefaultUserAgent,\n\t}\n\tclient.Options(with...)\n\treturn client\n}", "func New() (*Client, error) {\n\tcs, err := newClients()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tcs: cs,\n\t}, nil\n}", "func NewClient(cl *kgo.Client) *Client {\n\treturn &Client{cl}\n}", "func NewClient(c *ConnectionOption) (*Client, error) {\n\tvar t transport\n\tswitch c.Interface {\n\tcase \"lan\":\n\t\tif c.IntegrityAlgorithm != RAKPAlgorithmIntegrity_None {\n\t\t\treturn nil, fmt.Errorf(\"unsupported integrity algorithm for lan: %s\", c.IntegrityAlgorithm.String())\n\t\t}\n\n\t\tif c.ConfidentialityAlgorithm != RAKPAlgorithmEncryto_None {\n\t\t\treturn nil, fmt.Errorf(\"unsupported confidentiality algorithm for lan: %s\", c.ConfidentialityAlgorithm.String())\n\t\t}\n\n\t\tt = newLan(c)\n\tcase \"lanplus\":\n\t\tif c.ConfidentialityAlgorithm != RAKPAlgorithmEncryto_None &&\n\t\t\tc.ConfidentialityAlgorithm != RAKPAlgorithmEncryto_AES_CBC_128 {\n\t\t\treturn nil, fmt.Errorf(\"unsupported confidentiality algorithm: %s\", c.ConfidentialityAlgorithm.String())\n\t\t}\n\t\tt = newLanPlus(c)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported interface: %s\", c.Interface)\n\t}\n\n\treturn &Client{\n\t\tConnectionOption: c,\n\t\ttransport: t,\n\t}, nil\n}", "func NewClient(cfg *Config, args ...interface{}) (endpoint.Connector, error) {\n\treturn cfg.newClient(args)\n}", "func NewClient() *Client {\n\treturn &Client{\n\t\tService: &service.Default{},\n\t}\n}", "func NewClient(cfg Config) (*Client, error) {\n\tvar (\n\t\tc Client\n\t\tv *validator.Validate\n\t\terr error\n\t)\n\n\tv = validator.New()\n\n\terr = v.Struct(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.cfg = cfg\n\tc.clntCredCfg = clientcredentials.Config{\n\t\tClientID: cfg.ClientID,\n\t\tClientSecret: cfg.ClientSecret,\n\t}\n\n\tc.oauth = OAuth{\n\t\tClientID: cfg.ClientID,\n\t\tClientSecret: cfg.ClientSecret,\n\t}\n\n\terr = c.SetRegionParameters(cfg.Region, cfg.Locale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &c, nil\n}", "func NewClient(typ Type) *Client {\n\treturn &Client{\n\t\ttyp: typ,\n\t}\n}", "func New(client *client.Client, properties ClientProperties) *Client {\n\treturn &Client{\n\t\tclient: client,\n\n\t\taccountSid: properties.AccountSid,\n\t\tcountryCode: properties.CountryCode,\n\t}\n}", "func NewClient(conf *ClientConfig, opt ...grpc.DialOption) *Client {\n\tc := new(Client)\n\tif err := c.SetConfig(conf); err != nil {\n\t\tpanic(err)\n\t}\n\tc.UseOpt(opt...)\n\tc.Use(c.recovery(), c.handle())\n\treturn c\n}", "func New(cfg *ClientConfig) *Client {\n\treturn &Client{\n\t\tservice: cfg.Service,\n\t\tuser: cfg.User,\n\t}\n}", "func NewClient(cfg *Config) *Client {\n\tcfg.init()\n\n\tc := Client{\n\t\tclient: &client{\n\t\t\tbaseClient: baseClient{\n\t\t\t\tcfg: cfg,\n\t\t\t\tconnPool: newConnPool(cfg),\n\t\t\t},\n\t\t},\n\t\tctx: context.Background(),\n\t}\n\tc.init()\n\n\treturn &c\n}", "func (c *Config) NewClient(database string) *Client {\n\treturn &Client{\n\t\tconfig: *c,\n\t\tdatabaseName: database,\n\t}\n}", "func NewClient(c context.Context, opts ...ClientOption) (*Client, error) {\n\tcl := &Client{\n\t\tkeepAlive: 60 * time.Second,\n\t\thandshakeTimeout: 10 * time.Second,\n\t}\n\n\tvar err error\n\n\t// execute all options\n\tfor _, opt := range opts {\n\t\tif err = opt(c, cl); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcl.setClient()\n\n\treturn cl, nil\n}", "func NewClient(d *schema.ResourceData, terraformVersion string, options client.Options) (client.Client, error) {\n\t// Config initialization\n\tcfg, err := GetConfig(d, terraformVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.New(cfg, options)\n}", "func newClient() (client *Client) {\n\n\tclient = new(Client)\n\n\tid := <-uuidBuilder\n\tclient.Id = id.String()\n\tclient.subscriptions = make(map[string]bool)\n\n\tclients[client.Id] = client\n\n\tlog.WithField(\"clientID\", id.String()).Info(\"Created new Client\")\n\treturn\n}", "func New() *Client {\n\treturn &Client{\n\t\tClientInfo: ClientInfo{\n\t\t\t// api defaults\n\t\t\tdatatype: &defaultDatatype,\n\t\t\toutputsize: &defaultOutputsize,\n\t\t},\n\t}\n}", "func New(info metadata.ClientInfo, options ...ClientOpt) *Client {\n\tc := &Client{\n\t\tInfo: info,\n\t\tHandlers: request.DefaultHandlers(),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: 60 * time.Second,\n\t\t\tTransport: &http.Transport{\n\t\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\t\tDialContext: (&net.Dialer{\n\t\t\t\t\tTimeout: 1 * time.Second,\n\t\t\t\t\tKeepAlive: 90 * time.Second,\n\t\t\t\t}).DialContext,\n\t\t\t\tTLSHandshakeTimeout: 3 * time.Second,\n\t\t\t\tMaxIdleConns: 100,\n\t\t\t\tMaxIdleConnsPerHost: 8,\n\t\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Apply options\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\treturn c\n}", "func NewClient(config *Config) (*Client, error) {\n\tdefConfig := DefaultConfig()\n\n\tif len(config.Address) == 0 {\n\t\tconfig.Address = defConfig.Address\n\t}\n\n\tif len(config.Scheme) == 0 {\n\t\tconfig.Scheme = defConfig.Scheme\n\t}\n\n\tif config.HTTPClient == nil {\n\t\tconfig.HTTPClient = defConfig.HTTPClient\n\t}\n\n\tclient := &Client{\n\t\tConfig: *config,\n\t}\n\treturn client, nil\n}", "func NewClient() *Client {\n\tc := new(Client)\n\tc.SetSoftwareName(DefaultSoftwareName)\n\tc.logger = NewLogger()\n\treturn c\n}" ]
[ "0.78923184", "0.7740766", "0.76316303", "0.75836253", "0.75573534", "0.7527537", "0.7513437", "0.74467295", "0.7428837", "0.73944014", "0.739247", "0.73919266", "0.7381", "0.73679173", "0.7352626", "0.73470515", "0.7340001", "0.73302734", "0.7327137", "0.732241", "0.732241", "0.732241", "0.7317447", "0.73106754", "0.73105925", "0.7297348", "0.72782165", "0.7272006", "0.7270417", "0.7270417", "0.7270417", "0.72554386", "0.7251422", "0.7243956", "0.7238955", "0.723555", "0.7228333", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.722745", "0.721614", "0.7209185", "0.7209185", "0.7198531", "0.71889246", "0.71888167", "0.7188404", "0.7184541", "0.71698445", "0.7167378", "0.71556616", "0.7155188", "0.715316", "0.7152306", "0.71503806", "0.7144195", "0.7142405", "0.71353245", "0.711756", "0.7112029", "0.71040446", "0.70946693", "0.70917696", "0.7087698", "0.70849466", "0.7078518", "0.70781964", "0.70778537", "0.7074354", "0.7072851", "0.70701545", "0.70675004", "0.705741", "0.705088", "0.7050508", "0.7050077", "0.7045623", "0.70370054", "0.70353276", "0.7022746", "0.70173943" ]
0.7058738
91
get executes an HTTP request against the API.
func (c *Client) get(path string) (string, error) { url := c.endpoint + path resp, err := c.httpClient.Get(url) if err != nil { return "", err } defer resp.Body.Close() bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return "", err } body := string(bodyBytes) if resp.StatusCode < 200 || resp.StatusCode >= 300 { return body, fmt.Errorf("response status was %d", resp.StatusCode) } return body, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Get (url string, args map[string]string) (*http.Response, error) {\n\t// create a client\n\tclient, req, _ := GetHttpClient(url)\n\t// build the query\n\tif len(args) > 0 {\n\t\treq = buildQuery(req, args)\n\t}\n\t// execute the request\n\t//fmt.Println(req.URL.String())\n\treturn client.Do(req)\n}", "func (client *Client) Get(action string, params url.Values, header http.Header) (*Response, error) {\r\n\treturn client.Request(\"GET\", action, params, header, nil)\r\n}", "func (c *Client) Get(url string, headers map[string]string, params map[string]interface{}) (*APIResponse, error) {\n\tfinalURL := c.baseURL + url\n\tr, err := http.NewRequest(\"GET\", finalURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %v\", err)\n\t}\n\n\treturn c.performRequest(r, headers, params)\n}", "func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {\n\treturn c.makeRequest(url, http.MethodGet, headers, queryParams, nil)\n}", "func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) {\n\treturn c.DoRequest(ctx, http.MethodGet, url, data...)\n}", "func Get(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"GET\", url, data...)\n}", "func get(url string, qparms rest.QParms) ([]byte, error) {\n\theaders := rest.Headers{\"Authorization\": \"Bearer \" + token}\n\tfor k, v := range defaultHeaders {\n\t\theaders[k] = v\n\t}\n\tclient := rest.NewClient(headers, qparms)\n\n\tbody, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}", "func (c *Client) get(url string, query url.Values) (json.RawMessage, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create get request\")\n\t}\n\treq.URL.RawQuery = query.Encode()\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cound not get %v\", url)\n\t}\n\tdefer res.Body.Close()\n\tvar resp response\n\tif err := json.NewDecoder(res.Body).Decode(&resp); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not decode response\")\n\t}\n\tif resp.Code != 0 {\n\t\treturn nil, errors.Errorf(\"get response code %d\", resp.Code)\n\t}\n\treturn resp.Data, nil\n}", "func (f5 *f5LTM) get(url string, result interface{}) error {\n\treturn f5.restRequest(\"GET\", url, nil, result)\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn do(\"GET\", url, nil)\n}", "func (g *Getter) Get(url string) (*http.Response, error) {\n\treturn g.Client.Get(url)\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}", "func (rb *RequestBuilder) Get(url string) *Response {\n\treturn rb.DoRequest(http.MethodGet, url, nil)\n}", "func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}", "func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {\n return c.doRequest(\"GET\", route, queryValues, nil)\n}", "func (c *Client) get(rawURL string, authenticate bool, out interface{}) error {\n\terr := c.do(rawURL, \"GET\", authenticate, http.StatusOK, nil, out)\n\treturn errio.Error(err)\n}", "func (client *Client) Get(c context.Context, uri string, params interface{}, res interface{}) (err error) {\n\treq, err := client.NewRequest(xhttp.MethodGet, uri, params)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn client.client.Do(c, req, res)\n}", "func (c Client) get(path string, params url.Values, holder interface{}) error {\n\treturn c.request(\"GET\", path, params, &holder)\n}", "func (session *Session) Get(path string, params Params) (response []byte, err error) {\n\turlStr := session.getUrl(path, params)\n\tlog.Println(urlStr)\n\tresponse, err = session.sendGetRequest(urlStr)\n\treturn\n\n\t//res, err = MakeResult(response)\n\t//return\n\n}", "func Get(url string) (resp *http.Response, err error) {\n\treturn DefaultClient.Get(url)\n}", "func Get(url string) (*http.Response, error) {\n\treturn DefaultClient.Get(url)\n}", "func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}", "func (h *Client) Get(url string, values url.Values) (body []byte, statusCode int, err error) {\n\tif values != nil {\n\t\turl += \"?\" + values.Encode()\n\t}\n\tvar req *http.Request\n\treq, err = http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn h.do(req)\n}", "func (t *ApiTester) Get(route string) (*ApiTesterResponse, error) {\n\t// prepare the request here\n\trequest, err := http.NewRequest(\"GET\", \"http://\"+t.Server.Listener.Addr().String()+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do the actual request here\n\tresponse, err := t.Client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBuffer, _ := ioutil.ReadAll(response.Body)\n\n\treturn &ApiTesterResponse{\n\t\tRawResponse: response,\n\t\tStatusCode: response.StatusCode,\n\t\tBodyStr: string(bodyBuffer),\n\t}, nil\n}", "func (c *Client) get(endpoint string, queries map[string]string) (*http.Response, error) {\n\t// Assemble request\n\treq, err := c.buildRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add query strings\n\tif queries != nil {\n\t\tencodeQuery(req.URL, queries)\n\t}\n\n\tclient := buildHTTPSClient(c.verifySSL)\n\treturn client.Do(req)\n}", "func (c *Client) get(url string, result interface{}) error {\n\treq, err := c.newRequest(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err = checkResponse(resp); err != nil {\n\t\treturn err\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = checkResults(b); err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, &result)\n\n\treturn err\n}", "func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}", "func (c *Client) Get(headers map[string]string, queryParams map[string]string) ([]byte, error) {\n\n\t// add parameters to the url\n\tv := url.Values{}\n\tfor key, value := range queryParams {\n\t\tv.Add(key, value)\n\t}\n\turi, err := url.Parse(c.baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi.RawQuery = v.Encode()\n\tc.baseURL = uri.String()\n\n\t// create a new get request\n\trequest, err := http.NewRequest(\"GET\", c.baseURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add headers to the request\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := c.sendRequestWithRetry(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if response is an error (not a 200)\n\tif response.StatusCode > 299 {\n\t\treturn nil, errors.New(response.Status)\n\t}\n\t// read the body as an array of bytes\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\treturn responseBody, err\n}", "func get(url string) (*http.Response, error) {\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tresp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"get failed: %s\\n\", resp.Status)\n\t}\n\n\treturn resp, nil\n}", "func (conn Connection) Get(cmd string, result interface{}) (resp *http.Response, err error) {\n\treturn conn.Send(http.MethodGet, cmd, nil, result)\n}", "func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) {\n\treturn c.Do(\"GET\", url, headers, nil)\n}", "func Get(config *HTTPConfig) (*HTTPResult, error) {\n\treturn HandleRequest(\"GET\", config)\n}", "func (c *Client) Get(endpoint string, params map[string]string) *grequests.Response {\n\turl := c.Endpoint + endpoint\n\tresp, err := grequests.Get(url, &grequests.RequestOptions{\n\t\tParams: params,\n\t})\n\tif err != nil {\n\t\tutilities.CheckError(resp.Error, \"Unable to make requests\")\n\t}\n\n\tif resp.Ok != true {\n\t\tlog.Println(\"Request did not return OK\")\n\t}\n\n\treturn resp\n}", "func Get(opts ...Option) ([]byte, error) {\n\treturn request(\"GET\", opts...)\n}", "func (cl *Client) Get(c context.Context, url string, opts ...RequestOption) (*Response, error) {\n\treq, err := cl.NewRequest(c, http.MethodGet, url, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cl.Do(c, req)\n}", "func (api *API) Get(method string, params map[string]string, result interface{}) {\n\trequest := api.Request(method, result)\n\tif params != nil {\n\t\trequest.SetQueryParams(params)\n\t}\n\n\t_, err := request.Get(api.url + \"/\" + method)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func Get(url string, data ...interface{}) (*Response, error) {\n\tr := NewRequest()\n\treturn r.Get(url, data...)\n}", "func (c *Client) Get(url string) (*Response, error) {\n\treq, err := c.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq = c.Config.AddRequestHeader(req)\n\tresponse, err := c.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func Get(url string, key string) (Response, error) {\n\n\tres, err := http.Get(url + \"/jsonResult.php?test=\" + key)\n\n\tif err != nil {\n\t\treturn Response{}, err\n\t}\n\n\tdefer res.Body.Close()\n\treturn process(ioutil.ReadAll(res.Body))\n}", "func (client *HTTPClient) Get(url string, opts *RequestOptions) (resp *http.Response, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tresp, err = client.Do(req, opts)\n\treturn\n}", "func (a *API) Get(path string) (resp *http.Response, err error) {\n\tu, err := url.ParseRequestURI(a.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu.Path = path\n\n\treturn a.Client.Get(u.String())\n}", "func (cli *Client) Get(targetURL *url.URL) {\n\tvar resp *resty.Response\n\tvar err error\n\n\tif cli.Config.Oauth2Enabled {\n\t\tresp, err = resty.R().\n\t\t\tSetHeader(\"Authorization\", fmt.Sprintf(\"Bearer %s\", cli.AccessToken)).\n\t\t\tGet(targetURL.String())\n\t} else {\n\t\tresp, err = resty.R().Get(targetURL.String())\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"ERR: Could not GET request, caused by: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Print(resp)\n}", "func (s *DefaultClient) Get(endpoint string) ([]byte, *http.Response, error) {\n\treturn s.http(http.MethodGet, endpoint, nil)\n}", "func get(resource string) ([]byte, error) {\n\thttpParams := &HTTPParams{\n\t\tResource: resource,\n\t\tVerb: \"GET\",\n\t}\n\treturn processRequest(httpParams)\n}", "func sendGet(method string, uri string, args ...interface{}) (responseBody []byte, statusCode int, err error) {\n\tclient := &http.Client{}\n\n\treq, _ := http.NewRequest(method, uri, nil)\n\n\tfor _, arg := range args {\n\t\tswitch val := arg.(type) {\n\t\tcase url.Values:\n\t\t\t// Assign http query to the request URL\n\t\t\treq.URL.RawQuery = val.Encode()\n\n\t\tcase http.Header:\n\t\t\t// Assign request header\n\t\t\treq.Header = val\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Response error. Error: %+v\\n\", err.Error())\n\t\treturn nil, 500, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\t// Read response body\n\tstatusCode = resp.StatusCode\n\n\tresult, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error when converting response body to []byte: %+v\\n\", err.Error())\n\t\treturn nil, statusCode, err\n\t}\n\n\treturn result, statusCode, nil\n}", "func (c *Client) Get(path string) (io.ReadCloser, error) {\n\n\treq, err := http.NewRequest(\"GET\", c.url+\"/\"+path, nil)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"URL: %v\\n\", req.URL)\n\n\treq.Header.Add(\"Authorization\", \"Bearer \"+c.apiKey)\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func (oc *OAuthConsumer) Get( url string, fparams Params, at *AccessToken) (r *http.Response, err os.Error) {\n\treturn oc.oAuthRequest(url, fparams, at, \"GET\")\n}", "func Get(query string) (*client.Response, error) {\n\tresponse, err := client.Get(APIBaseURL+query).Header(\"Accept\", acceptType).End()\n\treturn response, err\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetOK), nil\n\n}", "func (a *Client) Get(params *GetParams) (*GetOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for get: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (r *Request) Get(url string) *Request {\n\tr.method = http.MethodGet\n\tr.url = url\n\treturn r\n}", "func (c clientType) Get(path string) (*resty.Response, error) {\n\treturn c.execute(http.MethodGet, path, nil)\n}", "func Get(ctx context.Context, url string, options ...RequestOption) (*Response, error) {\n\tr, err := newRequest(ctx, http.MethodGet, url, nil, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn doRequest(http.DefaultClient, r)\n}", "func Get(dst []byte, url string) (statusCode int, body []byte, err error) {\n\treturn defaultClient.Get(dst, url)\n}", "func (client *Client) Get(path string) Response {\n\treturn client.processRequest(path, \"GET\")\n}", "func (v *DCHttpClient) Get(url string, headers map[string]string) (response *DCHttpResponse, err error) {\n\treturn v.DoWithoutContent(http.MethodGet, url, headers)\n}", "func (c *Client) Get(ctx context.Context, query string) ([]byte, int, error) {\n\n\tauthKey, err := GetAccessTokenFromContext(ctx)\n\tif err != nil {\n\t\treturn nil, http.StatusForbidden, fmt.Errorf(\"Missing token in context\")\n\t}\n\n\treq, _ := http.NewRequest(\"GET\", query, nil)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"X-Requested-With\", \"XMLHttpRequest\")\n\treq.Header.Add(\"authorization\", authKey)\n\tresp, err := c.httpClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Error(\"GET request error:\", err)\n\t\treturn nil, resp.StatusCode, err\n\t}\n\t// this is required to properly empty the buffer for the next call\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn body, resp.StatusCode, err\n}", "func (c *Client) Get(path string, query map[string]string, response interface{}) error {\n\turl, err := c.createURL(path, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client: error creating http request: %s\", err.Error())\n\t}\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"token %s\", c.token))\n\treq.Header.Add(\"Accept\", c.AcceptHeader)\n\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client: error making a http request: %s\", err.Error())\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"client: error reading api error response: %s\", err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"client: GitHub api error - status %d: %s\", res.StatusCode, body)\n\t}\n\n\tdecoder := json.NewDecoder(res.Body)\n\terr = decoder.Decode(&response)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client: error unmarshaling json response: %s\", err.Error())\n\t}\n\treturn nil\n}", "func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\r\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\r\n\treturn\r\n}", "func (c *Client) Get(route string) (io.ReadCloser, error) {\n\t// Prepare HTTP request\n\treq, err := http.NewRequest(\"GET\", c.url+route, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do the request over the default client\n\treturn c.performRequest(req)\n}", "func (a *API) Get(u string) (*http.Response, []byte, error) {\n\tvar body []byte\n\tvar resp *http.Response\n\tif a.Verbose {\n\t\tfmt.Printf(\"Get: %v\\n\", u)\n\t}\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err == nil {\n\t\t// Salsa's API needs these cookies to verify authentication.\n\t\tfor _, c := range a.Cookies {\n\t\t\treq.AddCookie(c)\n\t\t}\n\t\tresp, err = a.Client.Do(req)\n\t\tif err == nil {\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tm := fmt.Sprintf(\"invalid response code %v\", resp.Status)\n\t\t\t\terr = errors.New(m)\n\t\t\t\treturn resp, body, err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err = ioutil.ReadAll(resp.Body)\n\t\t\tif a.Verbose {\n\t\t\t\tfmt.Printf(\"Get: %v\\n\", string(body))\n\t\t\t}\n\t\t}\n\t}\n\treturn resp, body, err\n}", "func (req *Req) Get(u string) ([]byte, error) {\n\treturn req.request(\"GET\", u)\n}", "func Get(url, authToken string) (*http.Response, error) {\n\treturn get(url, authToken, 1)\n}", "func Get(url string, ret interface{}) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"http get\")\n\t}\n\tdefer func() { _ = resp.Body.Close() }()\n\treturn dealResp(resp, ret)\n}", "func (c *Client) Get(path string, params map[string]string, res interface{}, auth bool) (err error) {\n\tif c.debug {\n\t\tfmt.Println(\"GET:\", auth, path, params)\n\t}\n\tif auth {\n\t\tc.Sign(path, \"\")\n\t}\n\n\tvar r *httpclient.Response\n\tr, err = c.api.Get(c.URL()+path, params)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\terr = handleResponse(r, res, auth)\n\treturn\n}", "func (api *API) Get(path string) (body []byte, statusCode int, err error) {\n\treq, err := http.NewRequest(\"GET\", api.host+path, nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tr, statusCode, err := api.do(req)\n\tif err != nil {\n\t\treturn nil, statusCode, err\n\t}\n\tbody, err = ioutil.ReadAll(r)\n\t_ = r.Close()\n\treturn body, statusCode, err\n}", "func Get(method, url string, params map[string]string, vPtr interface{}) error {\n\taccount, token, err := LoginWithSelectedAccount()\n\tif err != nil {\n\t\treturn LogError(\"Couldn't get account details or login token\", err)\n\t}\n\turl = fmt.Sprintf(\"%s%s\", account.ServerURL, url)\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif token != \"\" {\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\tq := req.URL.Query()\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer CloseTheCloser(resp.Body)\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\trespBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &respBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = LogError(fmt.Sprintf(\"error while getting service got http status code %s - %s\", resp.Status, respBody[\"error\"]), nil)\n\t\treturn fmt.Errorf(\"received invalid status code (%d)\", resp.StatusCode)\n\t}\n\n\tif err := json.Unmarshal(data, vPtr); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Get(domain, url, token, tokenKey string) (*http.Response, error) {\n\t/*\n\t * First we will initalize the client\n\t * Then we will send the get request\n\t * Then we will return the response\n\t */\n\t//initalizing the client\n\tclient := heimdallC.NewClient(\n\t\theimdallC.WithHTTPClient(&myHTTPClient{\n\t\t\ttoken: token,\n\t\t\ttokenKey: tokenKey,\n\t\t\tdomain: domain,\n\t\t}),\n\t)\n\n\t//then we will make the request\n\tres, err := client.Get(url, http.Header{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//return the response\n\treturn res, nil\n}", "func (c *httpClient) Get(url string,\n\theaders http.Header) (*Response, error) {\n\treturn c.do(http.MethodGet, url, headers, nil)\n}", "func (api *api) doGet(url string) (result []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Error(\"this shouldn't happen: %v\", err)\n\t\treturn nil, err\n\t}\n\tresp, err := api.client.Do(req)\n\tif err != nil {\n\t\tlog.Debug(\"got error response for URL %s: %v\", url, err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tstatusCode, status := resp.StatusCode, resp.Status\n\tif statusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"IB returned an error: %s: %s\", status, url)\n\t}\n\n\tresult, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading response body: %v: %s\", err, url)\n\t}\n\n\tlog.Trace(\"%s : SUCCESS\", url)\n\treturn result, nil\n}", "func (g *Github) Get(url string) (*http.Response, error) {\n\treturn g.Do(http.MethodGet, url, http.NoBody)\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\n\tresp, err := c.client.Do(req)\n\treturn resp, err\n}", "func httpGet(t *testing.T, url string) ([]byte, error) {\n\tclient := &http.Client{}\n\tresp, err := invokeWithRetry(\n\t\tfunc() (response *http.Response, e error) {\n\t\t\treturn client.Get(url)\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\treturn handleHttpResp(t, resp)\n}", "func (its *Request) Get() ([]byte, error) {\n\trequest, err := http.NewRequest(\"GET\", its.IsHTTPS+\"://\"+its.Host+its.Path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add BearToken auth\n\tif its.BearToken != \"\" {\n\t\trequest.Header.Add(\"Authorization\", \"Bearer \"+its.BearToken)\n\t}\n\n\tclient := http.Client{}\n\t// add InsecureSkipVerify\n\tif its.IsHTTPS == \"https\" {\n\t\tclient.Transport = tr\n\t}\n\n\t// execute this request\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get,read and return\n\tdefer resp.Body.Close()\n\ttmp, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tmp, nil\n}", "func get(url string) (string, error) {\n\t//defer fetch.CatchPanic(\"Get()\")\n\tresp, err := httpClient.Get(url)\n\tif err != nil {\n\t\tpanic(\"Couldn't perform GET request to \" + url)\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Unable to read the response body\")\n\t}\n\ts := string(bytes)\n\treturn s, nil\n}", "func Get(targetURL string, params map[string]string, authHeader string) ([]byte, error) {\n\tlog.Debugf(\"GET targetURL=%s, params=%+v, auth=%s\", targetURL, params, authHeader)\n\n\treq, _ := http.NewRequest(\"GET\", targetURL, nil)\n\treq.URL.RawQuery = convertToValues(params).Encode()\n\tif authHeader != \"\" {\n\t\treq.Header.Add(\"Authorization\", authHeader)\n\t}\n\treturn doRequest(req)\n}", "func HTTPGET(url string, auth bool, authToken string) (int, []byte, error) {\n\treturn httpRequest(\"GET\", url, auth, authToken, nil)\n}", "func (session *Session) Get(path string, params Params) (res Result, err error) {\n\turlStr := session.app.BaseEndPoint + session.getRequestUrl(path, params)\n\n\tvar response []byte\n\tresponse, err = session.SendGetRequest(urlStr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tres, err = MakeResult(response)\n\treturn\n}", "func (h *httpCloud) get(path string, resp interface{}) error {\n\trequestType := \"GET\"\n\tbody, err := h.sendHTTPRequest(requestType, path, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"HTTP request to cloudprovider failed: %v\", err)\n\t}\n\tif body != nil {\n\t\tif err := json.Unmarshal(body, resp); err != nil {\n\t\t\treturn fmt.Errorf(\"GET response Unmarshal for %s failed with error: %v\\n\", path, err)\n\t\t}\n\t}\n\treturn nil\n}", "func HTTPGet(params *HTTPRequest) (*http.Response, error) {\n\tparams.Method = \"GET\"\n\tprintHTTPRequest(params)\n\n\tu, err := url.Parse(params.URL)\n\tif err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\tif len(params.Query) > 0 {\n\t\tu.RawQuery = params.Query.Encode()\n\t}\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err := printHTTPResponse(params.URL, resp); err != nil {\n\t\tprintErrorLine(err)\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func Get(url string) *THttpClient {\r\n\treturn NewHttpClient(url).Get(\"\")\r\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\tb := c.breakerLookup(url)\n\tif b == nil {\n\t\treturn c.client.Get(url)\n\t}\n\n\tctx := getGetCtx()\n\tdefer releaseGetCtx(ctx)\n\n\tctx.Client = c.client\n\tctx.ErrorOnBadStatus = c.errOnBadStatus\n\tctx.URL = url\n\tif err := b.Call(ctx, breaker.WithTimeout(c.timeout)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ctx.Response, ctx.Error\n}", "func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := client.Get(getURL(client, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := client.Get(getURL(client, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := client.Get(getURL(client, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (sr *Client) get(uri string) (body []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", uri, &bytes.Buffer{})\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"create new HTTP request: %v: %v\", uri, err.Error())\n\t}\n\n\tdata, err := sr.c.Do(req)\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"make request error:%v: %v\", uri, err.Error())\n\t}\n\tdefer data.Body.Close()\n\n\tif data.StatusCode != 200 {\n\t\tdata, err = sr.c.Do(req)\n\t\tif err != nil {\n\t\t\treturn body, fmt.Errorf(\"make request retry error:%v: %v\", uri, err.Error())\n\t\t}\n\t\tdefer data.Body.Close()\n\n\t\tif data.StatusCode != 200 {\n\t\t\treturn body, fmt.Errorf(\"make request retry error: unexpected response status %v\", data.StatusCode)\n\t\t}\n\t}\n\n\tbody, err = ioutil.ReadAll(data.Body)\n\tif err != nil {\n\t\treturn body, fmt.Errorf(\"read body error: %v\", err.Error())\n\t}\n\n\treturn body, nil\n}", "func Get(c *eclcloud.ServiceClient, id string) (r GetResult) {\n\t_, r.Err = c.Get(getURL(c, id), &r.Body, nil)\n\treturn\n}", "func (c *Client) Get(dst []byte, url string) (statusCode int, body []byte, err error) {\n\treturn clientGetURL(dst, url, c)\n}", "func (conn Connection) Get(cmd string, result interface{}) (effect *SideEffect, resp *http.Response, err error) {\n\treturn conn.Send(http.MethodGet, cmd, nil, result)\n}", "func (d *Doer) Get(url string, response interface{}) (*http.Response, error) {\n\treq, err := d.newRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d.do(req, response)\n}", "func Get(client *eclcloud.ServiceClient, id string) (r GetResult) {\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\n\treturn\n}", "func Get(client *eclcloud.ServiceClient, id string) (r GetResult) {\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\n\treturn\n}", "func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, nil)\n\treturn\n}", "func (a *APITest) Get(url string) *Request {\n\ta.request.method = http.MethodGet\n\ta.request.url = url\n\treturn a.request\n}", "func (m *MockClient) Get(url string) (*http.Response, error) {\n\treturn GetFunc(url)\n}", "func (this *HttpClient) get(name string, version int, watch bool, sourceVersion string) (*http.Response, error) {\n\n\tlog.Println(\"Getting bucket: \", name)\n\n\treq, err := http.NewRequest(\"GET\", this.getBucketURL(name, version, watch), nil)\n\tif err != nil {\n\t\tlog.Println(\"Error creating new request\", err)\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"X-Config-Bucket-Version\", sourceVersion)\n\n // identity headers\n req.Header.Add(\"X-Client-IPv4\", this.ipv4)\n req.Header.Add(\"X-Client-Hostname\", this.hostname)\n\n\tresp, err := this.instance.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"Error making request\", err)\n\t\treturn nil, err\n\t} else {\n\t\treturn resp, nil\n\t}\n}", "func Get(client *gophercloud.ServiceClient, id string) GetResult {\n\tvar res GetResult\n\t_, res.Err = client.Get(getURL(client, id), &res.Body, nil)\n\treturn res\n}", "func get(url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"got status code: %s\", resp.Status)\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func Get(c *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Get(c *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (c *baseClient) Get(path string) *baseClient {\n\tc.method = \"GET\"\n\treturn c.Path(path)\n}" ]
[ "0.77595377", "0.77251273", "0.7716675", "0.76562077", "0.76207167", "0.7431276", "0.7420969", "0.7399707", "0.7396884", "0.7348557", "0.7347757", "0.73327327", "0.7316341", "0.7291157", "0.72833484", "0.7280878", "0.723802", "0.7236105", "0.7231965", "0.719686", "0.71941847", "0.7192224", "0.7165984", "0.7162419", "0.71544045", "0.7148544", "0.713202", "0.71272796", "0.7127075", "0.71153563", "0.70750505", "0.7071432", "0.706745", "0.70660996", "0.70419765", "0.7036202", "0.70260394", "0.7022839", "0.7018793", "0.70128745", "0.699313", "0.699311", "0.6988547", "0.6985106", "0.69642663", "0.6956303", "0.6953163", "0.6950379", "0.6943648", "0.6938541", "0.69310796", "0.69287264", "0.692215", "0.6916987", "0.69106025", "0.69023407", "0.68957907", "0.6893204", "0.6889096", "0.68888056", "0.6886476", "0.6882325", "0.688093", "0.6878596", "0.6874702", "0.68714815", "0.6870531", "0.68662465", "0.68639463", "0.6863108", "0.6861974", "0.6861477", "0.6861209", "0.6857534", "0.68377227", "0.68364954", "0.68290436", "0.6815403", "0.6811947", "0.68112946", "0.68104357", "0.68056476", "0.68023676", "0.68023676", "0.68023676", "0.679091", "0.67837036", "0.67835045", "0.6777032", "0.677641", "0.6767916", "0.6767916", "0.67594415", "0.67549676", "0.6750325", "0.67497474", "0.6746567", "0.6745042", "0.6741427", "0.6741427", "0.67412794" ]
0.0
-1
IsHcloudServer checks if the currently called server is a hcloud server by calling a metadata endpoint if the endpoint answers with a nonempty value this method returns true, otherwise false.
func (c *Client) IsHcloudServer() bool { hostname, err := c.Hostname() if err != nil { return false } if len(hostname) > 0 { return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *StorageNetAppCloudTargetAllOf) HasServer() bool {\n\tif o != nil && o.Server != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VirtualizationIweHost) HasPhysicalServer() bool {\n\tif o != nil && o.PhysicalServer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerCloud() bool {\n\tif o != nil && o.ServerCloud != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *StorageRemoteKeySetting) HasPrimaryServer() bool {\n\tif o != nil && o.PrimaryServer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ServerConfigImportAllOf) HasServer() bool {\n\tif o != nil && o.Server != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *StorageRemoteKeySetting) HasSecondaryServer() bool {\n\tif o != nil && o.SecondaryServer != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *IamLdapProviderAllOf) HasServer() bool {\n\tif o != nil && o.Server != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ConvergedinfraServerComplianceDetailsAllOf) HasServer() bool {\n\tif o != nil && o.Server != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DhcpRangeDataData) HasServerType() bool {\n\tif o != nil && o.ServerType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *OsInstallAllOf) HasServer() bool {\n\tif o != nil && o.Server != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Command) hasServerHTTP() bool {\n\treturn c.Flags&FlagSetServerHTTP != 0\n}", "func (o *DhcpRangeDataData) HasServerName() bool {\n\tif o != nil && o.ServerName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Cloud) IsHealth() (bool, error) {\n\tif err := c.runCmd(infra.Scripts[\"check_fx_agent\"].(string)); err != nil {\n\t\tif err := c.runCmd(infra.Scripts[\"start_fx_agent\"].(string)); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn true, nil\n}", "func (o *StorageEnclosure) HasServerId() bool {\n\tif o != nil && o.ServerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (n PidMode) IsHost() bool {\n\treturn n == \"host\"\n}", "func (o *StorageRemoteKeySetting) HasServerCertificate() bool {\n\tif o != nil && o.ServerCertificate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (n IpcMode) IsHost() bool {\n\treturn n == IPCModeHost\n}", "func (provider *cloudStackCloudProvider) HasInstance(node *v1.Node) (bool, error) {\n\treturn true, cloudprovider.ErrNotImplemented\n}", "func (o *GuardianPolicyDataData) HasServerName() bool {\n\tif o != nil && o.ServerName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *ManagerClient) IsServerUp() bool {\n\tget, err := m.Prepare(\"GET\", GetServerKeyURL, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"IsServerUp cannot create server key request: %s\", err)\n\t\treturn false\n\t}\n\tresp, err := m.httpClient.Do(get)\n\tif err != nil {\n\t\tlog.Errorf(\"IsServerUp cannot issue server key request: %s\", err)\n\t\treturn false\n\t}\n\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t\treturn resp.StatusCode == 200\n\t}\n\treturn false\n}", "func (o *PluginDnsClient) IsNameServer() bool { return o.params.NameServer }", "func (o *HyperflexServerFirmwareVersionEntryAllOf) HasServerPlatform() bool {\n\tif o != nil && o.ServerPlatform != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DhcpRangeDataData) HasServerId() bool {\n\tif o != nil && o.ServerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (d *DeploymentOptions) IsCloud() bool {\n\treturn d.Target.Type() == TargetCloud || d.Target.Type() == TargetHosted\n}", "func (n UsernsMode) IsHost() bool {\n\treturn n == \"host\"\n}", "func (r Virtual_Guest) IsCloudInit() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"isCloudInit\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *GuardianPolicyDataData) HasServerId() bool {\n\tif o != nil && o.ServerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HostsAnomalyDetectionConfig) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (d *HetznerCloudProvider) HasInstance(node *apiv1.Node) (bool, error) {\n\treturn true, cloudprovider.ErrNotImplemented\n}", "func (mgr *endpointManager) HostEndpointExists() bool {\n\treturn mgr.GetHostEndpoint() != nil\n}", "func dsHasServer(ds tc.DeliveryServiceName, crConfig tc.CRConfig) bool {\n\tfor _, server := range crConfig.ContentServers {\n\t\tif _, ok := server.DeliveryServices[string(ds)]; ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n\n}", "func (n UTSMode) IsHost() bool {\n\treturn n == \"host\"\n}", "func (o *DnsZoneDataData) HasServerType() bool {\n\tif o != nil && o.ServerType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DhcpRangeDataData) HasServerVersion() bool {\n\tif o != nil && o.ServerVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsViewparamDataData) HasServerName() bool {\n\tif o != nil && o.ServerName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DhcpRangeDataData) HasServerAddr() bool {\n\tif o != nil && o.ServerAddr != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsViewparamDataData) HasServerId() bool {\n\tif o != nil && o.ServerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (mi *MinIOInstance) HasMetadata() bool {\n\treturn mi.Spec.Metadata != nil\n}", "func (i *SampleConfigIntegration) HasMultipleServers() bool {\n\treturn len(i.Servers) > 1\n}", "func (info *endpointsInfo) IsServing() bool {\n\treturn info.serving\n}", "func (instance *Host) Exists(ctx context.Context) (_ bool, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn false, fail.InvalidInstanceError()\n\t}\n\n\tdefer elapsed(ctx, fmt.Sprintf(\"Exist of %s\", instance.name.Load().(string)))()\n\ttheID, err := instance.GetID()\n\tif err != nil {\n\t\treturn false, fail.ConvertError(err)\n\t}\n\n\tif beta := os.Getenv(\"SAFESCALE_DETECT_CORRUPTION\"); beta != \"yes\" {\n\t\treturn true, nil\n\t}\n\n\t_, xerr := instance.Service().InspectHost(ctx, theID)\n\tif xerr != nil {\n\t\tswitch xerr.(type) {\n\t\tcase *fail.ErrNotFound:\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\treturn false, xerr\n\t\t}\n\t}\n\n\treturn true, nil\n}", "func (o *AppSso) HasMetadataUrl() bool {\n\tif o != nil && o.MetadataUrl != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *ManagerClient) IsServerAuthenticated() (auth bool, up bool) {\n\tif m.IsServerAuthEnforced() {\n\t\tget, err := m.Prepare(\"GET\", GetServerKeyURL, nil)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"IsServerAuthenticated cannot create server key request: %s\", err)\n\t\t\treturn false, false\n\t\t}\n\t\tresp, err := m.httpClient.Do(get)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"IsServerAuthenticated cannot issue server key request: %s\", err)\n\t\t\treturn false, false\n\t\t}\n\t\tif resp != nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode == 200 {\n\t\t\t\tkey, _ := ioutil.ReadAll(resp.Body)\n\t\t\t\tif m.serverKey == string(key) {\n\t\t\t\t\t// if the server can be authenticated\n\t\t\t\t\treturn true, true\n\t\t\t\t}\n\t\t\t\tlog.Warn(\"Failed to authenticate remote server\")\n\t\t\t\t// if the server is not authenticated\n\t\t\t\treturn false, true\n\t\t\t}\n\t\t\treturn false, false\n\t\t}\n\t\treturn false, false\n\t}\n\treturn true, m.IsServerUp()\n}", "func (h *host) Health() bool {\n\treturn h.healthFlags == 0\n}", "func (o *DnsZoneDataData) HasServerIpmType() bool {\n\tif o != nil && o.ServerIpmType != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TxsdCounterSimpleContentExtensionType) IsHost() bool { return me.String() == \"host\" }", "func isHost(mode string) bool {\n\treturn mode == \"host\"\n}", "func (o *DhcpRangeDataData) HasServerClassName() bool {\n\tif o != nil && o.ServerClassName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerClassName() bool {\n\tif o != nil && o.ServerClassName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (k *kamateraCloudProvider) HasInstance(node *apiv1.Node) (bool, error) {\n\treturn true, cloudprovider.ErrNotImplemented\n}", "func (o *DnsZoneDataData) HasServerState() bool {\n\tif o != nil && o.ServerState != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerName() bool {\n\tif o != nil && o.ServerName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (host Host) IsEmpty() bool {\n\treturn host.Name == \"\"\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsServerPublic() bool {\n\treturn me.String() == \"server-public\"\n}", "func (c *Config) IsGCPManaged() bool {\n\treturn c.Tenant.InternalAPI == \"\"\n}", "func (o *DnsZoneDataData) HasServerIpmProtocol() bool {\n\tif o != nil && o.ServerIpmProtocol != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SmartstackBackend) HasHostname() bool {\n\tif o != nil && o.Hostname != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (tencentcloud *tencentCloudProvider) HasInstance(node *apiv1.Node) (bool, error) {\n\treturn true, cloudprovider.ErrNotImplemented\n}", "func (o *DnsZoneDataData) HasServerForceHybrid() bool {\n\tif o != nil && o.ServerForceHybrid != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *V1VirusDatasetRequest) HasHost() bool {\n\tif o != nil && o.Host != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerId() bool {\n\tif o != nil && o.ServerId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *V2TcpConfiguration) HasHost() bool {\n\tif o != nil && o.Host != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (impl *Server) Exist(s *model.Server) (bool, base.ModelInterface) {\n\tvar (\n\t\tc = impl.TemplateImpl.GetConnection()\n\t\tserver = new(entity.Server)\n\t)\n\n\tif s == nil {\n\t\treturn false, nil\n\t}\n\n\tc.Where(\"\\\"PhysicalUUID\\\" = ?\", s.PhysicalUUID).First(server)\n\tif s.PhysicalUUID == server.PhysicalUUID {\n\t\treturn true, server.ToModel()\n\t}\n\treturn false, nil\n}", "func ServerDeploymentConfig_IsResource(construct awscdk.IConstruct) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_codedeploy.ServerDeploymentConfig\",\n\t\t\"isResource\",\n\t\t[]interface{}{construct},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *VirtualizationIweVirtualMachine) HasHost() bool {\n\tif o != nil && o.Host != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *StorageNetAppCloudTargetAllOf) HasCloudStorage() bool {\n\tif o != nil && o.CloudStorage != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Service) HasServiceVhost() bool {\n\tif o != nil && o.ServiceVhost != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SchemaDefinitionRestDto) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsHAProxySupported() (bool, error) {\n\tminVersion := haProxyMinPMMServerVersion\n\tlessThanMinVersion, err := ServerVersionLessThan(minVersion)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif lessThanMinVersion {\n\t\treturn false, fmt.Errorf(\"haproxy is not supported in this version, please update your pmm-server to %s or higher\", minVersion)\n\t}\n\n\treturn true, nil\n}", "func (c CgroupnsMode) IsHost() bool {\n\treturn c == CgroupnsModeHost\n}", "func (i *ServerDBImplement) IsServerExist(s *model.Server) (bool, *model.Server) {\n\tif s == nil {\n\t\treturn false, nil\n\t}\n\tc := commonDB.GetConnection()\n\tserver := new(entity.Server)\n\tc.Where(\"Physical_UUID = ?\", s.PhysicalUUID).First(server)\n\tif s.PhysicalUUID == server.PhysicalUUID {\n\t\treturn true, createServerModel(server)\n\t}\n\treturn false, nil\n}", "func (p *PluginConfig) IsRemote() bool {\n\treturn p.GetRemoteHostname() != \"\"\n}", "func isServerDirective(directive string) bool {\n\tif isEqualString(directive, ServerDirective) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *StoragePhysicalDisk) HasIsPlatformSupported() bool {\n\tif o != nil && o.IsPlatformSupported != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *provision) isCloud() bool {\n\treturn p.IsGCPManaged && p.runtimeType == \"CLOUD\"\n}", "func (m *ManagerClient) IsServerAuthEnforced() bool {\n\treturn m.serverKey != \"\"\n}", "func (o *HyperflexSoftwareVersionPolicy) HasServerFirmwareVersionInfo() bool {\n\tif o != nil && o.ServerFirmwareVersionInfo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (z *Zone) HasMetadata() bool {\n\tj, _ := json.Marshal(z)\n\tj2, _ := json.Marshal(&Zone{Domain: z.Domain})\n\treturn string(j) != string(j2)\n}", "func (bsmr BlobsSetMetadataResponse) IsServerEncrypted() string {\n\treturn bsmr.rawResponse.Header.Get(\"x-ms-request-server-encrypted\")\n}", "func hasMultipleServers(config clientcmdapi.Config) bool {\n\tserver := \"\"\n\tfor _, cluster := range config.Clusters {\n\t\tif len(server) == 0 {\n\t\t\tserver = cluster.Server\n\t\t}\n\t\tif server != cluster.Server {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s *Server) isHealthy() bool {\n\treturn s.healthy && s.serviceHealthyFn()\n}", "func (o *VirtualizationIweHost) GetPhysicalServerOk() (*ComputePhysicalRelationship, bool) {\n\tif o == nil || o.PhysicalServer == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PhysicalServer, true\n}", "func (o *VirtualizationIweHost) HasManagementIpAddress() bool {\n\tif o != nil && o.ManagementIpAddress != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func ServerArgsPresent(neededArgs []string) bool {\n\tcurrentArgs := K3sServerArgs()\n\tfor _, arg := range neededArgs {\n\t\tif !contains(currentArgs, arg) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *EnvironmentAutoUpdateConfig) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TxsdNodeRoleSimpleContentExtensionCategory) IsServerInternal() bool {\n\treturn me.String() == \"server-internal\"\n}", "func (sd *ServiceData) HasUnaryEndpoint() bool {\n\tfor _, ed := range sd.Endpoints {\n\t\tif ed.ServerStream == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *DhcpRangeDataData) HasServerClassParameters() bool {\n\tif o != nil && o.ServerClassParameters != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func HasMetadata() predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(Table, FieldID),\n\t\t\tsqlgraph.To(MetadataTable, FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, false, MetadataTable, MetadataColumn),\n\t\t)\n\t\tsqlgraph.HasNeighbors(s, step)\n\t})\n}", "func (bgpr BlobsGetPropertiesResponse) IsServerEncrypted() string {\n\treturn bgpr.rawResponse.Header.Get(\"x-ms-server-encrypted\")\n}", "func (o *IamServiceProviderAllOf) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerVersion() bool {\n\tif o != nil && o.ServerVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ServerConfigImportAllOf) HasServerProfile() bool {\n\tif o != nil && o.ServerProfile != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *Switch) Has_host( host *string ) (bool) {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tif s.hvmid[*host] != nil {\t\t\t// allow searches based on the uuid\n\t\treturn true\n\t}\n\n\treturn s.hosts[*host]\n}", "func (o *DhcpRangeDataData) HasServerComment() bool {\n\tif o != nil && o.ServerComment != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsServerlessDomain(domain string) bool {\n\treturn serverlessDomainRegex.MatchString(domain)\n}", "func (options *Options) HasCloudOptions() bool {\n\treturn options.ScanList ||\n\t\toptions.DeleteScan != \"\" ||\n\t\toptions.ScanOutput != \"\" ||\n\t\toptions.ListDatasources ||\n\t\toptions.ListTargets ||\n\t\toptions.ListTemplates ||\n\t\toptions.RemoveDatasource != \"\" ||\n\t\toptions.AddTarget != \"\" ||\n\t\toptions.AddTemplate != \"\" ||\n\t\toptions.RemoveTarget != \"\" ||\n\t\toptions.RemoveTemplate != \"\" ||\n\t\toptions.GetTarget != \"\" ||\n\t\toptions.GetTemplate != \"\"\n}", "func ServerApplication_IsResource(construct awscdk.IConstruct) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_codedeploy.ServerApplication\",\n\t\t\"isResource\",\n\t\t[]interface{}{construct},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (s *Server) HasMethod(method string) bool {\n if _, _, err := s.services.get(method); err == nil {\n return true\n }\n return false\n}", "func (s *Server) HasMethod(name string) bool {\n\t_, err := s.services.get(name)\n\treturn err == nil\n}" ]
[ "0.6468986", "0.64323115", "0.642939", "0.61945724", "0.60722655", "0.5934701", "0.5887409", "0.58597904", "0.5826412", "0.5817674", "0.5815323", "0.5770542", "0.56772035", "0.56686264", "0.5660452", "0.5634336", "0.56322336", "0.56308174", "0.5621893", "0.5621792", "0.56046677", "0.5593535", "0.55872613", "0.557252", "0.55586785", "0.5550444", "0.55311596", "0.55310917", "0.5528195", "0.55256015", "0.5519961", "0.5516251", "0.5495807", "0.5487616", "0.54793704", "0.546591", "0.54606265", "0.5456645", "0.5450787", "0.54501736", "0.54331326", "0.5425586", "0.54227746", "0.54110026", "0.54095405", "0.5396579", "0.5395271", "0.53772116", "0.53666323", "0.5351817", "0.5348562", "0.5342183", "0.53404695", "0.53331983", "0.5325179", "0.53250426", "0.5323923", "0.5307883", "0.5301957", "0.52903545", "0.52820253", "0.527882", "0.52571917", "0.5240546", "0.52123296", "0.5208092", "0.520446", "0.52026534", "0.52018154", "0.5199428", "0.51912004", "0.5179479", "0.51755005", "0.51645076", "0.5157076", "0.5152117", "0.51512253", "0.51425296", "0.5133714", "0.5130072", "0.5121853", "0.5115121", "0.5113129", "0.51027864", "0.5102047", "0.5101461", "0.50951564", "0.50948954", "0.50908506", "0.5089082", "0.5080632", "0.50764906", "0.50752616", "0.5074382", "0.5073886", "0.5073858", "0.5073729", "0.5071145", "0.5062825", "0.5058123" ]
0.8344598
0
Hostname returns the hostname of the server that did the request to the Metadata server.
func (c *Client) Hostname() (string, error) { return c.get("/hostname") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *AppServerV3) GetHostname() string {\n\treturn s.Spec.Hostname\n}", "func (s *DatabaseServerV3) GetHostname() string {\n\treturn s.Spec.Hostname\n}", "func (rc RequestCall) GetHostname() string {\n\treturn strings.Split(rc.Request.Host, \":\")[0]\n}", "func (s *ProvisionedServer) HostName() string { return s.Server.Hostname }", "func (s *WindowsDesktopServiceV3) GetHostname() string {\n\treturn s.Spec.Hostname\n}", "func (m *Message) GetHostname() string {\n\tif m.Lambda != nil {\n\t\treturn m.Lambda.ARN\n\t}\n\thname, err := hostname.Get(context.TODO())\n\tif err != nil {\n\t\t// this scenario is not likely to happen since\n\t\t// the agent cannot start without a hostname\n\t\thname = \"unknown\"\n\t}\n\treturn hname\n}", "func GetHostname(req *http.Request) string {\n\tif req == nil {\n\t\treturn \"\"\n\t}\n\th, _, err := net.SplitHostPort(req.Host)\n\tif err != nil {\n\t\treturn req.Host\n\t}\n\treturn h\n}", "func GetHostname(ctx context.Context) (string, error) {\n\tmetadataJSON, err := instanceMetaFetcher.Fetch(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar metadata struct {\n\t\tVMID string\n\t}\n\tif err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse Azure instance metadata: %s\", err)\n\t}\n\n\tif err := validate.ValidHostname(metadata.VMID); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn metadata.VMID, nil\n}", "func GetHostname() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\n\thostname, err := getMetadataItemWithMaxLength(\"/hostname\", config.Datadog.GetInt(\"metadata_endpoints_max_hostname_size\"))\n\tif err != nil {\n\t\tif hostname, found := cache.Cache.Get(hostnameCacheKey); found {\n\t\t\tlog.Debugf(\"Unable to get ec2 hostname from aws metadata, returning cached hostname '%s': %s\", hostname, err)\n\t\t\treturn hostname.(string), nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tcache.Cache.Set(hostnameCacheKey, hostname, cache.NoExpiration)\n\n\treturn hostname, nil\n}", "func (o LookupServerResultOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServerResult) string { return v.Hostname }).(pulumi.StringOutput)\n}", "func (o *SmartstackBackend) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (s *SessionTrackerV1) GetHostname() string {\n\treturn s.Spec.Hostname\n}", "func (m *SiteCollection) GetHostname()(*string) {\n return m.hostname\n}", "func GetHostname() (string, error) {\n\thostnameData, err := GetHostnameData()\n\treturn hostnameData.Hostname, err\n}", "func (o *NodeUpdate) GetHostname() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Hostname\n}", "func (o *ShowSystem) GetHostname() string {\n\tif o == nil || IsNil(o.Hostname) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (c *Ctx) Hostname() string {\n\treturn BytesToString(c.Request.URI().Host())\n}", "func (o *EventAttributes) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (f *FastURL) GetHostname() []byte {\n\treturn f.hostname\n}", "func Hostname() (string, error)", "func (o *ServiceCheck) GetHostName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn o.HostName\n}", "func GetHostName() string {\n\treturn os.Getenv(\"HOSTNAME\")\n}", "func (o *V0037Node) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (o *ApplianceDeviceClaimAllOf) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (o GetServiceHostnameConfigurationManagementOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceHostnameConfigurationManagement) string { return v.HostName }).(pulumi.StringOutput)\n}", "func GetHostname() string {\n\thostname, err := os.Hostname()\n\n\tif err != nil {\n\t\thostname = \"Unknown\"\n\t\tlog.Fatal(err)\n\t}\n\n\treturn hostname\n}", "func GetHostname() string {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn name\n}", "func (o ServiceHostnameConfigurationManagementOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationManagement) string { return v.HostName }).(pulumi.StringOutput)\n}", "func getHostName() (string){\n host, err := os.Hostname()\n if err != nil {\n fmt.Println(\"%s\", err)\n log.Error(\"get os.HostName error \", err)\n } else {\n //fmt.Println(\"%s\", host)\n log.Debugf(\"get os.HostName success host:\", host)\n }\n return host\n}", "func (o GetServiceHostnameConfigurationScmOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceHostnameConfigurationScm) string { return v.HostName }).(pulumi.StringOutput)\n}", "func internalHostname() (hn string, err error) {\n\t// attempt to fetch FQDN\n\thn, err = helpers.RunCommand(\"/usr/bin/env\", \"\", \"hostname\", \"-f\")\n\tif err == nil && hn != \"\" {\n\t\treturn\n\t}\n\n\t// failing that try the short name\n\thn, err = helpers.RunCommand(\"/usr/bin/env\", \"\", \"hostname\")\n\tif err == nil && hn != \"\" {\n\t\treturn\n\t}\n\n\t// return whatever we did get including the error\n\treturn\n}", "func GetHostname() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Errorf(\"failed to get hostname, err: %v\", err)\n\t\treturn \"\"\n\t}\n\n\treturn hostname\n}", "func (o CustomDomainManagementOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainManagement) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o HybridConnectionOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (o *NSQProducer) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (p *ProxyForward) GetHostname() string {\n\tif p.Hostname != \"\" {\n\t\treturn p.Hostname\n\t}\n\n\treturn p.Name\n}", "func (o ServiceHostnameConfigurationScmOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationScm) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (_this *URL) Hostname() string {\n\tvar ret string\n\tvalue := _this.Value_JS.Get(\"hostname\")\n\tret = (value).String()\n\treturn ret\n}", "func GetHostnameData() (HostnameData, error) {\n\tcacheHostnameKey := cache.BuildAgentKey(\"hostname\")\n\tif cacheHostname, found := cache.Cache.Get(cacheHostnameKey); found {\n\t\treturn cacheHostname.(HostnameData), nil\n\t}\n\n\tvar hostName string\n\tvar err error\n\tvar provider string\n\n\t// try the name provided in the configuration file\n\tconfigName := config.Datadog.GetString(\"hostname\")\n\terr = validate.ValidHostname(configName)\n\tif err == nil {\n\t\thostnameData := saveHostnameData(cacheHostnameKey, configName, HostnameProviderConfiguration)\n\t\tif !isHostnameCanonicalForIntake(configName) && !config.Datadog.GetBool(\"hostname_force_config_as_canonical\") {\n\t\t\t_ = log.Warnf(\"Hostname '%s' defined in configuration will not be used as the in-app hostname. For more information: https://dtdg.co/agent-hostname-force-config-as-canonical\", configName)\n\t\t}\n\t\treturn hostnameData, err\n\t}\n\n\texpErr := new(expvar.String)\n\texpErr.Set(err.Error())\n\thostnameErrors.Set(\"configuration/environment\", expErr)\n\n\tlog.Debugf(\"Unable to get the hostname from the config file: %s\", err)\n\tlog.Debug(\"Trying to determine a reliable host name automatically...\")\n\n\t// if fargate we strip the hostname\n\tif fargate.IsFargateInstance() {\n\t\thostnameData := saveHostnameData(cacheHostnameKey, \"\", \"\")\n\t\treturn hostnameData, nil\n\t}\n\n\t// GCE metadata\n\tlog.Debug(\"GetHostname trying GCE metadata...\")\n\tif getGCEHostname, found := hostname.ProviderCatalog[\"gce\"]; found {\n\t\tgceName, err := getGCEHostname()\n\t\tif err == nil {\n\t\t\thostnameData := saveHostnameData(cacheHostnameKey, gceName, \"gce\")\n\t\t\treturn hostnameData, err\n\t\t}\n\t\texpErr := new(expvar.String)\n\t\texpErr.Set(err.Error())\n\t\thostnameErrors.Set(\"gce\", expErr)\n\t\tlog.Debug(\"Unable to get hostname from GCE: \", err)\n\t}\n\n\t// FQDN\n\tvar fqdn string\n\tcanUseOSHostname := isOSHostnameUsable()\n\tif canUseOSHostname {\n\t\tlog.Debug(\"GetHostname trying FQDN/`hostname -f`...\")\n\t\tfqdn, err = getSystemFQDN()\n\t\tif config.Datadog.GetBool(\"hostname_fqdn\") && err == nil {\n\t\t\thostName = fqdn\n\t\t\tprovider = \"fqdn\"\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\texpErr := new(expvar.String)\n\t\t\t\texpErr.Set(err.Error())\n\t\t\t\thostnameErrors.Set(\"fqdn\", expErr)\n\t\t\t}\n\t\t\tlog.Debug(\"Unable to get FQDN from system: \", err)\n\t\t}\n\t}\n\n\tisContainerized, containerName := getContainerHostname()\n\tif isContainerized {\n\t\tif containerName != \"\" {\n\t\t\thostName = containerName\n\t\t\tprovider = \"container\"\n\t\t} else {\n\t\t\texpErr := new(expvar.String)\n\t\t\texpErr.Set(\"Unable to get hostname from container API\")\n\t\t\thostnameErrors.Set(\"container\", expErr)\n\t\t}\n\t}\n\n\tif canUseOSHostname && hostName == \"\" {\n\t\t// os\n\t\tlog.Debug(\"GetHostname trying os...\")\n\t\tsystemName, err := os.Hostname()\n\t\tif err == nil {\n\t\t\thostName = systemName\n\t\t\tprovider = \"os\"\n\t\t} else {\n\t\t\texpErr := new(expvar.String)\n\t\t\texpErr.Set(err.Error())\n\t\t\thostnameErrors.Set(\"os\", expErr)\n\t\t\tlog.Debug(\"Unable to get hostname from OS: \", err)\n\t\t}\n\t}\n\n\t/* at this point we've either the hostname from the os or an empty string */\n\n\t// We use the instance id if we're on an ECS cluster or we're on EC2\n\t// and the hostname is one of the default ones\n\tif getEC2Hostname, found := hostname.ProviderCatalog[\"ec2\"]; found {\n\t\tlog.Debug(\"GetHostname trying EC2 metadata...\")\n\n\t\tif ecs.IsECSInstance() || ec2.IsDefaultHostname(hostName) {\n\t\t\tec2Hostname, err := getValidEC2Hostname(getEC2Hostname)\n\n\t\t\tif err == nil {\n\t\t\t\thostName = ec2Hostname\n\t\t\t\tprovider = \"aws\"\n\t\t\t} else {\n\t\t\t\texpErr := new(expvar.String)\n\t\t\t\texpErr.Set(err.Error())\n\t\t\t\thostnameErrors.Set(\"aws\", expErr)\n\t\t\t\tlog.Debug(err)\n\t\t\t}\n\t\t} else {\n\t\t\terr := fmt.Errorf(\"not retrieving hostname from AWS: the host is not an ECS instance and other providers already retrieve non-default hostnames\")\n\t\t\tlog.Debug(err.Error())\n\t\t\texpErr := new(expvar.String)\n\t\t\texpErr.Set(err.Error())\n\t\t\thostnameErrors.Set(\"aws\", expErr)\n\n\t\t\t// Display a message when enabling `ec2_use_windows_prefix_detection` would make the hostname resolution change.\n\t\t\tif ec2.IsWindowsDefaultHostname(hostName) {\n\t\t\t\t// As we are in the else clause `ec2.IsDefaultHostname(hostName)` is false. If `ec2.IsWindowsDefaultHostname(hostName)`\n\t\t\t\t// is `true` that means `ec2_use_windows_prefix_detection` is set to false.\n\t\t\t\tec2Hostname, err := getValidEC2Hostname(getEC2Hostname)\n\n\t\t\t\t// Check if we get a valid hostname when enabling `ec2_use_windows_prefix_detection` and the hostnames are different.\n\t\t\t\tif err == nil && ec2Hostname != hostName {\n\t\t\t\t\t// REMOVEME: This should be removed if/when the default `ec2_use_windows_prefix_detection` is set to true\n\t\t\t\t\tlog.Infof(\"The agent resolved your hostname as '%s'. You may want to use the EC2 instance-id ('%s') for the in-app hostname.\"+\n\t\t\t\t\t\t\" For more information: https://docs.datadoghq.com/ec2-use-win-prefix-detection\", hostName, ec2Hostname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\th, err := os.Hostname()\n\tif err == nil && !config.Datadog.GetBool(\"hostname_fqdn\") && fqdn != \"\" && hostName == h && h != fqdn {\n\t\tif runtime.GOOS != \"windows\" {\n\t\t\t// REMOVEME: This should be removed when the default `hostname_fqdn` is set to true\n\t\t\tlog.Warnf(\"DEPRECATION NOTICE: The agent resolved your hostname as '%s'. However in a future version, it will be resolved as '%s' by default. To enable the future behavior, please enable the `hostname_fqdn` flag in the configuration. For more information: https://dtdg.co/flag-hostname-fqdn\", h, fqdn)\n\t\t} else { // OS is Windows\n\t\t\tlog.Warnf(\"The agent resolved your hostname as '%s', and will be reported this way to maintain compatibility with version 5. To enable reporting as '%s', please enable the `hostname_fqdn` flag in the configuration. For more information: https://dtdg.co/flag-hostname-fqdn\", h, fqdn)\n\t\t}\n\t}\n\n\t// If at this point we don't have a name, bail out\n\tif hostName == \"\" {\n\t\terr = fmt.Errorf(\"unable to reliably determine the host name. You can define one in the agent config file or in your hosts file\")\n\t} else {\n\t\t// we got a hostname, residual errors are irrelevant now\n\t\terr = nil\n\t}\n\n\thostnameData := saveHostnameData(cacheHostnameKey, hostName, provider)\n\tif err != nil {\n\t\texpErr := new(expvar.String)\n\t\texpErr.Set(fmt.Sprintf(err.Error()))\n\t\thostnameErrors.Set(\"all\", expErr)\n\t}\n\treturn hostnameData, err\n}", "func GetHostname(addr string) string {\n\treturn strings.Split(addr, \":\")[0]\n}", "func (c *Container) Hostname() string {\n\treturn c.hostname\n}", "func (o LookupInstanceResultOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupInstanceResult) string { return v.Hostname }).(pulumi.StringOutput)\n}", "func hostnameHandler(w http.ResponseWriter, r *http.Request) {\n\th, err := os.Hostname()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"unable to get hostname: %s\", err)\n\t}\n\tfmt.Fprintf(w, \"You are querying host %s\\n\", h)\n}", "func (n *Namespace) GetHostName(cmd *exec.Cmd) {\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCloneflags: syscall.CLONE_NEWUTS,\n\t}\n}", "func (o *V1VirusDatasetRequest) GetHost() string {\n\tif o == nil || o.Host == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Host\n}", "func GetHostName(r *http.Request) string {\n\thost := r.Header.Get(\"X-Forwarded-Host\")\n\tif host != \"\" {\n\t\treturn host\n\t}\n\treturn r.Host\n}", "func (o WorkerDomainOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerDomain) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (o CustomDomainScmOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainScm) string { return v.HostName }).(pulumi.StringOutput)\n}", "func getHostname(c *gin.Context) {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.IndentedJSON(http.StatusOK, gin.H{\"hostname\": name})\n}", "func (o NodeBalancerOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NodeBalancer) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (m MetaData) GetHost() string {\n\tif len(m) == 0 {\n\t\treturn \"\"\n\t}\n\tfor _, k := range []string{\"x-forwarded-host\", \"host\"} {\n\t\tif v := m[k]; v != \"\" {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"\"\n}", "func (c *Context) Host() string {\n\treturn string(c.RequestCtx.Host())\n}", "func (m *SiteCollection) SetHostname(value *string)() {\n m.hostname = value\n}", "func GetHostname() (string, error) {\n\thostname, err := os.Hostname()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.ToLower(hostname), nil\n}", "func (km KeyValueMap) Hostname() string {\n\treturn km[kmHostname]\n}", "func Host() string {\n\treturn host\n}", "func GetHost() string {\n\treturn Config().Hostname\n}", "func (n Node) Hostname() string {\n\tparts := strings.Split(n.Name, \"@\")\n\tif len(parts) >= 2 {\n\t\treturn parts[1]\n\t}\n\treturn \"\"\n}", "func (o EciScalingConfigurationOutput) HostName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringPtrOutput { return v.HostName }).(pulumi.StringPtrOutput)\n}", "func GetHostname(hostname string) (string, error) {\n\tif hostname != \"\" {\n\t\treturn hostname, nil\n\t}\n\treturn os.Hostname()\n}", "func (v *Client) Host() string {\n\tif v.host == \"\" {\n\t\tv.host = v.req.Host\n\t}\n\treturn v.host\n}", "func (o GetServiceHostnameConfigurationProxyOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceHostnameConfigurationProxy) string { return v.HostName }).(pulumi.StringOutput)\n}", "func GetHostname(hostnameOverride string) string {\n\thostname := hostnameOverride\n\tif hostname == \"\" {\n\t\tnodename, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"couldn't determine hostname: %v\", err)\n\t\t}\n\t\thostname = nodename\n\t}\n\treturn strings.ToLower(strings.TrimSpace(hostname))\n}", "func (b *Backend) Hostname() string {\n\treturn b.hostaddress\n}", "func GetHostname(host ...string) string {\n\tif len(host) > 0 && strings.TrimSpace(host[0]) != \"\" {\n\t\tif h, ok := hostHostList[host[0]]; ok {\n\t\t\treturn h\n\t\t}\n\t\tstr := GetCmdStr(\"host %s\", host[0])\n\t\th := \"\"\n\t\tif strings.Contains(str, \"has address\") {\n\t\t\th = GetCmdStr(\"host %s|awk '{print $1}'\", host[0])\n\t\t\thostHostList[host[0]] = h\n\t\t} else if strings.Contains(str, \"domain name pointer\") {\n\t\t\th = strings.TrimSuffix(GetCmdStr(\"host %s|awk '{print $5}'\", host[0]), \".\")\n\t\t\thostHostList[host[0]] = h\n\t\t}\n\t\treturn h\n\t}\n\tif chostname == \"\" {\n\t\th, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tchostname = GetCmdStr(\"hostname\")\n\t\t} else {\n\t\t\tchostname = h\n\t\t}\n\t}\n\treturn chostname\n}", "func (o ServiceHostnameConfigurationProxyOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationProxy) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o GetServiceHostnameConfigurationPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceHostnameConfigurationPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func SetHostname(h string) {\n\thostname = h\n}", "func (c *tomlConfig) Host() string {\n\tparts := strings.Split(c.Server.HTTPAddress, \":\")\n\thost := c.Server.Host\n\tif len(parts) > 1 {\n\t\thost = host + \":\" + parts[len(parts)-1]\n\t}\n\treturn host\n}", "func HostName() (hostName string) {\n\tif hostName, _ = os.Hostname(); len(hostName) == 0 {\n\t\thostName = \"localhost\"\n\t}\n\treturn\n}", "func (c *Config) GetHostname() string {\n\thostname := c.GlobalConfig.Hostname\n\tif hostname != \"\" {\n\t\treturn hostname\n\t}\n\n\tvar err error\n\thostname, err = os.Hostname()\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn hostname\n}", "func (o *SmartstackBackend) GetHostnameOk() (*string, bool) {\n\tif o == nil || o.Hostname == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Hostname, true\n}", "func (o InstanceFromTemplateOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (o GetServiceHostnameConfigurationDeveloperPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceHostnameConfigurationDeveloperPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func Host(hostname string) (string, error) {\n\tif hostname == \"\" {\n\t\treturn \"\", trace.BadParameter(\"missing parameter hostname\")\n\t}\n\t// if this is IPv4 or V6, return as is\n\tif ip := net.ParseIP(hostname); len(ip) != 0 {\n\t\treturn hostname, nil\n\t}\n\t// has no indication of port, return, note that\n\t// it will not break ipv6 as it always has at least one colon\n\tif !strings.Contains(hostname, \":\") {\n\t\treturn hostname, nil\n\t}\n\thost, _, err := SplitHostPort(hostname)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\treturn host, nil\n}", "func (o HTTPHealthCheckResponseOutput) Host() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HTTPHealthCheckResponse) string { return v.Host }).(pulumi.StringOutput)\n}", "func HostAddr() string {\n\treturn server.addr\n}", "func (m *Machine) Host() string {\n\treturn m.host\n}", "func getEndpointHostName(ep string, exec executor.Executor) (string, error) {\n\tres, err := exec.Exec(\"wget\", \"-O-\", \"-q\", fmt.Sprintf(\"http://%s/hostname\", ep))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func getEndpointHostName(ep string, exec executor.Executor) (string, error) {\n\tres, err := exec.Exec(\"wget\", \"-O-\", \"-q\", fmt.Sprintf(\"http://%s/hostname\", ep))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func (o HTTPSHealthCheckResponseOutput) Host() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HTTPSHealthCheckResponse) string { return v.Host }).(pulumi.StringOutput)\n}", "func (o ServiceHostnameConfigurationPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o ServiceHostnameConfigurationDeveloperPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceHostnameConfigurationDeveloperPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func hostname(hostport string) (string, error) {\n\thost, _, err := net.SplitHostPort(hostport)\n\treturn host, err\n}", "func (o CustomDomainDeveloperPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainDeveloperPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o CustomDomainPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (c *PAPIClient) Hostname(hostID, contractID, groupID string) (HostnameSummary, error) {\n\thostnames := &Hostnames{}\n\terr := resourceRequest(c, \"GET\", papiHostnameEndpoint(c.GetCredentials(), hostID, contractID, groupID), nil, hostnames)\n\tif err != nil {\n\t\treturn HostnameSummary{}, err\n\t}\n\treturn hostnames.Hostnames.Items[0], err\n}", "func (o CustomDomainGatewayOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainGateway) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o *NodeUpdate) GetHostnameOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Hostname, true\n}", "func (o EcsLaunchTemplateOutput) HostName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringPtrOutput { return v.HostName }).(pulumi.StringPtrOutput)\n}", "func (d *Demo) ServerName() string {\n\treturn d.header.GetServerName()\n}", "func (c *Config) Host() string {\n\thost, err := os.Hostname()\n\tif nil == err {\n\t\treturn c.Get(\"host\", host)\n\t}\n\treturn c.Get(\"host\", \"localhost\")\n}", "func (d *DHCPv4) HostName() string {\n\treturn GetString(OptionHostName, d.Options)\n}", "func (o *NSQProducer) SetHostname(v string) {\n\to.Hostname = &v\n}", "func GetHostname(hostnameOverride string) (string, error) {\n\thostName := hostnameOverride\n\tif len(hostName) == 0 {\n\t\tnodeName, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't determine hostname: %v\", err)\n\t\t}\n\t\thostName = nodeName\n\t}\n\n\t// Trim whitespaces first to avoid getting an empty hostname\n\t// For linux, the hostname is read from file /proc/sys/kernel/hostname directly\n\thostName = strings.TrimSpace(hostName)\n\tif len(hostName) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty hostname is invalid\")\n\t}\n\treturn strings.ToLower(hostName), nil\n}", "func (node *Node) Host() string {\n\treturn node.IP().String() + fmt.Sprintf(\":%d\", node.Port())\n}", "func (c *Config) HostName() string {\n\tswitch c.Protocol {\n\tcase HTTP:\n\t\treturn \"http host\"\n\tcase HTTPS:\n\t\treturn \"https host\"\n\tcase Socks:\n\t\treturn \"socks host\"\n\t}\n\treturn \"\"\n}", "func (o *NodeUpdate) SetHostname(v string) {\n\to.Hostname = v\n}", "func GetHostname(hostnameOverride string) (string, error) {\n\thostName := hostnameOverride\n\tif len(hostName) == 0 {\n\t\tnodeName, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't determine hostname: %w\", err)\n\t\t}\n\t\thostName = nodeName\n\t}\n\n\t// Trim whitespaces first to avoid getting an empty hostname\n\t// For linux, the hostname is read from file /proc/sys/kernel/hostname directly\n\thostName = strings.TrimSpace(hostName)\n\tif len(hostName) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty hostname is invalid\")\n\t}\n\n\treturn strings.ToLower(hostName), nil\n}", "func (c *service) Host() string {\n\treturn c.host\n}" ]
[ "0.75538117", "0.7466091", "0.74589264", "0.73750436", "0.7302828", "0.72553", "0.7239988", "0.72094566", "0.7176512", "0.7165193", "0.71639174", "0.7122988", "0.7088989", "0.70687085", "0.705074", "0.7002528", "0.69893676", "0.69723624", "0.69542754", "0.6947687", "0.6921452", "0.6913334", "0.6901898", "0.68853474", "0.68539345", "0.68306416", "0.6792704", "0.678427", "0.67735404", "0.6768047", "0.67612636", "0.67371184", "0.6725386", "0.67054385", "0.6697212", "0.66880983", "0.6686065", "0.66841155", "0.66575056", "0.66402185", "0.6631754", "0.66157204", "0.6613321", "0.66093767", "0.65847504", "0.65829533", "0.6582883", "0.656895", "0.6536599", "0.653069", "0.6520222", "0.6503353", "0.64983463", "0.6431831", "0.64317346", "0.6430532", "0.64210045", "0.6419568", "0.64155966", "0.64137304", "0.6408784", "0.6407772", "0.63947", "0.6393884", "0.63866794", "0.6386441", "0.6372463", "0.63689506", "0.63633984", "0.63601565", "0.6337768", "0.63369024", "0.6333254", "0.63214624", "0.6318175", "0.6317087", "0.6306788", "0.63033736", "0.62999636", "0.62999636", "0.6295758", "0.6292545", "0.62763447", "0.62590957", "0.62530464", "0.6237033", "0.6232597", "0.6216243", "0.6215441", "0.62028325", "0.6198337", "0.6194062", "0.61939013", "0.6190408", "0.61777717", "0.61767054", "0.61762154", "0.61754656", "0.6171873", "0.61494875" ]
0.7228013
7
InstanceID returns the ID of the server that did the request to the Metadata server.
func (c *Client) InstanceID() (int, error) { resp, err := c.get("/instance-id") if err != nil { return 0, err } return strconv.Atoi(resp) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func instanceID() string {\n\ttimeout := time.Duration(5 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\tr, err := client.Get(metadataURL)\n\tif err != nil {\n\t\tlog.Warnf(fmt.Sprint(\"error requesting metadata. \", err.Error()))\n\t\treturn \"\"\n\t}\n\tdefer r.Body.Close()\n\n\tvar metadata = new(metaDataID)\n\terr = json.NewDecoder(r.Body).Decode(metadata)\n\tif err != nil {\n\t\tlog.Warnf(fmt.Sprint(\"error parsing metadata. \", err.Error()))\n\t\treturn \"\"\n\t}\n\n\treturn metadata.UUID\n}", "func (s *Server) InstanceID() string {\n\treturn s.serverInstanceID\n}", "func (s *Server) InstanceID() string {\n\treturn s.serverInstanceID\n}", "func (m *metadata) GetInstanceID() string {\n\treturn m.instanceID\n}", "func InstanceID() string {\n\treturn instanceID\n}", "func (c *Client) GetInstanceID() (string, error) {\n\tresp, err := c.httpClient.Get(instanceMetadataBaseURL + \"/hetzner/v1/metadata/instance-id\")\n\tif err != nil {\n\t\tvar neterr net.Error\n\t\tif errors.As(err, &neterr) && (neterr.Timeout() || neterr.Temporary()) {\n\t\t\treturn \"\", &errorx.RetryableError{Message: \"timeout or temporary error in HTTP request\", Err: neterr}\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"error in http request: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"unexpected status code %d != 200\", resp.StatusCode)\n\t\tif resp.StatusCode >= 500 && resp.StatusCode < 600 {\n\t\t\treturn \"\", &errorx.RetryableError{Message: \"retryable HTTP error\", Err: err}\n\t\t}\n\t\treturn \"\", err\n\t}\n\tinstanceIDB, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error reading response body: %w\", err)\n\t}\n\treturn string(instanceIDB), nil\n}", "func (a *Adapter) InstanceID() string {\n\treturn a.manifest.instance.id\n}", "func (m *Info) GetInstanceID() string {\n\treturn m.ec2Metadata.getInstanceID()\n}", "func (d *driver) InstanceID(\n\tctx types.Context,\n\topts types.Store) (*types.InstanceID, error) {\n\treturn utils.InstanceID(ctx)\n}", "func GetInstanceId() string {\n\tcmd := \"curl\"\n\tcmdArgs := []string{\"-s\", \"http://169.254.169.254/latest/meta-data/instance-id\"}\n\tout, err := exec.Command(cmd, cmdArgs...).Output()\n\tif err != nil {\n\t\tlog.Printf(\"Instance Id err is %s\\n\", err)\n\t\treturn \"\"\n\t}\n\tlog.Printf(\"The instance id is %s\\n\", out)\n\treturn string(out)\n}", "func GetInstanceId() string {\n\tcmd := \"curl\"\n\tcmdArgs := []string{\"-s\", \"http://169.254.169.254/latest/meta-data/instance-id\"}\n\tout, err := exec.Command(cmd, cmdArgs...).Output()\n\tif err != nil {\n\t\tlog.Printf(\"Instance Id err is %s\\n\", err)\n\t\treturn \"\"\n\t}\n\tlog.Printf(\"The instance id is %s\\n\", out)\n\treturn string(out)\n}", "func (client *AWSClient) GetInstanceID() (string, error) {\n\tif client.svcEC2Metadata.Available() {\n\t\ti, err := client.svcEC2Metadata.GetInstanceIdentityDocument()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn i.InstanceID, nil\n\t}\n\treturn \"\", errors.New(\"program is not running with EC2 Instance or metadata service is not available\")\n}", "func GetInstanceID() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\n\tinstanceID, err := getMetadataItemWithMaxLength(\"/instance-id\", config.Datadog.GetInt(\"metadata_endpoints_max_hostname_size\"))\n\tif err != nil {\n\t\tif instanceID, found := cache.Cache.Get(instanceIDCacheKey); found {\n\t\t\tlog.Debugf(\"Unable to get ec2 instanceID from aws metadata, returning cached instanceID '%s': %s\", instanceID, err)\n\t\t\treturn instanceID.(string), nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tcache.Cache.Set(instanceIDCacheKey, instanceID, cache.NoExpiration)\n\n\treturn instanceID, nil\n}", "func (s *scope) InstanceID() string {\n\treturn s.instance.InstanceID\n}", "func (i *instances) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tdroplet, err := dropletByName(ctx, i.resources.gclient, nodeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(droplet.ID), nil\n}", "func (m *Machine) InstanceId() (instance.Id, error) {\n\tvar results params.StringResults\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: m.tag.String()}},\n\t}\n\terr := m.st.call(\"InstanceId\", args, &results)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(results.Results) != 1 {\n\t\treturn \"\", fmt.Errorf(\"expected 1 result, got %d\", len(results.Results))\n\t}\n\tresult := results.Results[0]\n\tif result.Error != nil {\n\t\treturn \"\", result.Error\n\t}\n\treturn instance.Id(result.Result), nil\n}", "func (o EnterpriseProxyAccessOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EnterpriseProxyAccess) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (did *SPDeviceInformationData) InstanceID() (string, error) {\n\trequiredSize := uint32(0)\n\terr := setupDiGetDeviceInstanceId(w32.HANDLE(did.devInfo), &did.spDeviceInformationData, nil, 0, &requiredSize)\n\n\tbuff := make([]uint16, requiredSize)\n\terr = setupDiGetDeviceInstanceId(w32.HANDLE(did.devInfo), &did.spDeviceInformationData, unsafe.Pointer(&buff[0]), uint32(len(buff)), &requiredSize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn windows.UTF16ToString(buff[:]), err\n}", "func (m *WorkflowCreateRequest) GetInstanceID() string {\n\tif m != nil {\n\t\treturn m.InstanceID\n\t}\n\treturn \"\"\n}", "func (i *instances) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tvm, err := i.discoverNodeByName(ctx, nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error trying to find VM: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif vm == nil {\n\t\tklog.V(4).Info(\"instances.InstanceID() InstanceNotFound \", nodeName)\n\t\treturn \"\", cloudprovider.InstanceNotFound\n\t}\n\n\tif vm.Status.BiosUUID == \"\" {\n\t\treturn \"\", errBiosUUIDEmpty\n\t}\n\n\tklog.V(4).Infof(\"instances.InstanceID() called to get vm: %v uuid: %v\", nodeName, vm.Status.BiosUUID)\n\treturn vm.Status.BiosUUID, nil\n}", "func (i *Instances) InstanceID(name string) (string, error) {\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Create vSphere client\n\tc, err := vsphereLogin(i.cfg, ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer c.Logout(ctx)\n\n\tvm, err := getVirtualMachineByName(i.cfg, ctx, c, name)\n\n\tvar mvm mo.VirtualMachine\n\terr = getVirtualMachineManagedObjectReference(ctx, c, vm, \"summary\", &mvm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif mvm.Summary.Runtime.PowerState == ActivePowerState {\n\t\treturn \"/\" + vm.InventoryPath, nil\n\t}\n\n\tif mvm.Summary.Config.Template == false {\n\t\tglog.Warning(\"VM %s, is not in %s state\", name, ActivePowerState)\n\t} else {\n\t\tglog.Warning(\"VM %s, is a template\", name)\n\t}\n\n\treturn \"\", cloudprovider.InstanceNotFound\n}", "func (s *singleton) GetInstanceId() int64 {\n\treturn s.id\n}", "func (o ConnectionCloudSqlOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ConnectionCloudSql) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func GetInstanceID(svc *ec2metadata.EC2Metadata) (string, error) {\n\tdoc, err := svc.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn doc.InstanceID, nil\n}", "func (o BandwidthPackageAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BandwidthPackageAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o DomainAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DomainAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o SnapshotOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Snapshot) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (h *httpCloud) ExternalID(instance string) (string, error) {\n\treturn instance, nil\n}", "func (o GetChartNamespacesNamespaceOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChartNamespacesNamespace) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func GetInstanceID() (string, error) {\n\tvalue := os.Getenv(\"AWS_INSTANCE_ID\")\n\tif len(value) > 0 {\n\t\treturn value, nil\n\t}\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", \"http://169.254.169.254/latest/meta-data/instance-id\", nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}", "func (o AlidnsDomainAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AlidnsDomainAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func instanceID(resourceSpec *runtime.RawExtension) (string, error) {\n\tif resourceSpec == nil {\n\t\treturn \"\", nil\n\t}\n\n\tspec := partialSpec{}\n\terr := json.Unmarshal(resourceSpec.Raw, &spec)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"unmarshalling StateResource spec failed\")\n\t}\n\n\treturn spec.InstanceID, nil\n}", "func (o AssociationOutput) InstanceId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Association) pulumi.StringPtrOutput { return v.InstanceId }).(pulumi.StringPtrOutput)\n}", "func GetAppInstanceId(r *http.Request) string {\n\tquery, _ := GetHTTPTags(r)\n\treturn query.Get(AppInstanceIdStr)\n}", "func (o GetChainsChainOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o ConnectionCloudSqlPtrOutput) InstanceId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConnectionCloudSql) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.InstanceId\n\t}).(pulumi.StringPtrOutput)\n}", "func (inst Instance) ID() int {\n\treturn inst.id\n}", "func (i *Instance) ID() string {\n\treturn i.InstanceID\n}", "func (o RouteOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Route) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o EndpointAclPolicyOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EndpointAclPolicy) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetRegistryEnterpriseNamespacesResultOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRegistryEnterpriseNamespacesResult) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o BgpIpOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BgpIp) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (s *Server) ID() string {\n\treturn s.Config().GetUuid()\n}", "func (o InstanceAttachmentOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceAttachment) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (i *Instance) ID() string {\n\treturn i.MachineID\n}", "func (aws *awsCloudProvider) GetInstanceID(node *apiv1.Node) string {\n\treturn node.Spec.ProviderID\n}", "func (dc *Client) GetRuntimeID(accountID, instanceID string) (string, error) {\n\tquery := dc.queryProvider.RuntimeForInstanceId(instanceID)\n\treq := machineGraph.NewRequest(query)\n\treq.Header.Add(accountIDKey, accountID)\n\n\tdc.log.Info(\"Send request to director\")\n\tresponse, err := dc.getRuntimeIdFromDirector(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdc.log.Info(\"Extract the RuntimeID from the response\")\n\treturn dc.getIDFromRuntime(&response.Result)\n}", "func (s *ServiceInstance) getID() serviceInstanceID {\n\treturn serviceInstanceID{\n\t\taddress: s.Address.String(),\n\t\tname: serviceInstanceName(s.InstanceName),\n\t}\n}", "func (o UserOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *User) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o GetEndpointAclPoliciesPolicyOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointAclPoliciesPolicy) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (o InstanceFromTemplateOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) pulumi.StringOutput { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (s *Server) ID() uint32 {\n\treturn s.id\n}", "func vmInstanceMetadata(c *http.Client) (region string, resourceID string, err error) {\n\treq, err := http.NewRequest(\"GET\", vmInstanceMetadataURL, nil)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"error creating request: %w\", err)\n\t}\n\treq.Header.Set(\"Metadata\", \"true\")\n\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tif resp.StatusCode >= 300 || resp.StatusCode < 200 {\n\t\treturn \"\", \"\", fmt.Errorf(\"unable to fetch instance metadata: [%s] %d\",\n\t\t\tvmInstanceMetadataURL, resp.StatusCode)\n\t}\n\n\tvar metadata virtualMachineMetadata\n\tif err := json.Unmarshal(body, &metadata); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tregion = metadata.Compute.Location\n\tresourceID = metadata.ResourceID()\n\n\treturn region, resourceID, nil\n}", "func (s *Server) GetInstance() *http.Server { return s.instance }", "func (s *Server) Id() string {\n\treturn s.ID()\n}", "func (o GetChartRepositoriesRepositoryOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChartRepositoriesRepository) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (s *ServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (i *instance) appID() string {\n\treturn i.opts.appID()\n}", "func (c *Config) InstanceKey(agentKey string) (string, error) {\n\turl, err := url.Parse(string(c.ConnectionString))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse connection string URL: %w\", err)\n\t}\n\n\treturn url.Host, nil\n}", "func (p *Provider) SessionID() string {\n\tp.sessionLock.RLock()\n\tdefer p.sessionLock.RUnlock()\n\treturn p.sessionID\n}", "func (s *InternalServerError) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (o GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpcOutput) InstanceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointLinkedVpcsVpcEndpointLinkedVpc) string { return v.InstanceId }).(pulumi.StringOutput)\n}", "func (d *DHCPv4) ServerIdentifier() net.IP {\n\treturn GetIP(OptionServerIdentifier, d.Options)\n}", "func (ev binlogEvent) ServerID() uint32 {\n\treturn binary.LittleEndian.Uint32(ev.Bytes()[5 : 5+4])\n}", "func (os *OpenStack) GetInstanceByID(instanceID string) (*servers.Server, error) {\n\tserver, err := servers.Get(os.compute, instanceID).Extract()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn server, nil\n}", "func GetLocalEc2InstanceID() (string, error) {\n\treturn getEc2Metadata(ec2InstanceIDURL)\n}", "func (nc *NetClient) SessionID() string {\n\treturn nc.Session.ID\n}", "func (image *image) SessionID() int32 {\n\treturn image.sessionID\n}", "func (fmd *FakeMysqlDaemon) GetServerID(ctx context.Context) (uint32, error) {\n\treturn 1, nil\n}", "func (s *Service) InstanceKey() string {\n\treturn s.InstanceName.String()\n}", "func (i *Info) Instance(r *http.Request) (*sessions.Session, error) {\n\treturn i.store.Get(r, i.Name)\n}", "func serverID(td spiffeid.TrustDomain) *spiretypes.SPIFFEID {\n\treturn &spiretypes.SPIFFEID{\n\t\tTrustDomain: td.String(),\n\t\tPath: idutil.ServerIDPath,\n\t}\n}", "func queryInstanceMetadata() (*instanceMetadata, error) {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", \"http://169.254.169.254/metadata/instance\", nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating a new request: %s\", err)\n\t}\n\treq.Header.Add(\"Metadata\", \"True\")\n\n\tq := req.URL.Query()\n\tq.Add(\"format\", \"json\")\n\tq.Add(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = q.Encode()\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error sending request to the metadata server: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading a response from the metadata server: %s\", err)\n\t}\n\tmetadata, err := unmarshalInstanceMetadata(body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshalling metadata: %s\", err)\n\t}\n\treturn metadata, nil\n}", "func (o InstanceOutput) ImageId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.ImageId }).(pulumi.StringOutput)\n}", "func NewInstanceID() string {\n\tg := uuid.Must(uuid.NewV4())\n\tp := strings.Split(g.String(), \"-\")\n\treturn p[len(p)-1]\n}", "func (s *ClusterContainsContainerInstancesException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (s *InternalServerException) RequestID() string {\n\treturn s.RespMetadata.RequestID\n}", "func (inst *Instance) ID() string {\n\tif inst == nil || inst.inst == nil {\n\t\treturn \"\"\n\t}\n\treturn inst.inst.ID()\n}", "func (o *CloudVolumeInstanceAttachment) GetInstanceId() string {\n\tif o == nil || o.InstanceId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.InstanceId\n}", "func (o *DnsViewparamDataData) GetServerId() string {\n\tif o == nil || o.ServerId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ServerId\n}", "func (f *FFS) ID(ctx context.Context) (ffs.APIID, error) {\n\tresp, err := f.client.ID(ctx, &rpc.IDRequest{})\n\tif err != nil {\n\t\treturn ffs.EmptyInstanceID, err\n\t}\n\treturn ffs.APIID(resp.Id), nil\n}" ]
[ "0.7940388", "0.7496837", "0.7496837", "0.7470635", "0.7221164", "0.71790284", "0.7150159", "0.7012753", "0.69377714", "0.67950314", "0.67950314", "0.67815906", "0.6730924", "0.6730696", "0.6707766", "0.6682073", "0.6582132", "0.65752953", "0.6568842", "0.6531832", "0.6528647", "0.65147275", "0.6513188", "0.6340057", "0.6313043", "0.6304698", "0.6304698", "0.6304698", "0.6286741", "0.6279478", "0.62485176", "0.62395614", "0.6226314", "0.6190491", "0.61848754", "0.6179562", "0.6170094", "0.6154185", "0.61534685", "0.6151008", "0.6109003", "0.60939735", "0.60747355", "0.60648966", "0.605949", "0.60451895", "0.6008928", "0.59882176", "0.59849405", "0.5912695", "0.58998895", "0.58902085", "0.5843089", "0.5830754", "0.5829921", "0.58185047", "0.5811048", "0.5805633", "0.58001524", "0.5798002", "0.57820576", "0.5731824", "0.57135975", "0.57067645", "0.57063997", "0.56963736", "0.5664463", "0.5658774", "0.5652461", "0.5645607", "0.56290674", "0.5611298", "0.5603587", "0.55705553", "0.55643326", "0.5561705", "0.5543864", "0.55347085", "0.5519215", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54959095", "0.54950565", "0.5493717", "0.5476937", "0.54731065", "0.5471452" ]
0.7444569
4
PublicIPv4 returns the Public IPv4 of the server that did the request to the Metadata server.
func (c *Client) PublicIPv4() (net.IP, error) { resp, err := c.get("/public-ipv4") if err != nil { return nil, err } return net.ParseIP(resp), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PublicIpv4(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldPublicIpv4), v))\n\t})\n}", "func PublicAddr() string {\n\tif devel() {\n\t\treturn defaultIP\n\t}\n\taddr, err := awsPublicIPv4()\n\tif err != nil {\n\t\talt.Warnf(\"env: Could not fetch instance public IPv4 from environment: %v\", err)\n\t\taddr = defaultIP // punt\n\t}\n\treturn addr\n}", "func (opdns OpenDNSProvider) GetIPv4() (string, error) {\n\t// Lookup OpenDNS IPv4 Addr\n\topdnsRes, err := opdns.doQuery(dns.Fqdn(opendnsResolver), dns.TypeA, opendnsResolver+\":53\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\topdnsRecord, ok := opdnsRes.Answer[0].(*dns.A)\n\tif !ok {\n\t\treturn \"\", errors.New(\"OpenDNS failed to return a valid IPv4 address for itself\")\n\t}\n\n\t// Query OpenDNS for clients public ip\n\tres, err := opdns.doQuery(opendnsMyIP, dns.TypeA, opdnsRecord.A.String()+\":53\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trecord, ok := res.Answer[0].(*dns.A)\n\tif !ok {\n\t\treturn \"\", errors.New(\"OpenDNS failed to return a valid A record\")\n\t}\n\n\treturn record.A.String(), nil\n}", "func (internet Internet) IPv4(v reflect.Value) (interface{}, error) {\n\treturn internet.ipv4(), nil\n}", "func (c *Client) GetIPv4() string {\n\treturn c.ip.String()\n}", "func ParsePublicIPV4(ip string) (*l5dNetPb.IPAddress, error) {\n\tnetIP := net.ParseIP(ip)\n\tif netIP != nil {\n\t\toBigInt := IPToInt(netIP.To4())\n\t\tnetIPAddress := &l5dNetPb.IPAddress{\n\t\t\tIp: &l5dNetPb.IPAddress_Ipv4{\n\t\t\t\tIpv4: uint32(oBigInt.Uint64()),\n\t\t\t},\n\t\t}\n\t\treturn netIPAddress, nil\n\t}\n\treturn nil, fmt.Errorf(\"Invalid IP address: %s\", ip)\n}", "func IPv4() (string, error) {\n\tconn, err := net.Dial(\"udp\", \"8.8.8.8:80\")\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Failed to determine your IP\")\n\t}\n\tlocalAddr := conn.LocalAddr().(*net.UDPAddr)\n\tmyIP := localAddr.IP.String()\n\tconn.Close()\n\treturn myIP, nil\n}", "func PublicIpv4Contains(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldPublicIpv4), v))\n\t})\n}", "func PublicIpv4EQ(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (o GetLoadBalancersBalancerZoneMappingOutput) PublicIpv4Address() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLoadBalancersBalancerZoneMapping) string { return v.PublicIpv4Address }).(pulumi.StringOutput)\n}", "func PublicIpv4GTE(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (i Internet) Ipv4() string {\n\tips := make([]string, 0, 4)\n\n\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(1, 255)))\n\tfor j := 0; j < 3; j++ {\n\t\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(0, 255)))\n\t}\n\n\treturn strings.Join(ips, \".\")\n}", "func getLocalIPV4() string {\n\taddrList, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tlogrus.Panicf(\"net.InterfaceAddrs error : %v\", err)\n\t}\n\n\tfor _, addr := range addrList {\n\t\tif ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {\n\t\t\tif ip.IP.To4() == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn ip.IP.String()\n\t\t}\n\t}\n\treturn \"127.0.0.1\"\n}", "func (h *Hub) PublicIPAddress() (result string, err error) {\n\treturn h.client.sendXPathRequest(mySagemcomBoxDeviceInfoPublicIpv4)\n}", "func GetLocalIPv4() ([]string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn nil, fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\tip, err := getMetadataItem(\"/local-ipv4\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []string{ip}, nil\n}", "func (i Internet) LocalIpv4() string {\n\tips := make([]string, 0, 4)\n\tips = append(ips, i.Faker.RandomStringElement([]string{\"10\", \"172\", \"192\"}))\n\n\tif ips[0] == \"10\" {\n\t\tfor j := 0; j < 3; j++ {\n\t\t\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(0, 255)))\n\t\t}\n\t}\n\n\tif ips[0] == \"172\" {\n\t\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(16, 31)))\n\n\t\tfor j := 0; j < 2; j++ {\n\t\t\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(0, 255)))\n\t\t}\n\t}\n\n\tif ips[0] == \"192\" {\n\t\tips = append(ips, \"168\")\n\n\t\tfor j := 0; j < 2; j++ {\n\t\t\tips = append(ips, strconv.Itoa(i.Faker.IntBetween(0, 255)))\n\t\t}\n\t}\n\n\treturn strings.Join(ips, \".\")\n}", "func (o LoadBalancerZoneMappingOutput) PublicIpv4Address() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LoadBalancerZoneMapping) *string { return v.PublicIpv4Address }).(pulumi.StringPtrOutput)\n}", "func (o NodeBalancerOutput) Ipv4() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NodeBalancer) pulumi.StringOutput { return v.Ipv4 }).(pulumi.StringOutput)\n}", "func IPv4(name string) (string, error) {\n\ti, err := net.InterfaceByName(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taddrs, err := i.Addrs()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, a := range addrs {\n\t\tif ipn, ok := a.(*net.IPNet); ok {\n\t\t\tif ipn.IP.To4() != nil {\n\t\t\t\treturn ipn.IP.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"no IPv4 found for interface: %q\", name)\n}", "func PublicIpv4HasPrefix(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (ep *epInfoCache) IPv4Address() netip.Addr {\n\treturn ep.ipv4\n}", "func IPv4(opts ...options.OptionFunc) string {\n\treturn singleFakeData(IPV4Tag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\treturn i.ipv4()\n\t}, opts...).(string)\n}", "func GetIPv4(client *godo.Client, ctx context.Context, name string) (string, error) {\n\tdroplets, err := rawListDroplets(client, ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, droplet := range droplets {\n\t\tif droplet.Name == name {\n\t\t\tip, err := droplet.PublicIPv4()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"droplet does not exist with that name\")\n}", "func IPv4(a, b, c, d uint8) IP {\n\treturn IP{\n\t\tlo: 0xffff00000000 | uint64(a)<<24 | uint64(b)<<16 | uint64(c)<<8 | uint64(d),\n\t\tz: z4,\n\t}\n}", "func (h *Host) GetPublicIP() string {\n\thostNetworkV1 := propsv1.NewHostNetwork()\n\terr := h.Properties.Get(HostProperty.NetworkV1, hostNetworkV1)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tip := hostNetworkV1.PublicIPv4\n\tif ip == \"\" {\n\t\tip = hostNetworkV1.PublicIPv6\n\t}\n\treturn ip\n}", "func PublicIpv4LT(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldPublicIpv4), v))\n\t})\n}", "func privateIPv4() (net.IP, error) {\n\tas, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, a := range as {\n\t\tipnet, ok := a.(*net.IPNet)\n\t\tif !ok || ipnet.IP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\n\t\tip := ipnet.IP.To4()\n\t\tif isPrivateIPv4(ip) {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\n\t//change: use \"POD_IP\"\n\tip := net.ParseIP(os.Getenv(\"POD_IP\"))\n\tif ip == nil {\n\t\treturn nil, errors.New(\"no private ip address\")\n\t}\n\tif ipV4 := ip.To4(); ipV4 != nil {\n\t\treturn ipV4, nil\n\t}\n\treturn nil, errors.New(\"no pod ipv4 address\")\n}", "func Ipv4(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldIpv4), v))\n\t})\n}", "func (internet *Internet) IPv4Address() string {\n\tvar parts []string\n\tfor i := 0; i < 4; i++ {\n\t\tparts = append(parts, fmt.Sprintf(\"%d\", internet.faker.random.Intn(253)+2))\n\t}\n\treturn strings.Join(parts, \".\")\n}", "func IPv4Address(ctx context.Context, client *docker.Client, containerID string) (net.IP, error) {\n\tc, err := client.InspectContainerWithContext(containerID, ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"find container %s address: %w\", containerID, err)\n\t}\n\treturn ipv4Address(c)\n}", "func PublicIpv4EqualFold(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.EqualFold(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (t *netUtils) GetLocalIpv4() string {\n\tt.once.Do(func() {\n\t\tif ias, err := net.InterfaceAddrs(); err == nil {\n\t\t\tfor _, address := range ias {\n\t\t\t\tif ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {\n\t\t\t\t\tif ipNet.IP.To4() != nil {\n\t\t\t\t\t\tt.localIpv4 = ipNet.IP.String()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\treturn t.localIpv4\n}", "func IsPublicIPv4(ip net.IP) bool {\n\tif ip == nil {\n\t\treturn false\n\t}\n\n\tif ip.IsLoopback() || ip.IsLinkLocalMulticast() || ip.IsLinkLocalUnicast() {\n\t\treturn false\n\t}\n\n\tif ip4 := ip.To4(); ip4 != nil {\n\t\tswitch true {\n\t\tcase ip4[0] == 10:\n\t\t\treturn false\n\t\tcase ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:\n\t\t\treturn false\n\t\tcase ip4[0] == 192 && ip4[1] == 168:\n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (c *Connection) PublicIP() string {\n\tif c.ipAddress == \"\" {\n\t\tc.getPublicIP()\n\t}\n\treturn c.ipAddress\n}", "func localIPv4s() ([]string, error) {\n\tvar ips []string\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\n\tfor _, a := range addrs {\n\t\tif ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {\n\t\t\tips = append(ips, ipnet.IP.String())\n\t\t}\n\t}\n\n\treturn ips, nil\n}", "func PublicIpv4HasSuffix(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldPublicIpv4), v))\n\t})\n}", "func PublicIpv4LTE(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldPublicIpv4), v))\n\t})\n}", "func GetPublicIPAddress(client Clients, ctx context.Context,\n\tresourceGroup string, PublicIPname string, expand string) (PublicIPAddress string, err error) {\n\tvmPublicIP := client.VMPublicIP\n\tVMIP, err := vmPublicIP.Get(ctx, resourceGroup, PublicIPname, expand)\n\tif err != nil {\n\t\t\treturn\n\t}\n\tif VMIP.PublicIPAddressPropertiesFormat != nil && VMIP.PublicIPAddressPropertiesFormat.IPAddress != nil {\n\t\t\tPublicIPAddress = *VMIP.PublicIPAddressPropertiesFormat.IPAddress\n\n\t} else {\n\t\t\terr = errors.New(\"Vm has no publicIPAddress\")\n\t}\n\treturn\n\n}", "func PublicIpv4ContainsFold(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.ContainsFold(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (o *CreateClientGatewayRequest) GetPublicIp() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.PublicIp\n}", "func DetectHostIPv4() (string, error) {\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn \"\", errors.WithStack(err)\n\t}\n\tfor _, a := range addrs {\n\t\tif ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\tif ipnet.IP.To4() == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn ipnet.IP.String(), nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"cannot detect host IPv4 address\")\n}", "func (ipSet *IPSet) IsIPv4() bool {\n\treturn govalidator.IsIPv4(ipSet.IPv4)\n}", "func (instanceKey *InstanceKey) IsIPv4() bool {\n\treturn ipv4Regexp.MatchString(instanceKey.Hostname)\n}", "func GetPublicIPAddress() (string, error) {\n\tresp, err := http.Get(\"http://checkip.amazonaws.com/\")\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t\tresp.Close = true\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), err\n}", "func stringIPv4(n uint32) string {\n\tip := make(net.IP, 4)\n\tbinary.BigEndian.PutUint32(ip, n)\n\treturn ip.String()\n}", "func IpV4Address() string {\n\tblocks := []string{}\n\tfor i := 0; i < 4; i++ {\n\t\tnumber := seedAndReturnRandom(255)\n\t\tblocks = append(blocks, strconv.Itoa(number))\n\t}\n\n\treturn strings.Join(blocks, \".\")\n}", "func (o *LinkPublicIpRequest) GetPublicIp() string {\n\tif o == nil || o.PublicIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIp\n}", "func RandomIPv4() string {\n\tfirst := rand.Int31n(256)\n\tsecond := rand.Int31n(256)\n\tthird := rand.Int31n(256)\n\tfourth := rand.Int31n(256)\n\tstr := fmt.Sprintf(\"%d.%d.%d.%d\", first, second, third, fourth)\n\treturn str\n}", "func PublicIpv4GT(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldPublicIpv4), v))\n\t})\n}", "func GetPublicAddress() (PublicAddress, error) {\n\tvar ip PublicAddress\n\tres, err := http.Get(\"http://ipinfo.io/json\")\n\tif err != nil {\n\t\treturn ip, err\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ip, err\n\t}\n\n\terr = json.Unmarshal(body, &ip)\n\tif err != nil {\n\t\treturn ip, nil\n\t}\n\n\treturn ip, nil\n}", "func (instance *Host) GetPublicIP(_ context.Context) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn \"\", fail.InvalidInstanceError()\n\t}\n\n\tthis, err := instance.MetadataCore.properties.UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\n\tif val, ok := this[hostproperty.NetworkV2]; !ok {\n\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t} else {\n\t\tif val == nil {\n\t\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t\t}\n\t}\n\n\taclo, err := this[hostproperty.NetworkV2].UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\thnV2, _ := aclo.(*propertiesv2.HostNetworking) // nolint\n\n\tpublicIP := hnV2.PublicIPv4\n\tif publicIP == \"\" {\n\t\tpublicIP = hnV2.PublicIPv6\n\t\tif publicIP == \"\" {\n\t\t\treturn \"\", fail.NotFoundError(\"failed to find Public IP of Host '%s'\", instance.GetName())\n\t\t}\n\t}\n\n\treturn publicIP, nil\n}", "func ResolveIPv4(host string) (net.IP, error) {\n\tif node := DefaultHosts.Search(host); node != nil {\n\t\tif ip := node.Data.(net.IP).To4(); ip != nil {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip != nil {\n\t\tif !strings.Contains(host, \":\") {\n\t\t\treturn ip, nil\n\t\t}\n\t\treturn nil, errIPVersion\n\t}\n\n\tif DefaultResolver != nil {\n\t\treturn DefaultResolver.ResolveIPv4(host)\n\t}\n\n\tipAddrs, err := net.LookupIP(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, ip := range ipAddrs {\n\t\tif ip4 := ip.To4(); ip4 != nil {\n\t\t\treturn ip4, nil\n\t\t}\n\t}\n\n\treturn nil, errIPNotFound\n}", "func PublicIpv4In(vs ...string) predicate.Agent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldPublicIpv4), v...))\n\t})\n}", "func publicIP() (net.IP, error) {\n\tresp, err := http.Get(publicEcho)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn := net.ParseIP(string(out))\n\tif n == nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse ip %s\", string(out))\n\t}\n\n\treturn n, nil\n}", "func isIPv4(fl FieldLevel) bool {\n\tip := net.ParseIP(fl.Field().String())\n\n\treturn ip != nil && ip.To4() != nil\n}", "func PublicIpv4NEQ(v string) predicate.Agent {\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\ts.Where(sql.NEQ(s.C(FieldPublicIpv4), v))\n\t})\n}", "func (s *Server) IPv4Net() (*net.IPNet, error) {\n\tvar ip net.IP\n\tif ip = net.ParseIP(s.IPv4Address); ip == nil {\n\t\treturn nil, fmt.Errorf(\"error parsing IPv4Address '%s'\", s.IPv4Address)\n\t}\n\treturn &net.IPNet{\n\t\tIP: ip,\n\t\tMask: net.CIDRMask(32, 32),\n\t}, nil\n}", "func GetPublicIP() (*net.IPAddr, error) {\n\n\t// make a request to IPGetURL to get the public ip address\n\tresp, err := http.Get(IPGetURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// process the response\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert the response into the ip address\n\treturn net.ResolveIPAddr(\"\", string(body))\n}", "func (o *IppoolPoolMember) GetIpV4Address() string {\n\tif o == nil || o.IpV4Address == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.IpV4Address\n}", "func indexAsIPv4(i uint32, baseSlashEight int) string {\n\tip := make(net.IP, 4)\n\tbinary.BigEndian.PutUint32(ip, uint32(i)+uint32(baseSlashEight*16777216))\n\treturn ip.String()\n}", "func (p *IPv4) Version() int {\n\treturn p.version\n}", "func (b *Box) GetPublicIp() string {\n\treturn b.PublicIp\n}", "func (o *PublicIp) GetPublicIp() string {\n\tif o == nil || o.PublicIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIp\n}", "func (o *PublicIp) GetPublicIp() string {\n\tif o == nil || o.PublicIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIp\n}", "func (internet *Internet) PrivateIPv4Address() string {\n\tfor {\n\t\ts := internet.IPv4Address()\n\t\tif isPrivateNet(s) {\n\t\t\treturn s\n\t\t}\n\t}\n}", "func ipv4only(addr IPAddr) bool {\n\treturn supportsIPv4 && addr.IP.To4() != nil\n}", "func parseIPv4(ip string) net.IP {\n\tif parsedIP := net.ParseIP(strings.TrimSpace(ip)); parsedIP != nil {\n\t\tif ipv4 := parsedIP.To4(); ipv4 != nil {\n\t\t\treturn ipv4\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *LinkPublicIpRequest) GetPublicIpId() string {\n\tif o == nil || o.PublicIpId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIpId\n}", "func (o *CreateLoadBalancerRequest) GetPublicIp() string {\n\tif o == nil || o.PublicIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIp\n}", "func (o *StorageHitachiPortAllOf) GetIpv4Address() string {\n\tif o == nil || o.Ipv4Address == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Ipv4Address\n}", "func NewIPv4(value string) (IPv4, error) {\n\tvar IP = IPv4{value: value}\n\n\tif !IP.validate() {\n\t\treturn IPv4{}, ErrInvalidIPv4\n\t}\n\n\treturn IP, nil\n}", "func (e *Domain) Public() *PublicKey {\n\tif e.PublicKey != nil {\n\t\treturn e.PublicKey\n\t}\n\n\tif e.ClearPrivateKey != nil {\n\t\treturn e.ClearPrivateKey.Public()\n\t}\n\treturn nil\n}", "func (ipSet *IPSet) HasIPv4() bool {\n\treturn ipSet.IPv4 != \"\"\n}", "func (o *LocalDatabaseProvider) GetIpPoolV4() string {\n\tif o == nil || o.IpPoolV4 == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.IpPoolV4\n}", "func (s *Service) GetPublicIPAddress(resourceGroup string, IPName string) (armada.PublicIPAddress, error) {\n\t//JEB return s.scope.AirshipClients.PublicIPAddresses.Get(s.scope.Context, resourceGroup, IPName, \"\")\n\treturn armada.PublicIPAddress{}, nil\n}", "func (s IPV4) String() string {\n\treturn fmt.Sprintf(\"%v.%v.%v.%v\", s[0], s[1], s[2], s[3])\n}", "func IPv4(str string) bool {\n\tip := net.ParseIP(str)\n\treturn ip != nil && strings.Contains(str, \".\")\n}", "func (ip IPv4) String() string {\n\treturn string(ip.value)\n}", "func (ip IPv4) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\", ip[0], ip[1], ip[2], ip[3])\n}", "func (c *MockAzureCloud) PublicIPAddress() azure.PublicIPAddressesClient {\n\treturn c.PublicIPAddressesClient\n}", "func (af AddressFamily) IsIPv4() bool {\n\treturn af == AddressFamilyIPv4\n}", "func (p *IPv4) Offset() uint16 {\n\treturn p.offset\n}", "func getLocalIP()(ipv4 string, err error) {\n\tvar (\n\t\taddrs []net.Addr\n\t\taddr net.Addr\n\t\tipNet *net.IPNet\n\t\tisIpNet bool\n\t)\n\t//get all network interface\n\tif addrs, err = net.InterfaceAddrs(); err != nil {\n\t\treturn\n\t}\n\t//get first none localhost IP address\n\tfor _, addr = range addrs {\n\t\t//ipv4, ipv6\n\t\t//this network address is ip address\n\t\tif ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback() {\n\t\t\t//skip ipv6\n\t\t\tif ipNet.IP.To4() != nil {\n\t\t\t\tipv4 = ipNet.IP.String() //192.168.1.1\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\terr = common.ERR_NO_LOCAL_IP_FOUND\n\treturn\n}", "func (n *hostOnlyNetwork) SaveIPv4(vbox VBoxManager) error {\n\tif n.IPv4.IP != nil && n.IPv4.Mask != nil {\n\t\tif err := vbox.vbm(\"hostonlyif\", \"ipconfig\", n.Name, \"--ip\", n.IPv4.IP.String(), \"--netmask\", net.IP(n.IPv4.Mask).String()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *Lisp_address) lisp_is_ipv4() bool {\n\treturn((len(a.address) == 4))\n}", "func GetPublicIPAddressID(client Clients,\n\tctx context.Context, resourceGroup string, networkInterface string,\n\texpand string) (PublicIPAddressID string, err error) {\n\tvmInterface := client.VMInterface\n\tinterfaces, err := vmInterface.Get(ctx, resourceGroup, networkInterface, expand)\n\tif err != nil {\n\t\t\treturn\n\t}\n\tinterfaceinfo := *interfaces.InterfacePropertiesFormat.IPConfigurations\n\tinterfID := *interfaceinfo[0].InterfaceIPConfigurationPropertiesFormat\n\n\tif interfID.PublicIPAddress != nil && interfID.PublicIPAddress.ID != nil {\n\t\t\tID := strings.Split(*interfID.PublicIPAddress.ID, \"/\")\n\t\t\tPublicIPAddressID = ID[8]\n\t} else {\n\t\t\terr = errors.New(\"Vm has no publicIPname\")\n\t}\n\treturn\n}", "func (f *FSEIDFields) HasIPv4() bool {\n\treturn has2ndBit(f.Flags)\n}", "func (p *IPv4) Src() net.IP {\n\treturn p.src\n}", "func (h *Ec2Handler) PublicIP() (*string, error) {\n\tinput := &ec2.DescribeNetworkInterfacesInput{\n\t\tNetworkInterfaceIds: []*string{\n\t\t\taws.String(*h.Eni),\n\t\t},\n\t}\n\n\tresult, err := h.Service.DescribeNetworkInterfaces(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tlog.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif len(result.NetworkInterfaces) > 0 {\n\t\treturn result.NetworkInterfaces[0].Association.PublicIp, err\n\t}\n\treturn nil, errors.New(\"No ENI found\")\n\t// (TODO)If public IP not found, attach an EIP\n}", "func (b *OGame) GetPublicIP() (string, error) {\n\treturn b.getPublicIP()\n}", "func (o InstanceOutput) AccessIpV4() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.AccessIpV4 }).(pulumi.StringOutput)\n}", "func (p *publicIPResolver) Resolve() (string, error) {\n\toutput, err := exec.Command(\"dig\", \"+time=1\", \"+short\", p.Hostname, \"@\"+p.Server).Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(output) == 0 {\n\t\t//fail.\n\t\treturn \"\", errors.New(\"no ipv4 valid address\")\n\t}\n\tstringIP := string(output[0 : len(output)-1]) //output has a trailing newline\n\tip := net.ParseIP(stringIP)\n\tif ip == nil || ip.To4() == nil {\n\t\treturn \"\", errors.New(\"no ipv4 valid address\")\n\t}\n\treturn stringIP, nil\n}", "func extractIPv4(ptr string) string {\n\ts := strings.Replace(ptr, \".in-addr.arpa\", \"\", 1)\n\twords := strings.Split(s, \".\")\n\tfor i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {\n\t\twords[i], words[j] = words[j], words[i]\n\t}\n\treturn strings.Join(words, \".\")\n}", "func ParseIPv4(data []byte) (Packet, error) {\n\tif len(data) < 20 {\n\t\treturn nil, ErrorTruncated\n\t}\n\tihl := int(data[0] & 0x0f)\n\theaderLen := ihl * 4\n\tlength := int(bo.Uint16(data[2:]))\n\n\tif headerLen < 20 || headerLen > length {\n\t\treturn nil, ErrorInvalid\n\t}\n\tif length > len(data) {\n\t\treturn nil, ErrorTruncated\n\t}\n\tif Checksum(data[0:headerLen]) != 0 {\n\t\treturn nil, ErrorChecksum\n\t}\n\n\treturn &IPv4{\n\t\tversion: int(data[0] >> 4),\n\t\ttos: int(data[1]),\n\t\tid: bo.Uint16(data[4:]),\n\t\tflags: int8(data[6] >> 5),\n\t\toffset: bo.Uint16(data[6:]) & 0x1fff,\n\t\tttl: data[8],\n\t\tprotocol: Protocol(data[9]),\n\t\tsrc: net.IP(data[12:16]),\n\t\tdst: net.IP(data[16:20]),\n\t\tdata: data[headerLen:length],\n\t}, nil\n}", "func (o GetLBFrontendIpConfigurationOutput) PublicIpAddressId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLBFrontendIpConfiguration) string { return v.PublicIpAddressId }).(pulumi.StringOutput)\n}", "func (client *MockClient) generatePodIPv4() string {\n\tclient.ipCounter++\n\treturn fmt.Sprintf(\"1.1.%d.%d\", client.ipCounter/256, client.ipCounter%256)\n}", "func IsIPv4(ip *net.IP) bool {\n\treturn ip.To4() != nil\n}", "func (n *NetworkAssociation) IPv4Net() (*net.IPNet, error) {\n\tvar ip net.IP\n\tif ip = net.ParseIP(n.ServerIP); ip == nil {\n\t\treturn nil, fmt.Errorf(\"error parsing ServerIP '%s'\", ip)\n\t}\n\treturn &net.IPNet{\n\t\tIP: ip,\n\t\tMask: net.CIDRMask(24, 32),\n\t}, nil\n}", "func getLocalIP() net.IP {\n\t// try host file first\n\tif h, err := os.Hostname(); err == nil {\n\t\tif addrs, err := net.LookupIP(h); err == nil && len(addrs) != 0 {\n\t\t\tif ipv4 := addrs[0].To4(); ipv4 != nil {\n\t\t\t\treturn ipv4\n\t\t\t}\n\t\t}\n\t}\n\t// then try local interfaces\n\tif addrs, err := net.InterfaceAddrs(); err == nil {\n\t\tfor _, address := range addrs {\n\t\t\t// check the address type and if it is not a loopback the display it\n\t\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\t\tif ipv4 := ipnet.IP.To4(); ipv4 != nil {\n\t\t\t\t\treturn ipv4\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// default use random (may not be a valid ip, but ok)\n\tipv4 := make([]byte, 4)\n\tsafeRandom(ipv4)\n\treturn ipv4\n}", "func AllLocalIP4() ([]net.IP, error) {\n\tdevices, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []net.IP{}\n\tfor _, dev := range devices {\n\t\tif dev.Flags&net.FlagUp != 0 {\n\t\t\taddrs, err := dev.Addrs()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor i := range addrs {\n\t\t\t\tif ip, ok := addrs[i].(*net.IPNet); ok {\n\t\t\t\t\tif ip.IP.To4() != nil {\n\t\t\t\t\t\tret = append(ret, ip.IP)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn ret, nil\n}" ]
[ "0.775234", "0.7012714", "0.691517", "0.6890725", "0.68701094", "0.6776191", "0.67407", "0.66122025", "0.6596317", "0.6571325", "0.6540334", "0.6535578", "0.6456901", "0.6455598", "0.64042497", "0.6378031", "0.6375623", "0.6311204", "0.63032615", "0.62778425", "0.6264339", "0.62629193", "0.6203791", "0.6200218", "0.61998475", "0.6195142", "0.6173486", "0.6167399", "0.61597776", "0.6155863", "0.61397195", "0.612713", "0.61187565", "0.6076183", "0.60382634", "0.60193455", "0.598249", "0.59425354", "0.5941841", "0.58952016", "0.58814794", "0.5866687", "0.5866296", "0.58588624", "0.5851499", "0.5830964", "0.5827437", "0.58182013", "0.5805094", "0.5795052", "0.57898563", "0.5775306", "0.5774111", "0.5771993", "0.5756813", "0.5728229", "0.57250065", "0.57194364", "0.57039523", "0.56934595", "0.56891966", "0.56828207", "0.5670953", "0.5670953", "0.5669155", "0.564829", "0.5643089", "0.56259125", "0.56235904", "0.56222886", "0.56036294", "0.5561767", "0.5554165", "0.5549632", "0.5549568", "0.5544833", "0.5527406", "0.55193424", "0.5506093", "0.550333", "0.54843056", "0.5451741", "0.544118", "0.54386854", "0.5433842", "0.5424841", "0.5420968", "0.54205537", "0.54141253", "0.5409441", "0.54091495", "0.54028755", "0.54024523", "0.54011536", "0.5394192", "0.539225", "0.5388267", "0.5378808", "0.5376633", "0.53617966" ]
0.82904613
0
Region returns the Network Zone of the server that did the request to the Metadata server.
func (c *Client) Region() (string, error) { return c.get("/region") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o NetworkOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Network) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o GetHostedZoneResultOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetHostedZoneResult) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (o PublicAdvertisedPrefixPublicDelegatedPrefixResponseOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PublicAdvertisedPrefixPublicDelegatedPrefixResponse) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o NodeBalancerOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NodeBalancer) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o PublicDelegatedPrefixPublicDelegatedSubPrefixResponseOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PublicDelegatedPrefixPublicDelegatedSubPrefixResponse) string { return v.Region }).(pulumi.StringOutput)\n}", "func (c *MockAzureCloud) Region() string {\n\treturn c.Location\n}", "func (v *VCard) Region() string {\n\treturn v.getFirstAddressField(4)\n}", "func (c *Client) Region() string {\n\treturn c.region.String()\n}", "func (o ServerGroupOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServerGroup) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r ListDNSRecordsRequest) GetRegionId() string {\n return \"\"\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (m *metadata) GetRegion() string {\n\treturn m.region\n}", "func (o RegionNetworkEndpointGroupOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionNetworkEndpointGroup) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o RecordLatencyRoutingPolicyOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RecordLatencyRoutingPolicy) string { return v.Region }).(pulumi.StringOutput)\n}", "func (m *Info) GetRegion() string {\n\treturn m.ec2Metadata.getRegion()\n}", "func (o GetTrafficPolicyDocumentEndpointOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentEndpoint) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (r QueryDeviceStatusForPCdnRequest) GetRegionId() string {\n return \"\"\n}", "func (e Endpoint) Region() string {\n\tif e.Properties.CredentialScope.Region != \"\" {\n\t\treturn fmt.Sprintf(\"%q\", e.Properties.CredentialScope.Region)\n\t}\n\treturn \"region\"\n}", "func (o StorageNodeStatusGeographyOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageNodeStatusGeography) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (c *AccessConfig) metadataRegion() string {\n\n\tclient := cleanhttp.DefaultClient()\n\n\t// Keep the default timeout (100ms) low as we don't want to wait in non-EC2 environments\n\tclient.Timeout = 100 * time.Millisecond\n\tec2meta := ec2metadata.New(session.New(), &aws.Config{\n\t\tHTTPClient: client,\n\t})\n\tregion, err := ec2meta.Region()\n\tif err != nil {\n\t\tlog.Println(\"Error getting region from metadata service, \"+\n\t\t\t\"probably because we're not running on AWS.\", err)\n\t\treturn \"\"\n\t}\n\treturn region\n}", "func (o GetEndpointResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o LookupFloatingIpResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFloatingIpResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (s serverConfigV14) GetRegion() string {\n\tserverConfigMu.RLock()\n\tdefer serverConfigMu.RUnlock()\n\n\treturn s.Region\n}", "func (c *Client) GetRegion() string {\n\treturn c.config.Region\n}", "func (r AuthPrivilegeRequest) GetRegionId() string {\n return \"\"\n}", "func (o RegionTargetHttpsProxyOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionTargetHttpsProxy) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o GetTrafficPolicyDocumentRuleRegionOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRuleRegion) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (r DeleteExtraCacheTimeRequest) GetRegionId() string {\n return \"\"\n}", "func (r DescribeThingShadowRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r DeployRequest) GetRegionId() string {\n return \"\"\n}", "func (r InvokeRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r CreateClusterRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r InvokeCommandRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o GatewayLocationDataOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GatewayLocationData) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (r LastDownsampleRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o GetTrafficPolicyDocumentRuleGeoProximityLocationOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRuleGeoProximityLocation) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (o *DisplayInfo) GetRegion() string {\n\tif o == nil || o.Region == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Region\n}", "func (r OnlineSqlTaskQueryRequest) GetRegionId() string {\n return r.RegionId\n}", "func getRegionFromZone(zoneName string) string {\n\treturn zoneName[:strings.LastIndex(zoneName, \"-\")]\n}", "func (r DescribeCacheInstancesRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r VerifyContractRequest) GetRegionId() string {\n return \"\"\n}", "func (r DescribeAuditLogRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o LookupSpacesBucketResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpacesBucketResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (r GetLargeScreenDataRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o GatewayLocationDataPtrOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *GatewayLocationData) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Region\n\t}).(pulumi.StringPtrOutput)\n}", "func (r SearchLogContextRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o StorageNodeStatusGeographyPtrOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageNodeStatusGeography) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Region\n\t}).(pulumi.StringPtrOutput)\n}", "func (r StatusReportRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o OceanOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o LookupDatabaseMysqlResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDatabaseMysqlResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func GetRegion(ctx *pulumi.Context) string {\n\tv, err := config.Try(ctx, \"newrelic:region\")\n\tif err == nil {\n\t\treturn v\n\t}\n\tvar value string\n\tif d := internal.GetEnvOrDefault(\"US\", nil, \"NEW_RELIC_REGION\"); d != nil {\n\t\tvalue = d.(string)\n\t}\n\treturn value\n}", "func (r DescribeBandwidthsRequest) GetRegionId() string {\n return \"\"\n}", "func (d *DB) Get_region(ipaddress string) (IP2Locationrecord, error) {\n\treturn d.query(ipaddress, region)\n}", "func (o GetGroupResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetGroupResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (o AiFeatureStoreEntityTypeFeatureOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreEntityTypeFeature) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r DescribeSlowLogRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o DatabaseReplicaOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringPtrOutput { return v.Region }).(pulumi.StringPtrOutput)\n}", "func Get_region(ipaddress string) IP2Locationrecord {\n\treturn handleError(defaultDB.query(ipaddress, region))\n}", "func (o MonitorV1Output) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *MonitorV1) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o ContainerV1Output) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerV1) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r AttachGroupPolicyRequest) GetRegionId() string {\n return \"\"\n}", "func GetRegion(svc *ec2metadata.EC2Metadata) (string, error) {\n\tdoc, err := svc.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn doc.Region, nil\n}", "func (o InstanceOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r *Bucket) Region() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"region\"])\n}", "func (r GeneralAlterEventRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r DescribeDomainOnlineStreamRequest) GetRegionId() string {\n return \"\"\n}", "func (config *Config) GetRegion() string {\n\tregion := config.Region\n\n\tif region == \"\" {\n\t\tregion = Region[\"bj\"]\n\t}\n\n\treturn region\n}", "func (CcsAwsSession *ccsAwsSession) GetRegion() *string {\n\treturn CcsAwsSession.session.Config.Region\n}", "func (info *endpointsInfo) GetZone() string {\n\treturn \"\"\n}", "func (o WorkerPoolOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (r CreateCollectInfoRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r UpdateAsCronRequest) GetRegionId() string {\n return r.RegionId\n}", "func (m *GetNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (d *Downloader) getRegion() string {\n\tif d.region != \"\" {\n\t\treturn d.region\n\t}\n\n\tregion, err := d.metadata.Region()\n\tif err != nil {\n\t\tlog.Warn(\"Could not retrieve the region from EC2 Instance Metadata. Error: %s\", err.Error())\n\t\tregion = config.DefaultRegionName\n\t}\n\td.region = region\n\n\treturn d.region\n}", "func GetRegion(metaEndPoint string, preferEnv bool) string {\n\tvar region string\n\tif preferEnv {\n\t\tregion = getRegionFromEnv()\n\t\tif region == \"\" {\n\t\t\tregion = getRegionFromInstanceDocument(metaEndPoint)\n\t\t}\n\t} else {\n\t\tregion = getRegionFromInstanceDocument(metaEndPoint)\n\t\tif region == \"\" {\n\t\t\tregion = getRegionFromEnv()\n\t\t}\n\t}\n\tif region == \"\" {\n\t\tlog.Println(\"No region information available. Defaulting to us-west-2\")\n\t\tregion = \"us-west-2\"\n\t}\n\treturn region\n}", "func (c *Client) GetRegion() Region {\n\treturn c.region\n}", "func (c *Client) GetRegion() Region {\n\treturn c.region\n}", "func (r CreateBackupPlanRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r DelSubDeviceWithCoreRequest) GetRegionId() string {\n return r.RegionId\n}", "func (f *Finding) Zone() string {\n\treturn f.badNetwork.JSONPayload.Properties.Location\n}", "func (r ReportTaskRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r AddPushStreamRuleRequest) GetRegionId() string {\n return \"\"\n}", "func (r ModifyTaskRequest) GetRegionId() string {\n return r.RegionId\n}", "func (r SetAuthConfigRequest) GetRegionId() string {\n return \"\"\n}", "func (r CreateVideoUploadTaskRequest) GetRegionId() string {\n return \"\"\n}", "func (o LookupRegionCommitmentResultOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionCommitmentResult) string { return v.Region }).(pulumi.StringOutput)\n}", "func (r CreateImageFromSnapshotsRequest) GetRegionId() string {\n return r.RegionId\n}", "func (o SslCertificateOutput) Region() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SslCertificate) pulumi.StringOutput { return v.Region }).(pulumi.StringOutput)\n}", "func (d *DynamoDBMetastore) GetRegionSuffix() string {\n\treturn d.regionSuffix\n}", "func (c *Client) GetZone() (zone string, err error) {\n\tclient := &http.Client{\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\turl := fmt.Sprintf(\"%s://%s.%s:%d\", c.Protocol, c.BucketName, c.Host, c.Port)\n\n\tr, err := client.Head(url)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Get QingStor zone failed for %v.\", err)\n\t\treturn\n\t}\n\n\t// Example URL: https://bucket.zone.qingstor.com\n\tzone = strings.Split(r.Header.Get(\"Location\"), \".\")[1]\n\treturn\n}", "func (o *Workloadv1Location) GetRegion() string {\n\tif o == nil || o.Region == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Region\n}", "func (t *Toon) Region() *Region {\n\treturn regionByID(t.RegionID())\n}", "func (o RegionAutoscalerOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringOutput { return v.Zone }).(pulumi.StringOutput)\n}", "func (r AddTemplateRequest) GetRegionId() string {\n return r.RegionId\n}", "func (m *CreateNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func CurrentRegion() string {\n\treturn currentRegion\n}", "func (m *GetServerConfigRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) string { return v.Zone }).(pulumi.StringOutput)\n}", "func (r UpdateListenerRequest) GetRegionId() string {\n return r.RegionId\n}" ]
[ "0.6817", "0.6758568", "0.6720305", "0.6707795", "0.6699388", "0.66549444", "0.664351", "0.6642627", "0.65156317", "0.6500608", "0.6492319", "0.64468133", "0.64309245", "0.64101046", "0.63972497", "0.6389187", "0.63647854", "0.6362243", "0.63586366", "0.6350317", "0.6347361", "0.63378006", "0.63289547", "0.6319039", "0.6309046", "0.6299769", "0.6223691", "0.6213223", "0.62095743", "0.6205863", "0.6199444", "0.6185749", "0.61701566", "0.6152018", "0.615191", "0.6147579", "0.61472034", "0.6137002", "0.6134532", "0.6130243", "0.6114933", "0.60907537", "0.60749024", "0.60610723", "0.60560596", "0.604516", "0.60435224", "0.6041038", "0.6034111", "0.60270685", "0.60204715", "0.6019544", "0.6015748", "0.60146123", "0.60106856", "0.59679276", "0.59574884", "0.594957", "0.5948054", "0.59266025", "0.592464", "0.5913107", "0.5900425", "0.5900425", "0.58996254", "0.58963877", "0.589446", "0.58833015", "0.58779263", "0.58639884", "0.58535117", "0.58529484", "0.58341515", "0.58279866", "0.58229786", "0.5821941", "0.5805224", "0.5805224", "0.5791784", "0.5791287", "0.57860583", "0.5774018", "0.5773654", "0.577327", "0.57709116", "0.5768528", "0.57669866", "0.57669604", "0.57663816", "0.57636", "0.5743941", "0.5743528", "0.57350135", "0.57155526", "0.5713019", "0.5711068", "0.57081527", "0.56932354", "0.5690837", "0.56863725" ]
0.6994445
0
AvailabilityZone returns the datacenter of the server that did the request to the Metadata server.
func (c *Client) AvailabilityZone() (string, error) { return c.get("/availability-zone") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *metadata) GetAvailabilityZone() string {\n\treturn m.availabilityZone\n}", "func (m *MachineScope) AvailabilityZone() string {\n\tif m.Machine.Spec.FailureDomain != nil {\n\t\treturn *m.Machine.Spec.FailureDomain\n\t}\n\t// Deprecated: to support old clients\n\tif m.AzureMachine.Spec.FailureDomain != nil {\n\t\treturn *m.AzureMachine.Spec.FailureDomain\n\t}\n\n\treturn \"\"\n}", "func (o ClusterOutput) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (o ContainerServiceOutput) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ContainerService) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (o ClusterInstanceOutput) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterInstance) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (m *ProxyConfig) GetAvailabilityZone() string {\n\tif m != nil {\n\t\treturn m.AvailabilityZone\n\t}\n\treturn \"\"\n}", "func (m *ProxyConfig) GetAvailabilityZone() string {\n\tif m != nil {\n\t\treturn m.AvailabilityZone\n\t}\n\treturn \"\"\n}", "func (o InstanceOutput) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (north north_DakotaTimeZones) Center() string {return \"America/North_Dakota/Center\" }", "func (o VolumeV2Output) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VolumeV2) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (client *AwsClientWrapper) GetAvailabilityZone(machine *clusterv1alpha1.Machine) (string, error) {\n\tinstance, err := getRunningInstance(machine, client.client)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif instance.Placement == nil {\n\t\treturn \"\", err\n\t}\n\treturn *instance.Placement.AvailabilityZone, nil\n}", "func (o SubnetOutput) AvailabilityZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Subnet) pulumi.StringOutput { return v.AvailabilityZone }).(pulumi.StringOutput)\n}", "func (r Virtual_DedicatedHost) GetDatacenter() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_DedicatedHost\", \"getDatacenter\", nil, &r.Options, &resp)\n\treturn\n}", "func getClusterNameFromZone(ctx context.Context, availabilityZone string) string {\n\tclusterName := \"\"\n\tclusterComputeResourceList, _, err := getClusterName(ctx, &e2eVSphere)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tnimbusGeneratedVcPwd := GetAndExpectStringEnvVar(vcUIPwd)\n\tcmd := fmt.Sprintf(\"dcli +username %s +password %s +skip +show com vmware \"+\n\t\t\"vcenter consumptiondomains zones cluster associations get --zone \"+\n\t\t\"%s\", adminUser, nimbusGeneratedVcPwd, availabilityZone)\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\tframework.Logf(\"Invoking command %v on vCenter host %v\", cmd, vcAddress)\n\tresult, err := fssh.SSH(cmd, vcAddress, framework.TestContext.Provider)\n\tframework.Logf(\"result: %v\", result)\n\tclusterId := strings.Split(result.Stdout, \"- \")[1]\n\tclusterID := strings.TrimSpace(clusterId)\n\tframework.Logf(\"clusterId: %v\", clusterID)\n\tfmt.Print(clusterId)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\tframework.Failf(\"couldn't execute command: %s on vCenter host: %v\", cmd, err)\n\t}\n\tfor _, cluster := range clusterComputeResourceList {\n\t\tclusterMoId := cluster.Reference().Value\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tframework.Logf(\"cluster MOID %v\", clusterMoId)\n\t\tif clusterMoId == clusterID {\n\t\t\tframework.Logf(\"Found matching cluster domain!!\")\n\t\t\tclusterName = cluster.Name()\n\t\t\tbreak\n\t\t}\n\t}\n\tframework.Logf(\"cluster on zone is: %s\", clusterName)\n\tif clusterName == \"\" {\n\t\tframework.Failf(\"couldn't find cluster on zone %s\", availabilityZone)\n\t}\n\treturn clusterName\n\n}", "func (info *endpointsInfo) GetZone() string {\n\treturn \"\"\n}", "func (z zones) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\tzone, err := queryInstanceMetadata(\"availability-zone\")\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\treturn cloudprovider.Zone{Region: zone}, nil\n}", "func (r Virtual_Guest) GetDatacenter() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getDatacenter\", nil, &r.Options, &resp)\n\treturn\n}", "func getHostedZone(APIServerURL string) (string, error) {\n\turl, err := url.Parse(APIServerURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsplit := strings.Split(url.Host, \".\")\n\tif len(split) < 2 {\n\t\treturn \"\", fmt.Errorf(\"can't derive hosted zone from URL %s\", APIServerURL)\n\t}\n\n\treturn strings.Join(split[1:], \".\"), nil\n}", "func (m *GetClusterRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (c *Client) GetZone() (zone string, err error) {\n\tclient := &http.Client{\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\turl := fmt.Sprintf(\"%s://%s.%s:%d\", c.Protocol, c.BucketName, c.Host, c.Port)\n\n\tr, err := client.Head(url)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Get QingStor zone failed for %v.\", err)\n\t\treturn\n\t}\n\n\t// Example URL: https://bucket.zone.qingstor.com\n\tzone = strings.Split(r.Header.Get(\"Location\"), \".\")[1]\n\treturn\n}", "func (m *GetServerConfigRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *SetMasterAuthRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (r Virtual_Storage_Repository) GetDatacenter() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Storage_Repository\", \"getDatacenter\", nil, &r.Options, &resp)\n\treturn\n}", "func (m *Cluster) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *CreateClusterRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *UpdateMasterRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (k *Kubernetes) primaryZone() string { return k.Zones[k.primaryZoneIndex] }", "func (o *VmRestorePoint) GetAvailabilityZoneId() string {\n\tif o == nil || o.AvailabilityZoneId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.AvailabilityZoneId\n}", "func (m *SetNodePoolAutoscalingRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *ListClustersRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (o *SSHAuthority) GetZone() int {\n\n\treturn o.Zone\n}", "func (m *UpdateClusterRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (info *BaseEndpointInfo) GetZone() string {\n\treturn info.Zone\n}", "func (r *Cluster) AvailabilityZones() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"availabilityZones\"])\n}", "func (m *GetNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (s *azureMachineService) getVirtualMachineZone() (string, error) {\n\tvmName := s.machineScope.AzureMachine.Name\n\tvmSize := s.machineScope.AzureMachine.Spec.VMSize\n\tlocation := s.machineScope.AzureMachine.Spec.Location\n\n\tzonesSpec := &availabilityzones.Spec{\n\t\tVMSize: vmSize,\n\t}\n\tzonesInterface, err := s.availabilityZonesSvc.Get(s.clusterScope.Context, zonesSpec)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to check availability zones for %s in region %s\", vmSize, location)\n\t}\n\tif zonesInterface == nil {\n\t\t// if its nil, probably means no zones found\n\t\treturn \"\", nil\n\t}\n\tzones, ok := zonesInterface.([]string)\n\tif !ok {\n\t\treturn \"\", errors.New(\"availability zones Get returned invalid interface\")\n\t}\n\n\tif len(zones) <= 0 {\n\t\treturn \"\", nil\n\t}\n\n\tvar zone string\n\tvar selectedZone string\n\tif s.machineScope.AzureMachine.Spec.AvailabilityZone.ID != nil {\n\t\tzone = *s.machineScope.AzureMachine.Spec.AvailabilityZone.ID\n\t}\n\n\tif zone != \"\" {\n\t\tfor _, allowedZone := range zones {\n\t\t\tif allowedZone == zone {\n\t\t\t\tselectedZone = zone\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\tklog.Infof(\"Selecting first available AZ as no availability zone was set or user-provided availability zone is not supported for VM size %s in location %s\", vmSize, location)\n\t\tselectedZone = zones[0]\n\t}\n\n\tklog.Infof(\"Selected availability zone %s for %s\", selectedZone, vmName)\n\n\treturn selectedZone, nil\n}", "func (bc *Baiducloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\tzone := cloudprovider.Zone{\n\t\tFailureDomain: \"unknow\",\n\t\tRegion: bc.Region,\n\t}\n\tif bc.NodeName != \"\" {\n\t\tins, err := bc.getInstanceByNodeName(ctx, types.NodeName(bc.NodeName))\n\t\t// ins, err := bc.getVirtualMachine(types.NodeName(bc.NodeIP))\n\t\tif err != nil {\n\t\t\treturn zone, err\n\t\t}\n\t\tzone.FailureDomain = ins.AvailableZone\n\t}\n\treturn zone, nil\n}", "func (m *DeleteClusterRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (usaTz uSATimeZones) Mountain() string {return \"America/Denver\" }", "func (m *CreateNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *RollbackNodePoolUpgradeRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *SetNodePoolManagementRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *GetOperationRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (o *SparseSSHAuthority) GetZone() (out int) {\n\n\tif o.Zone == nil {\n\t\treturn\n\t}\n\n\treturn *o.Zone\n}", "func (z zones) GetZone() (cloudprovider.Zone, error) {\n\treturn cloudprovider.Zone{Region: z.region}, nil\n}", "func getDatacenter() string {\n\treturn getFlagOrEnvVar(*datacenter, EnvVarDatacenter)\n}", "func (o *Claims) GetZone() int {\n\n\treturn o.Zone\n}", "func (o RegionAutoscalerOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringOutput { return v.Zone }).(pulumi.StringOutput)\n}", "func (m *SetNodePoolSizeRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *UpdateNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *SetMonitoringServiceRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (canad canadaDeprecatedTimeZones) Mountain() string { return \"America/Edmonton\" }", "func (m *ListOperationsRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *DeleteNodePoolRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (s *EcsService) DescribeZone(id string) (zone map[string]interface{}, err error) {\n\tvar response map[string]interface{}\n\tconn, err := s.client.NewEcsClient()\n\tif err != nil {\n\t\treturn nil, WrapError(err)\n\t}\n\taction := \"DescribeZones\"\n\trequest := map[string]interface{}{\n\t\t\"RegionId\": s.client.RegionId,\n\t}\n\truntime := util.RuntimeOptions{}\n\truntime.SetAutoretry(true)\n\tresponse, err = conn.DoRequest(StringPointer(action), nil, StringPointer(\"POST\"), StringPointer(\"2014-05-26\"), StringPointer(\"AK\"), nil, request, &util.RuntimeOptions{})\n\tif err != nil {\n\t\terr = WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)\n\t\treturn zone, err\n\t}\n\taddDebug(action, response, request)\n\tv, err := jsonpath.Get(\"$.Zones.Zone\", response)\n\tif err != nil {\n\t\treturn zone, WrapErrorf(err, FailedGetAttributeMsg, id, \"$\", response)\n\t}\n\n\tif len(v.([]interface{})) < 1 {\n\t\treturn zone, WrapError(Error(\"There is no any availability zone in region %s.\", s.client.RegionId))\n\t}\n\n\tzoneIds := []string{}\n\tfor _, z := range v.([]interface{}) {\n\t\ttmp := z.(map[string]interface{})\n\t\tif tmp[\"ZoneId\"].(string) == id {\n\t\t\treturn tmp, nil\n\t\t}\n\t\tzoneIds = append(zoneIds, tmp[\"ZoneId\"].(string))\n\t}\n\treturn zone, WrapError(Error(\"availability_zone %s not exists in region %s, all zones are %s\", id, s.client.RegionId, zoneIds))\n}", "func GetClusterDNSDomain() (string, error) {\n\n\t// get configmap from openshift-node namespace\n\n\t// pull out node-config.yaml\n\n\t// pull out dnsDomain value\n\n\t// return it\n\treturn \"cluster.local\", nil\n}", "func (o *SparseClaims) GetZone() (out int) {\n\n\tif o.Zone == nil {\n\t\treturn\n\t}\n\n\treturn *o.Zone\n}", "func (z *zones) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\tklog.V(5).Info(\"GetZone()\")\n\treturn cloudprovider.Zone{\n\t\tFailureDomain: \"laptop\",\n\t\tRegion: \"virtualbox\",\n\t}, nil\n}", "func (client DnsClient) getZone(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/zones/{zoneNameOrId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetZoneResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (m *SetLegacyAbacRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (m *MachineScope) AvailabilitySet() (string, bool) {\n\t// AvailabilitySet service is not supported on EdgeZone currently.\n\tif !m.AvailabilitySetEnabled() || m.ExtendedLocation() != nil {\n\t\treturn \"\", false\n\t}\n\n\tif m.IsControlPlane() {\n\t\treturn azure.GenerateAvailabilitySetName(m.ClusterName(), azure.ControlPlaneNodeGroup), true\n\t}\n\n\t// get machine deployment name from labels for machines that maybe part of a machine deployment.\n\tif mdName, ok := m.Machine.Labels[clusterv1.MachineDeploymentNameLabel]; ok {\n\t\treturn azure.GenerateAvailabilitySetName(m.ClusterName(), mdName), true\n\t}\n\n\t// if machine deployment name label is not available, use machine set name.\n\tif msName, ok := m.Machine.Labels[clusterv1.MachineSetNameLabel]; ok {\n\t\treturn azure.GenerateAvailabilitySetName(m.ClusterName(), msName), true\n\t}\n\n\treturn \"\", false\n}", "func (o GetHostedZoneResultOutput) Region() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetHostedZoneResult) *string { return v.Region }).(pulumi.StringPtrOutput)\n}", "func (o DistributionPolicyZoneConfigurationResponseOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DistributionPolicyZoneConfigurationResponse) string { return v.Zone }).(pulumi.StringOutput)\n}", "func (o LookupRegionNetworkEndpointGroupResultOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRegionNetworkEndpointGroupResult) string { return v.Zone }).(pulumi.StringOutput)\n}", "func (o *ClusterUninstaller) getZoneName(zoneURL string) string {\n\treturn getNameFromURL(\"zones\", zoneURL)\n}", "func (o StorageNodeStatusGeographyOutput) Zone() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageNodeStatusGeography) *string { return v.Zone }).(pulumi.StringPtrOutput)\n}", "func (m *SetAddonsConfigRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (client DnsClient) GetZone(ctx context.Context, request GetZoneRequest) (response GetZoneResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.getZone, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = GetZoneResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = GetZoneResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(GetZoneResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into GetZoneResponse\")\n\t}\n\treturn\n}", "func (o *DnsZoneDataData) GetServerCloud() string {\n\tif o == nil || o.ServerCloud == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ServerCloud\n}", "func (a *Client) GetDatacenter(params *GetDatacenterParams, authInfo runtime.ClientAuthInfoWriter) (*GetDatacenterOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetDatacenterParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getDatacenter\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/dc/{dc}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetDatacenterReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetDatacenterOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*GetDatacenterDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (m *StartIPRotationRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (brazi brazilDeprecatedTimeZones) East() string { return \"America/Sao_Paulo\" }", "func (uSDep uSDeprecatedTimeZones) Mountain() string { return \"America/Denver\" }", "func (s *azureMachineService) isAvailabilityZoneSupported() bool {\n\tazSupported := false\n\n\tfor _, supportedLocation := range azure.SupportedAvailabilityZoneLocations {\n\t\tif s.machineScope.Location() == supportedLocation {\n\t\t\tazSupported = true\n\n\t\t\treturn azSupported\n\t\t}\n\t}\n\n\ts.machineScope.V(2).Info(\"Availability Zones are not supported in the selected location\", \"location\", s.machineScope.Location())\n\treturn azSupported\n}", "func (m *SetNetworkPolicyRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func getRegionFromZone(zoneName string) string {\n\treturn zoneName[:strings.LastIndex(zoneName, \"-\")]\n}", "func (o RecordSetOutput) ManagedZone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RecordSet) pulumi.StringOutput { return v.ManagedZone }).(pulumi.StringOutput)\n}", "func (m *ListNodePoolsRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (s *FastDNSv2Service) GetZone(ctx context.Context, zone string) (*ZoneMetadata, *Response, error) {\n\tu := fmt.Sprintf(\"config-dns/v2/zones/%v\", zone)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar zmeta *ZoneMetadata\n\tresp, err := s.client.Do(ctx, req, &zmeta)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn zmeta, resp, nil\n}", "func (m *CompleteIPRotationRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (o SubnetOutput) AvailabilityZoneId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Subnet) pulumi.StringOutput { return v.AvailabilityZoneId }).(pulumi.StringOutput)\n}", "func Get_server_timezone() (timezone string, err error) {\n\tresp, err := http.Get(\"http://localhost:8001/timezone\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer resp.Body.Close()\n\tvar result TimeZone\n\tjson.NewDecoder(resp.Body).Decode(&result)\n\treturn result.TimeZone, nil\n}", "func getApiServerIpOfZone(ctx context.Context, zone string) string {\n\tvar hostNames []string\n\tapiServerIpInZone := \"\"\n\t// Get Cluster details\n\tclusterComputeResource, _, err := getClusterName(ctx, &e2eVSphere)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tapiServerIPs := GetAndExpectStringEnvVar(apiServerIPs)\n\tapiServerIps := strings.Split(apiServerIPs, \",\")\n\tframework.Logf(\"apiServerIps: %v\", apiServerIps)\n\tclusterName := getClusterNameFromZone(ctx, zone)\n\thostsInCluster := getHostsByClusterName(ctx, clusterComputeResource, clusterName)\n\tfor _, hostObj := range hostsInCluster {\n\t\thostNames = append(hostNames, hostObj.Name())\n\t}\n\tframework.Logf(\"hostNames: %v\", hostNames)\n\tfor _, apiServer := range apiServerIps {\n\t\thost := getHostIpWhereVmIsPresent(apiServer)\n\t\tif isValuePresentInTheList(hostNames, host) {\n\t\t\tframework.Logf(\"Found apiserver in zone: %v\", apiServer)\n\t\t\tapiServerIpInZone = apiServer\n\t\t\tbreak\n\t\t}\n\t}\n\tif apiServerIpInZone == \"\" {\n\t\tframework.Failf(\"couldn't find cluster on zone %s\", zone)\n\t}\n\treturn apiServerIpInZone\n\n}", "func (decryptor *PgDecryptor) GetZoneMatcher() *zone.Matcher {\n\treturn decryptor.zoneMatcher\n}", "func (m *Operation) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func GetZoneInfo(instanceID string) (ZoneInfoStrut, error) {\n\t//-- New Var based on ZoneInfoStrut\n\tzoneInfo := ZoneInfoStrut{}\n\tif instanceID == \"\" {\n\t\treturn zoneInfo, errors.New(\"instanceid not provided\")\n\t}\n\t//-- Get JSON Config\n\ttrans := &http.Transport{Proxy: http.ProxyFromEnvironment}\n\tcl := &http.Client{Transport: trans, Timeout: time.Second * 30}\n\n\treq, err := http.NewRequest(\"GET\", \"https://files.hornbill.com/instances/\"+instanceID+\"/zoneinfo\", nil)\n\tif err != nil {\n\t\tlog.Println(\"Could not make request: \" + err.Error())\n\t\treturn zoneInfo, err\n\t}\n\tresponse, err := cl.Do(req)\n\tif err != nil || response.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error Loading Zone Info File: \" + err.Error())\n\t\t} else {\n\t\t\tlog.Println(\"Unexpected status when attempting to load Zone Info from \" + \"https://files.hornbill.com/instances/\" + instanceID + \"/zoneinfo\" + \" : \" + response.Status)\n\t\t}\n\t\t//-- If we fail fall over to using files.hornbill.co\n\t\treq, err = http.NewRequest(\"GET\", \"https://files.hornbill.co/instances/\"+instanceID+\"/zoneinfo\", nil)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not makre request: \" + err.Error())\n\t\t\treturn zoneInfo, err\n\t\t}\n\t\tresponse, err = cl.Do(req)\n\n\t\t//-- If we still have an error then return out\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error Loading Zone Info File: \" + err.Error())\n\t\t\treturn zoneInfo, err\n\t\t}\n\t}\n\t//-- Close Connection\n\tdefer response.Body.Close()\n\n\t//-- New Decoder\n\tdecoder := json.NewDecoder(response.Body)\n\n\t//-- Decode JSON\n\terrDECODE := decoder.Decode(&zoneInfo)\n\n\t//-- Error Checking\n\tif errDECODE != nil {\n\t\tlog.Println(\"Error Decoding Zone Info File:\", errDECODE.Error())\n\t\treturn zoneInfo, errDECODE\n\t}\n\treturn zoneInfo, nil\n}", "func (ac *azureClient) GetZone(ctx context.Context, resourceGroupName, zoneName string) (privatedns.PrivateZone, error) {\n\tctx, _, done := tele.StartSpanWithLogger(ctx, \"privatedns.AzureClient.GetZone\")\n\tdefer done()\n\tzone, err := ac.privatezones.Get(ctx, resourceGroupName, zoneName)\n\tif err != nil {\n\t\treturn privatedns.PrivateZone{}, err\n\t}\n\treturn zone, nil\n}", "func (m *CancelOperationRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func (o ReservationResponseOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ReservationResponse) string { return v.Zone }).(pulumi.StringOutput)\n}", "func (s *ClusterScope) APIServerHost() string {\n\tif s.IsAPIServerPrivate() {\n\t\treturn azure.GeneratePrivateFQDN(s.GetPrivateDNSZoneName())\n\t}\n\treturn s.APIServerPublicIP().DNSName\n}", "func (s dnsManagedZoneNamespaceLister) Get(name string) (*v1alpha1.DnsManagedZone, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"dnsmanagedzone\"), name)\n\t}\n\treturn obj.(*v1alpha1.DnsManagedZone), nil\n}", "func (a *Amazon) AvailabilityZones() (availabiltyZones []string) {\n\tif a.availabilityZones != nil {\n\t\treturn *a.availabilityZones\n\t}\n\n\tsubnets := a.tarmak.Cluster().Subnets()\n\tzones := make(map[string]bool)\n\n\tfor _, subnet := range subnets {\n\t\tzones[subnet.Zone] = true\n\t}\n\n\ta.availabilityZones = &availabiltyZones\n\n\tfor zone, _ := range zones {\n\t\tavailabiltyZones = append(availabiltyZones, zone)\n\t}\n\n\tsort.Strings(availabiltyZones)\n\n\treturn availabiltyZones\n}", "func (m *SetLabelsRequest) GetZone() string {\n\tif m != nil {\n\t\treturn m.Zone\n\t}\n\treturn \"\"\n}", "func GetZones(sess *session.Session) (*ec2.DescribeAvailabilityZonesOutput, error) {\n svc := ec2.New(sess)\n\n // snippet-start:[ec2.go.regions_and_zones.zones]\n resultAvalZones, err := svc.DescribeAvailabilityZones(nil)\n // snippet-end:[ec2.go.regions_and_zones.zones]\n if err != nil {\n return nil, err\n }\n\n return resultAvalZones, nil\n}", "func (o LookupInstanceResultOutput) Zone() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupInstanceResult) string { return v.Zone }).(pulumi.StringOutput)\n}", "func (o CatalogEntryOutput) Datacenter() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CatalogEntry) pulumi.StringOutput { return v.Datacenter }).(pulumi.StringOutput)\n}", "func (f *Finding) Zone() string {\n\treturn f.badNetwork.JSONPayload.Properties.Location\n}", "func (o StorageNodeStatusGeographyPtrOutput) Zone() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageNodeStatusGeography) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Zone\n\t}).(pulumi.StringPtrOutput)\n}", "func (p *Provider) GetZone(name string) (dns.Zone, error) {\n mZones, err := p.listMZones()\n if err != nil {\n return dns.Zone{}, fmt.Errorf(\"couldn't get zone `%s`, see: failed to list zones, see: %v\", name, err)\n }\n\n var foundZone *models.Zone\n\n for _, z := range mZones {\n if z.Origin != nil && *z.Origin == name {\n foundZone = z\n }\n }\n\n if foundZone == nil {\n return dns.Zone{}, fmt.Errorf(\"zone `%s` not found\", name)\n }\n\n mZone, err := p.getMZone(*foundZone.Origin, foundZone.VirtualNameServer)\n if err != nil {\n return dns.Zone{}, fmt.Errorf(\"couldn't get zone `%s`, see: failed to retrieve zone upstream, see: %v\", name, err)\n }\n\n return p.mapToDNSZone(mZone), nil\n}", "func (o *DnsZoneDataData) GetZoneMasters() string {\n\tif o == nil || o.ZoneMasters == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ZoneMasters\n}" ]
[ "0.6868365", "0.6628795", "0.64997023", "0.6461343", "0.62730974", "0.61088437", "0.61088437", "0.6015124", "0.6014005", "0.6009001", "0.59712696", "0.5803149", "0.5756778", "0.5631765", "0.56188065", "0.5612841", "0.5598365", "0.5534842", "0.5528192", "0.5501342", "0.54538536", "0.5426986", "0.5416631", "0.5386256", "0.53341305", "0.5313907", "0.5294009", "0.52717376", "0.526221", "0.52614284", "0.5238626", "0.5237548", "0.5229884", "0.52059245", "0.51852447", "0.5148974", "0.51213205", "0.51037645", "0.50619525", "0.5035303", "0.5017931", "0.50165266", "0.5016223", "0.50137264", "0.5012244", "0.50057316", "0.49966982", "0.49803987", "0.4976362", "0.49714628", "0.49496028", "0.49338406", "0.49069947", "0.49004632", "0.48868248", "0.4883651", "0.48812148", "0.48658508", "0.4865067", "0.48468232", "0.4837917", "0.48176998", "0.4815296", "0.48062935", "0.4802286", "0.47998238", "0.4798187", "0.4791437", "0.47823903", "0.47799408", "0.47735", "0.47660577", "0.47380188", "0.47357404", "0.47334567", "0.47309208", "0.47292328", "0.47275227", "0.47173688", "0.4716072", "0.47000766", "0.46989104", "0.4693976", "0.46908382", "0.4676661", "0.46706828", "0.4661958", "0.4657123", "0.46476716", "0.4646653", "0.46405137", "0.46307427", "0.46118027", "0.4609453", "0.4605632", "0.45986757", "0.45946708", "0.4582991", "0.45818114", "0.4578299" ]
0.6859813
1
PrivateNetworks returns details about the private networks the server is attached to. Returns YAML (unparsed).
func (c *Client) PrivateNetworks() (string, error) { return c.get("/private-networks") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PrivateNets() []*net.IPNet {\n\treturn privateNets\n}", "func (i *InstanceServiceHandler) ListPrivateNetworks(ctx context.Context, instanceID string, options *ListOptions) ([]PrivateNetwork, *Meta, error) {\n\turi := fmt.Sprintf(\"%s/%s/private-networks\", instancePath, instanceID)\n\treq, err := i.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnewValues, err := query.Values(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq.URL.RawQuery = newValues.Encode()\n\n\tnetworks := new(privateNetworksBase)\n\tif err = i.client.DoWithContext(ctx, req, networks); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn networks.PrivateNetworks, networks.Meta, nil\n}", "func (f *FakeInstance) ListPrivateNetworks(_ context.Context, _ string, _ *govultr.ListOptions) ([]govultr.PrivateNetwork, *govultr.Meta, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func PrivateNetworkInterfaces(logger log.Logger) []string {\n\tints, err := net.Interfaces()\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"error getting network interfaces\", \"err\", err)\n\t}\n\treturn privateNetworkInterfaces(ints, []string{}, logger)\n}", "func (c *Client) CloudInfoNetworkPrivate(projectID string) ([]types.CloudNetwork, error) {\n\tnetwork := []types.CloudNetwork{}\n\terr := c.Get(queryEscape(\"/cloud/project/%s/network/private\", projectID), &network)\n\treturn network, err\n}", "func (d *Discovery) GetPrivatePorts() []uint16 {\n\treturn d.privatePorts\n}", "func ParseListPrivateNetworksResponse(rsp *http.Response) (*ListPrivateNetworksResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ListPrivateNetworksResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest struct {\n\t\t\tPrivateNetworks *[]PrivateNetwork `json:\"private-networks,omitempty\"`\n\t\t}\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (o *LinkPrivateIpsRequest) GetPrivateIps() []string {\n\tif o == nil || o.PrivateIps == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIps\n}", "func (c *ClientWithResponses) ListPrivateNetworksWithResponse(ctx context.Context) (*ListPrivateNetworksResponse, error) {\n\trsp, err := c.ListPrivateNetworks(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseListPrivateNetworksResponse(rsp)\n}", "func (a *Adapter) PrivateSubnetIDs() []string {\n\treturn getSubnetIDs(a.manifest.privateSubnets)\n}", "func flattenPrivateCloudNetworkConfig(c *Client, i interface{}, res *PrivateCloud) *PrivateCloudNetworkConfig {\n\tm, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tr := &PrivateCloudNetworkConfig{}\n\n\tif dcl.IsEmptyValueIndirect(i) {\n\t\treturn EmptyPrivateCloudNetworkConfig\n\t}\n\tr.ManagementCidr = dcl.FlattenString(m[\"managementCidr\"])\n\tr.VmwareEngineNetwork = dcl.FlattenString(m[\"vmwareEngineNetwork\"])\n\tr.VmwareEngineNetworkCanonical = dcl.FlattenString(m[\"vmwareEngineNetworkCanonical\"])\n\tr.ManagementIPAddressLayoutVersion = dcl.FlattenInteger(m[\"managementIpAddressLayoutVersion\"])\n\n\treturn r\n}", "func TestGetServerNetworks(t *testing.T) {\n\trecord(t, \"getservernetworks\", func(t *testing.T, svc *Service) {\n\t\tserverDetails, err := createServer(svc, \"TestGetServerNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworking, err := svc.GetServerNetworks(&request.GetServerNetworksRequest{\n\t\t\tServerUUID: serverDetails.UUID,\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tsdNetworking := upcloud.Networking(serverDetails.Networking)\n\t\tassert.Equal(t, &sdNetworking, networking)\n\t})\n}", "func (n NetworkMode) IsPrivate() bool {\n\treturn !(n.IsHost() || n.IsContainer())\n}", "func (o AiEndpointDeployedModelOutput) PrivateEndpoints() AiEndpointDeployedModelPrivateEndpointArrayOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModel) []AiEndpointDeployedModelPrivateEndpoint { return v.PrivateEndpoints }).(AiEndpointDeployedModelPrivateEndpointArrayOutput)\n}", "func (o *PublicIp) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\n}", "func (o *PublicIp) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\n}", "func (provider *NetconfServiceProvider) GetPrivate() interface{} {\n\treturn provider.Private\n}", "func (pl *Peerlist) GetPrivateAddresses() []string {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\treturn pl.getAddresses(true)\n}", "func (o DatabaseReplicaOutput) PrivateNetworkUuid() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringOutput { return v.PrivateNetworkUuid }).(pulumi.StringOutput)\n}", "func (o ElastigroupNetworkInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupNetworkInterface) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o NetworkInterfaceOutput) SecondaryPrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.StringArrayOutput { return v.SecondaryPrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o *InlineResponse20049Post) GetPrivate() string {\n\tif o == nil || o.Private == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func (o *InlineResponse200115) GetPrivate() string {\n\tif o == nil || o.Private == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func NewListPrivateNetworksRequest(server string) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/private-network\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (o GetLBFrontendIpConfigurationOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLBFrontendIpConfiguration) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func (o NetworkInterfaceOutput) PrivateIpAddresses() NetworkInterfacePrivateIpAddressSpecificationArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) NetworkInterfacePrivateIpAddressSpecificationArrayOutput {\n\t\treturn v.PrivateIpAddresses\n\t}).(NetworkInterfacePrivateIpAddressSpecificationArrayOutput)\n}", "func (o *InlineResponse20033Milestones) GetPrivate() bool {\n\tif o == nil || o.Private == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func (d *Dry) ShowNetworks() {\n\tif networks, err := d.dockerDaemon.Networks(); err == nil {\n\t\td.changeViewMode(Networks)\n\t\td.networks = networks\n\t} else {\n\t\td.appmessage(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Could not retrieve network list: %s \", err.Error()))\n\t}\n}", "func (o *LinkPublicIpRequest) GetPrivateIp() string {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateIp\n}", "func (o GetServiceAdditionalLocationOutput) PrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetServiceAdditionalLocation) []string { return v.PrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o ResourceManagementPrivateLinkEndpointConnectionsResponseOutput) PrivateEndpointConnections() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ResourceManagementPrivateLinkEndpointConnectionsResponse) []string {\n\t\treturn v.PrivateEndpointConnections\n\t}).(pulumi.StringArrayOutput)\n}", "func (s *ClusterScope) PrivateEndpointSpecs() []azure.ResourceSpecGetter {\n\tnumberOfSubnets := len(s.AzureCluster.Spec.NetworkSpec.Subnets)\n\tif s.IsAzureBastionEnabled() {\n\t\tnumberOfSubnets++\n\t}\n\n\tprivateEndpointSpecs := make([]azure.ResourceSpecGetter, 0, numberOfSubnets)\n\n\tsubnets := s.AzureCluster.Spec.NetworkSpec.Subnets\n\tif s.IsAzureBastionEnabled() {\n\t\tsubnets = append(subnets, s.AzureCluster.Spec.BastionSpec.AzureBastion.Subnet)\n\t}\n\n\tfor _, subnet := range subnets {\n\t\tprivateEndpointSpecs = append(privateEndpointSpecs, s.getPrivateEndpoints(subnet)...)\n\t}\n\n\treturn privateEndpointSpecs\n}", "func (o *LinkPrivateIpsRequest) SetPrivateIps(v []string) {\n\to.PrivateIps = &v\n}", "func (o NetworkInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.StringPtrOutput { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o ServiceAdditionalLocationOutput) PrivateIpAddresses() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ServiceAdditionalLocation) []string { return v.PrivateIpAddresses }).(pulumi.StringArrayOutput)\n}", "func (o RouterInterfaceResponseOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterInterfaceResponse) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func (o LinkServiceNatIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LinkServiceNatIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o *InlineResponse20033Milestones) SetPrivate(v bool) {\n\to.Private = &v\n}", "func (o ResourceManagementPrivateLinkEndpointConnectionsResponsePtrOutput) PrivateEndpointConnections() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ResourceManagementPrivateLinkEndpointConnectionsResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PrivateEndpointConnections\n\t}).(pulumi.StringArrayOutput)\n}", "func NewPrivateDiscoverer() Discoverer {\n\treturn NewDiscoverer(\n\t\tPublicIPv4DiscovererOption(privatePublicIPv4),\n\t\tPublicIPv6DiscovererOption(privatePublicIPv6),\n\t)\n}", "func (p *Plan) GetPrivateRepos() int {\n\tif p == nil || p.PrivateRepos == nil {\n\t\treturn 0\n\t}\n\treturn *p.PrivateRepos\n}", "func (o *InlineResponse20049Post) SetPrivate(v string) {\n\to.Private = &v\n}", "func (o GetResolverInboundEndpointIpConfigurationOutput) PrivateIpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResolverInboundEndpointIpConfiguration) string { return v.PrivateIpAddress }).(pulumi.StringOutput)\n}", "func (o *InlineResponse20051TodoItems) GetPrivate() string {\n\tif o == nil || o.Private == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func (o *InlineResponse20027Person) GetPrivateNotes() string {\n\tif o == nil || o.PrivateNotes == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PrivateNotes\n}", "func (o *InlineResponse20034Milestone) GetPrivate() bool {\n\tif o == nil || o.Private == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func (n *Networks) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tvar sliceType []string\n\tif err := unmarshal(&sliceType); err == nil {\n\t\tfor _, name := range sliceType {\n\t\t\tn.Networks = append(n.Networks, &Network{\n\t\t\t\tName: name,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar mapType map[string]*Network\n\tif err := unmarshal(&sliceType); err != nil {\n\t\treturn err\n\t}\n\tfor name, network := range mapType {\n\t\tnetwork.Name = name\n\t\tn.Networks = append(n.Networks, network)\n\t}\n\treturn nil\n}", "func (o *InlineResponse20034Milestone) SetPrivate(v bool) {\n\to.Private = &v\n}", "func (o *InlineResponse200115) SetPrivate(v string) {\n\to.Private = &v\n}", "func (o *PublicIp) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (o *PublicIp) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (t *TeamDiscussion) GetPrivate() bool {\n\tif t == nil || t.Private == nil {\n\t\treturn false\n\t}\n\treturn *t.Private\n}", "func TestPrivateDns2(t *testing.T) {\n\tnewIntegrationTest(\"privatedns2.example.com\", \"privatedns2\").\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\twithPrivate().\n\t\trunTestTerraformAWS(t)\n}", "func (n UsernsMode) IsPrivate() bool {\n\treturn !n.IsHost()\n}", "func TestGetNetworks(t *testing.T) {\n\trecord(t, \"getnetworks\", func(t *testing.T, svc *Service) {\n\t\t_, err := createServer(svc, \"TestGetNetworks\")\n\t\trequire.NoError(t, err)\n\n\t\tnetworks, err := svc.GetNetworks()\n\t\trequire.NoError(t, err)\n\n\t\tassert.NotEmpty(t, networks.Networks)\n\n\t\tassert.NotEmpty(t, networks.Networks[0].IPNetworks)\n\t\tassert.NotEmpty(t, networks.Networks[0].Name)\n\t\tassert.NotEmpty(t, networks.Networks[0].Type)\n\t\tassert.NotEmpty(t, networks.Networks[0].UUID)\n\t\tassert.NotEmpty(t, networks.Networks[0].Zone)\n\n\t\t// Find a network with a server\n\t\tvar found bool\n\t\tfor _, n := range networks.Networks {\n\t\t\tif len(n.Servers) > 0 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tassert.True(t, found)\n\t})\n}", "func (pl *Peerlist) GetPrivateTrustPeers() []Peer {\n\tpl.lock.RLock()\n\tdefer pl.lock.RUnlock()\n\n\taddrs := pl.getTrustedAddresses(true)\n\treturn copyPeers(pl.peers, addrs)\n}", "func (o RouterInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterInterface) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o LoadBalancerFrontendIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LoadBalancerFrontendIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (s *ClusterScope) APIServerPrivateIP() string {\n\treturn s.APIServerLB().FrontendIPs[0].PrivateIPAddress\n}", "func GetPrivateInfo(ctx context.Context, privateKeyDir string) (*ServerPrivateInfo, error) {\n\tsPriv, err := cryptoio.ReadStandardPrivateKey(ctx, &cryptoio.ReadStandardPrivateKeyParams{FilePath: path.Join(privateKeyDir, cryptoio.DefaultStandardPrivateKey)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tePriv, err := cryptoio.ReadElGamalPrivateKey(path.Join(privateKeyDir, cryptoio.DefaultElgamalPrivateKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret, err := cryptoio.ReadElGamalSecret(path.Join(privateKeyDir, cryptoio.DefaultElgamalSecret))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ServerPrivateInfo{\n\t\tStandardPrivateKey: sPriv,\n\t\tElGamalPrivateKey: ePriv,\n\t\tSecret: secret,\n\t}, nil\n}", "func (o *LinkPublicIpRequest) SetPrivateIp(v string) {\n\to.PrivateIp = &v\n}", "func (o ResolverInboundEndpointIpConfigurationOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResolverInboundEndpointIpConfiguration) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (o *ViewMilestone) SetPrivate(v bool) {\n\to.Private = &v\n}", "func (um *UserManager) GetPrivateIPFSNetworksForUser(username string) ([]string, error) {\n\tu, err := um.FindByUserName(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u.IPFSNetworkNames, nil\n}", "func (o *InlineResponse20051TodoItems) SetPrivate(v string) {\n\to.Private = &v\n}", "func ParseGetPrivateNetworkResponse(rsp *http.Response) (*GetPrivateNetworkResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &GetPrivateNetworkResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest PrivateNetwork\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func privateNetworkInterfaces(all []net.Interface, fallback []string, logger log.Logger) []string {\n\tvar privInts []string\n\tfor _, i := range all {\n\t\taddrs, err := getInterfaceAddrs(&i)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"error getting addresses from network interface\", \"interface\", i.Name, \"err\", err)\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\ts := a.String()\n\t\t\tip, _, err := net.ParseCIDR(s)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Warn(logger).Log(\"msg\", \"error parsing network interface IP address\", \"interface\", i.Name, \"addr\", s, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ip.IsPrivate() {\n\t\t\t\tprivInts = append(privInts, i.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif len(privInts) == 0 {\n\t\treturn fallback\n\t}\n\treturn privInts\n}", "func (c CgroupnsMode) IsPrivate() bool {\n\treturn c == CgroupnsModePrivate\n}", "func flattenPrivateCloudNetworkConfigMap(c *Client, i interface{}, res *PrivateCloud) map[string]PrivateCloudNetworkConfig {\n\ta, ok := i.(map[string]interface{})\n\tif !ok {\n\t\treturn map[string]PrivateCloudNetworkConfig{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn map[string]PrivateCloudNetworkConfig{}\n\t}\n\n\titems := make(map[string]PrivateCloudNetworkConfig)\n\tfor k, item := range a {\n\t\titems[k] = *flattenPrivateCloudNetworkConfig(c, item.(map[string]interface{}), res)\n\t}\n\n\treturn items\n}", "func (c *Client) PrivateChannels() ([]discord.Channel, error) {\n\tvar dms []discord.Channel\n\treturn dms, c.RequestJSON(&dms, \"GET\", EndpointMe+\"/channels\")\n}", "func (i *InstanceServiceHandler) DetachPrivateNetwork(ctx context.Context, instanceID, networkID string) error {\n\turi := fmt.Sprintf(\"%s/%s/private-networks/detach\", instancePath, instanceID)\n\tbody := RequestBody{\"network_id\": networkID}\n\n\treq, err := i.client.NewRequest(ctx, http.MethodPost, uri, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.client.DoWithContext(ctx, req, nil)\n}", "func (o *InlineResponse20027Person) SetPrivateNotes(v string) {\n\to.PrivateNotes = &v\n}", "func (p *PushEventRepository) GetPrivate() bool {\n\tif p == nil || p.Private == nil {\n\t\treturn false\n\t}\n\treturn *p.Private\n}", "func NewMockPrivateNetworkDetector(ctrl *gomock.Controller) *MockPrivateNetworkDetector {\n\tmock := &MockPrivateNetworkDetector{ctrl: ctrl}\n\tmock.recorder = &MockPrivateNetworkDetectorMockRecorder{mock}\n\treturn mock\n}", "func (c *Container) GetPrivateAddress(t *testing.T) string {\n\tcontainer := c.parentContainer\n\tif container == \"\" {\n\t\tcontainer = c.container\n\t}\n\tresult := icmd.RunCommand(dockerCli.path, \"inspect\", container, \"-f\", \"{{.NetworkSettings.IPAddress}}\").Assert(t, icmd.Success)\n\treturn fmt.Sprintf(\"%s:%d\", strings.TrimSpace(result.Stdout()), c.privatePort)\n}", "func IsPrivateBlockchain() bool {\r\n\tpar := SysString(PrivateBlockchain)\r\n\treturn len(par) > 0 && par != `0` && par != `false`\r\n}", "func IsPrivateSubnet(ipaddr net.IP) bool {\n\tif ip := ipaddr.To4(); ip != nil {\n\t\tfor _, r := range privateRanges {\n\t\t\tif inRange(r, ip) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *GetClientConfig200ResponseDenylist) GetNetworks() GetClientConfig200ResponseNetworks1 {\n\tif o == nil || o.Networks == nil {\n\t\tvar ret GetClientConfig200ResponseNetworks1\n\t\treturn ret\n\t}\n\treturn *o.Networks\n}", "func (r *reader) GetDNSOverTLSPrivateAddresses() (privateAddresses []string, err error) {\n\ts, err := r.envParams.GetEnv(\"DOT_PRIVATE_ADDRESS\")\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(s) == 0 {\n\t\treturn nil, nil\n\t}\n\tprivateAddresses = strings.Split(s, \",\")\n\tfor _, address := range privateAddresses {\n\t\tip := net.ParseIP(address)\n\t\t_, _, err := net.ParseCIDR(address)\n\t\tif ip == nil && err != nil {\n\t\t\treturn nil, fmt.Errorf(\"private address %q is not a valid IP or CIDR range\", address)\n\t\t}\n\t}\n\treturn privateAddresses, nil\n}", "func isPrivateSubnet(ips string) bool {\n\tip := net.ParseIP(ips)\n\tfor _, r := range privateCIDRs {\n\t\tif r.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func flattenPrivateCloudNetworkConfigSlice(c *Client, i interface{}, res *PrivateCloud) []PrivateCloudNetworkConfig {\n\ta, ok := i.([]interface{})\n\tif !ok {\n\t\treturn []PrivateCloudNetworkConfig{}\n\t}\n\n\tif len(a) == 0 {\n\t\treturn []PrivateCloudNetworkConfig{}\n\t}\n\n\titems := make([]PrivateCloudNetworkConfig, 0, len(a))\n\tfor _, item := range a {\n\t\titems = append(items, *flattenPrivateCloudNetworkConfig(c, item.(map[string]interface{}), res))\n\t}\n\n\treturn items\n}", "func (o *LinkPrivateIpsRequest) GetPrivateIpsOk() (*[]string, bool) {\n\tif o == nil || o.PrivateIps == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateIps, true\n}", "func (u *Unifi) Networks(site *Site) ([]Network, error) {\n\tvar response struct {\n\t\tData []Network\n\t\tMeta meta\n\t}\n\terr := u.parse(site, \"rest/networkconf\", nil, &response)\n\treturn response.Data, err\n}", "func (o *PublicIp) GetPrivateIpOk() (string, bool) {\n\tif o == nil || o.PrivateIp == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.PrivateIp, true\n}", "func (o *InlineResponse20049Post) GetPrivateOk() (*string, bool) {\n\tif o == nil || o.Private == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Private, true\n}", "func (ctx *DevModelParallels) Networks() []*config.NetworkConfig {\n\treturn ctx.networks\n}", "func (s UserSet) WebReadGroupPrivate(params webtypes.WebReadGroupParams) []models.FieldMap {\n\tres := s.Collection().Call(\"WebReadGroupPrivate\", params)\n\tresTyped, _ := res.([]models.FieldMap)\n\treturn resTyped\n}", "func (config *Config) getPrivateDockerRegistries() error {\n\tcredentials, ok := os.LookupEnv(\"securedRegistries.json\")\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot find Private Docker Registries: environment variable securedRegistries not found\")\n\t}\n\n\tprivateDockerRegistries := map[string]*common.RegistryAuth{}\n\terr := json.Unmarshal([]byte(credentials), &privateDockerRegistries)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to unmarshall Private Docker registries due to %+v\", err)\n\t}\n\n\tdockerRegistries := []*common.RegistryAuth{}\n\tfor _, privatedockerRegistry := range privateDockerRegistries {\n\t\tdockerRegistries = append(dockerRegistries, privatedockerRegistry)\n\t}\n\n\tconfig.ImageFacade.PrivateDockerRegistries = dockerRegistries\n\n\treturn nil\n}", "func (o EcsLaunchTemplateOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringPtrOutput { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func expandPrivateCloudNetworkConfig(c *Client, f *PrivateCloudNetworkConfig, res *PrivateCloud) (map[string]interface{}, error) {\n\tif dcl.IsEmptyValueIndirect(f) {\n\t\treturn nil, nil\n\t}\n\n\tm := make(map[string]interface{})\n\tif v := f.ManagementCidr; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"managementCidr\"] = v\n\t}\n\tif v := f.VmwareEngineNetwork; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"vmwareEngineNetwork\"] = v\n\t}\n\n\treturn m, nil\n}", "func (g *Gossiper) ExportPrivateFiles() string {\n\tobj, e := json.MarshalIndent(g.PrivFiles, \"\", \"\\t\")\n\tutils.HandleError(e)\n\tfmt.Printf(\"Exported the following state: %+v\\n\", string(obj))\n\treturn string(obj)\n}", "func (m *MainWindow) hidePrivateAllServers() {\n\tfmt.Println(\"(Un)Hiding private servers in 'Servers' tab...\")\n\tif m.all_servers_hide_private.GetActive() {\n\t\tctx.Cfg.Cfg[\"/serverslist/all_servers/hide_private\"] = \"1\"\n\t} else {\n\t\tctx.Cfg.Cfg[\"/serverslist/all_servers/hide_private\"] = \"0\"\n\t}\n\tctx.Eventer.LaunchEvent(\"loadAllServers\", map[string]string{})\n}", "func (n PidMode) IsPrivate() bool {\n\treturn !(n.IsHost() || n.IsContainer())\n}", "func (e *Domain) Private() *PrivateKey {\n\tif e.ClearPrivateKey == nil {\n\t\te.decrypt_privatekey()\n\t}\n\treturn e.ClearPrivateKey\n}", "func onlyPrivate(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPrivateAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t\tlog.Debugf(\"\\tprivate - %s\\n\", addr.String())\n\t\t} else {\n\t\t\tlog.Debugf(\"\\tpublic - %s\\n\", addr.String())\n\t\t}\n\t}\n\treturn routable\n}", "func (n UTSMode) IsPrivate() bool {\n\treturn !n.IsHost()\n}", "func (o *PublicIp) GetPrivateIpOk() (*string, bool) {\n\tif o == nil || o.PrivateIp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrivateIp, true\n}", "func (o *ViewMilestone) GetPrivate() bool {\n\tif o == nil || o.Private == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Private\n}", "func (o InstanceOutput) IngressPrivateIp() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.IngressPrivateIp }).(pulumi.StringOutput)\n}", "func (client *AwsClientWrapper) GetPrivateIP(machine *clusterv1alpha1.Machine) (string, error) {\n\tinstance, err := getRunningInstance(machine, client.client)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif *instance.PrivateIpAddress == \"\" {\n\t\treturn \"\", fmt.Errorf(\"machine instance public DNS name not set\")\n\t}\n\n\treturn *instance.PrivateIpAddress, nil\n}" ]
[ "0.6852663", "0.64793926", "0.64706045", "0.6240507", "0.5949046", "0.58666754", "0.5787277", "0.56575096", "0.56419754", "0.5515053", "0.54796916", "0.5463644", "0.5424667", "0.53876376", "0.5366295", "0.5366295", "0.5332467", "0.52825356", "0.52755636", "0.5262584", "0.5258215", "0.52355665", "0.52339876", "0.5183993", "0.5179704", "0.5170675", "0.51699144", "0.51685953", "0.5159436", "0.5156155", "0.51487756", "0.51348674", "0.5132852", "0.51124746", "0.5103021", "0.507708", "0.50489527", "0.5044536", "0.5015013", "0.5010708", "0.49732473", "0.49631494", "0.49612707", "0.49581483", "0.4953864", "0.49482268", "0.49430215", "0.49422178", "0.49061155", "0.49049428", "0.49049428", "0.48805946", "0.487133", "0.48689047", "0.4865447", "0.48436233", "0.48434407", "0.48367715", "0.48161533", "0.48160565", "0.4814074", "0.47998136", "0.47979537", "0.47936887", "0.47651333", "0.47513166", "0.4744403", "0.47422728", "0.47351003", "0.47290492", "0.47274345", "0.47117686", "0.46992555", "0.46937647", "0.46923766", "0.46915844", "0.46825", "0.4682061", "0.46771568", "0.4666487", "0.4658563", "0.46542576", "0.46523654", "0.464986", "0.46435413", "0.46310112", "0.46217278", "0.46208748", "0.4619457", "0.4618248", "0.46146545", "0.4613005", "0.46102324", "0.46066388", "0.45954126", "0.4590379", "0.45763373", "0.4572353", "0.45723212", "0.45677885" ]
0.7987788
0
ReadPackageLead reads the deprecated lead section of an RPM file which is used in legacy RPM versions to store package metadata. This function should only be used if you intend to read a package lead in isolation.
func ReadPackageLead(r io.Reader) (*Lead, error) { // read bytes b := make([]byte, 96) n, err := r.Read(b) if err != nil { return nil, err } // check length if n != 96 { return nil, ErrBadLeadLength } // check magic number if 0 != bytes.Compare(b[:4], []byte{0xED, 0xAB, 0xEE, 0xDB}) { return nil, ErrNotRPMFile } // decode lead lead := &Lead{ VersionMajor: int(b[4]), VersionMinor: int(b[5]), Type: int(binary.BigEndian.Uint16(b[6:8])), Architecture: int(binary.BigEndian.Uint16(b[8:10])), Name: string(b[10:76]), OperatingSystem: int(binary.BigEndian.Uint16(b[76:78])), SignatureType: int(binary.BigEndian.Uint16(b[78:80])), } // check version if lead.VersionMajor < 3 || lead.VersionMajor > 4 { return nil, ErrUnsupportedVersion } // TODO: validate lead value ranges return lead, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetLead(i bson.ObjectId) (*lead, error) {\n\tvar l lead\n\terr := config.LeadsCollection.FindId(i).One(&l)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &l, nil\n}", "func (c *Client) GetCrmLeadTag(id int64) (*CrmLeadTag, error) {\n\tclts, err := c.GetCrmLeadTags([]int64{id})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif clts != nil && len(*clts) > 0 {\n\t\treturn &((*clts)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"id %v of crm.lead.tag not found\", id)\n}", "func ReadAltitudeHoldModeEngaged(data []byte) AltitudeHoldModeEngaged {\n\tbits := (data[6] & 0x40) >> 6\n\treturn AltitudeHoldModeEngaged(bits)\n}", "func ReadCertAuthorityPackage(packages pack.PackageService, clusterName string) (utils.TLSArchive, error) {\n\tcaPackage := PlanetCertAuthorityPackage(clusterName)\n\t_, reader, err := packages.ReadPackage(caPackage)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tdefer reader.Close()\n\treturn utils.ReadTLSArchive(reader)\n}", "func (c *Client) FindCrmLeadTag(criteria *Criteria) (*CrmLeadTag, error) {\n\tclts := &CrmLeadTags{}\n\tif err := c.SearchRead(CrmLeadTagModel, criteria, NewOptions().Limit(1), clts); err != nil {\n\t\treturn nil, err\n\t}\n\tif clts != nil && len(*clts) > 0 {\n\t\treturn &((*clts)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"crm.lead.tag was not found with criteria %v\", criteria)\n}", "func readModuleDeps(ctx context.Context) (map[string][]string, error) {\n\tb, err := testexec.CommandContext(ctx, \"lsmod\").Output(testexec.DumpLogOnError)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to read modules\")\n\t}\n\tmods := strings.Split(strings.TrimSpace(string(b)), \"\\n\")\n\t// Validity check.\n\tif !strings.HasPrefix(mods[0], \"Module \") {\n\t\treturn nil, errors.Errorf(\"unexpected header %q\", mods[0])\n\t}\n\n\tres := make(map[string][]string)\n\tfor _, m := range mods[1:] {\n\t\tif fs := strings.Fields(m); len(fs) == 3 {\n\t\t\tres[fs[0]] = nil\n\t\t} else if len(fs) == 4 {\n\t\t\tres[fs[0]] = strings.Split(fs[3], \",\")\n\t\t} else {\n\t\t\treturn nil, errors.Errorf(\"malformed module line %q\", m)\n\t\t}\n\t}\n\treturn res, nil\n}", "func (ref OpenDB) ParseLEFLibrary(filepath string) (err error) {\n\trc := C.ReadLib(ref.db, C.CString(filepath), C.CString(generateLibraryName(filepath)))\n\tif rc != 0 {\n\t\tcErr := C.GoString(C.LastError)\n\t\tif len(cErr) > 0 {\n\t\t\terr = fmt.Errorf(\"%v\", C.GoString(C.LastError))\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Unknown error has occured\")\n\t\t}\n\t}\n\treturn\n}", "func (db *DB) getModuleReadme(ctx context.Context, modulePath, resolvedVersion string) (_ *internal.Readme, err error) {\n\tdefer derrors.Wrap(&err, \"getModuleReadme(ctx, %q, %q)\", modulePath, resolvedVersion)\n\tvar readme internal.Readme\n\terr = db.db.QueryRow(ctx, `\n\t\tSELECT file_path, contents\n\t\tFROM modules m\n\t\tINNER JOIN units p\n\t\tON p.module_id = m.id\n\t\tINNER JOIN readmes r\n\t\tON p.id = r.path_id\n\t\tWHERE\n\t\t m.module_path=$1\n\t\t\tAND m.version=$2\n\t\t\tAND m.module_path=p.path`, modulePath, resolvedVersion).Scan(&readme.Filepath, &readme.Contents)\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\treturn nil, derrors.NotFound\n\tcase nil:\n\t\treturn &readme, nil\n\tdefault:\n\t\treturn nil, err\n\t}\n}", "func ReadPassward(directory string) (*Passward, error) {\n\tvar pw Passward\n\tdirectory, err := filepath.Abs(directory)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigPath := filepath.Join(directory, \"config.toml\")\n\t_, err = toml.DecodeFile(configPath, &pw)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpw.Path = directory // in case it was moved\n\tpw.vaults, err = ReadAllVaults(pw.vaultPath(), pw.GetCredentials())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif pw.SelectedVault != \"\" {\n\t\tpw.UseVault(pw.SelectedVault)\n\t}\n\n\treturn &pw, nil\n}", "func (pm *ProductMetadata) DCLPackage() string {\n\treturn strings.Replace(pm.PackagePath, \"_\", \"\", -1)\n}", "func (s *mdServerTlfStorage) getMDReadLocked(id kbfsmd.ID) (\n\t*RootMetadataSigned, error) {\n\t// Read file.\n\n\tvar srmds serializedRMDS\n\terr := kbfscodec.DeserializeFromFile(s.codec, s.mdPath(id), &srmds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trmds, err := DecodeRootMetadataSigned(\n\t\ts.codec, s.tlfID, srmds.Version, s.mdVer, srmds.EncodedRMDS,\n\t\tsrmds.Timestamp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check integrity.\n\n\tmdID, err := kbfsmd.MakeID(s.codec, rmds.MD)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif id != mdID {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Metadata ID mismatch: expected %s, got %s\",\n\t\t\tid, mdID)\n\t}\n\n\treturn rmds, nil\n}", "func parsePackageLock(_ string, reader io.Reader) ([]pkg.Package, error) {\n\tpackages := make([]pkg.Package, 0)\n\tdec := json.NewDecoder(reader)\n\n\tfor {\n\t\tvar lock PackageLock\n\t\tif err := dec.Decode(&lock); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse package-lock.json file: %w\", err)\n\t\t}\n\t\tfor name, pkgMeta := range lock.Dependencies {\n\t\t\tpackages = append(packages, pkg.Package{\n\t\t\t\tName: name,\n\t\t\t\tVersion: pkgMeta.Version,\n\t\t\t\tLanguage: pkg.JavaScript,\n\t\t\t\tType: pkg.NpmPkg,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn packages, nil\n}", "func (haa *HistoryArchiveAdapter) GetLedger(sequence uint32) (io.ArchiveLedgerReader, error) {\n\treturn nil, fmt.Errorf(\"not implemented yet\")\n}", "func Read(b []byte) (Feedback, error) {\n\tvar f Feedback\n\n\ts := string(b[:])\n\n\t// It seems that some vendors has a broken schema tag added. Its not closed and should not be there\n\t// So this is a hack to remove it\n\tif !matchschema.MatchString(s) {\n\t\ts = brokenschema.ReplaceAllString(string(b[:]), \"\")\n\t}\n\n\tif err := xml.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn Feedback{}, err\n\t}\n\treturn f, nil\n}", "func (oa *offsetAdmin) GetOffsetLag(partition int32) (groupOffset int64, partitionLag int64, err error) {\n\tif !oa.Valid() {\n\t\terr = fmt.Errorf(\"No specified Group and/or Topic\")\n\t\treturn\n\t}\n\toa.om, err = sarama.NewOffsetManagerFromClient(oa.grp, oa.client)\n\tif err != nil {\n\t\treturn\n\t}\n\toa.pom, err = oa.om.ManagePartition(oa.top, partition)\n\tif err != nil {\n\t\treturn\n\t}\n\tgroupOffset, _ = oa.pom.NextOffset()\n\tpartOffset, err := oa.client.GetOffset(oa.top, partition, sarama.OffsetNewest)\n\tif err != nil {\n\t\treturn\n\t}\n\tif groupOffset == -1 {\n\t\tgroupOffset = partOffset\n\t}\n\tpartitionLag = (partOffset - groupOffset)\n\toa.om.Close()\n\toa.pom.Close()\n\treturn\n}", "func readModuleName() (string, error) {\n\tmodFile, err := os.Open(\"./go.mod\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer modFile.Close()\n\tscanner := bufio.NewScanner(modFile)\n\tfor scanner.Scan() {\n\t\tpieces := strings.Split(scanner.Text(), \" \")\n\t\tfmt.Printf(\"FOund pieces as %+v\\n\", pieces)\n\t\tif len(pieces) >= 2 && pieces[0] == \"module\" {\n\t\t\treturn pieces[1], nil\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func GetTRBLeadInfo(ctx context.Context, trbLead *string) (*models.UserInfo, error) {\n\tvar trbLeadInfo *models.UserInfo\n\tif trbLead != nil {\n\t\tinfo, err := dataloaders.GetUserInfo(ctx, *trbLead)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttrbLeadInfo = info\n\t}\n\n\tif trbLeadInfo == nil {\n\t\ttrbLeadInfo = &models.UserInfo{}\n\t}\n\n\treturn trbLeadInfo, nil\n}", "func ReadLedgerMarker(row *sql.Row, a *LedgerMarker) error {\n\terr := row.Scan(&a.LMID, &a.LID, &a.BID, &a.RAID, &a.RID, &a.TCID, &a.Dt, &a.Balance, &a.State, &a.CreateTS, &a.CreateBy, &a.LastModTime, &a.LastModBy)\n\tSkipSQLNoRowsError(&err)\n\treturn err\n}", "func ParsePackage(r io.Reader) (*Package, error) {\n\trpm, err := rpmutils.ReadRpm(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnevra, err := rpm.Header.GetNEVRA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tversion := fmt.Sprintf(\"%s-%s\", nevra.Version, nevra.Release)\n\tif nevra.Epoch != \"\" && nevra.Epoch != \"0\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", nevra.Epoch, version)\n\t}\n\n\tp := &Package{\n\t\tName: nevra.Name,\n\t\tVersion: version,\n\t\tVersionMetadata: &VersionMetadata{\n\t\t\tSummary: getString(rpm.Header, rpmutils.SUMMARY),\n\t\t\tDescription: getString(rpm.Header, rpmutils.DESCRIPTION),\n\t\t\tLicense: getString(rpm.Header, rpmutils.LICENSE),\n\t\t\tProjectURL: getString(rpm.Header, rpmutils.URL),\n\t\t},\n\t\tFileMetadata: &FileMetadata{\n\t\t\tArchitecture: nevra.Arch,\n\t\t\tEpoch: nevra.Epoch,\n\t\t\tVersion: nevra.Version,\n\t\t\tRelease: nevra.Release,\n\t\t\tVendor: getString(rpm.Header, rpmutils.VENDOR),\n\t\t\tGroup: getString(rpm.Header, rpmutils.GROUP),\n\t\t\tPackager: getString(rpm.Header, rpmutils.PACKAGER),\n\t\t\tSourceRpm: getString(rpm.Header, rpmutils.SOURCERPM),\n\t\t\tBuildHost: getString(rpm.Header, rpmutils.BUILDHOST),\n\t\t\tBuildTime: getUInt64(rpm.Header, rpmutils.BUILDTIME),\n\t\t\tFileTime: getUInt64(rpm.Header, rpmutils.FILEMTIMES),\n\t\t\tInstalledSize: getUInt64(rpm.Header, rpmutils.SIZE),\n\t\t\tArchiveSize: getUInt64(rpm.Header, rpmutils.SIG_PAYLOADSIZE),\n\n\t\t\tProvides: getEntries(rpm.Header, rpmutils.PROVIDENAME, rpmutils.PROVIDEVERSION, rpmutils.PROVIDEFLAGS),\n\t\t\tRequires: getEntries(rpm.Header, rpmutils.REQUIRENAME, rpmutils.REQUIREVERSION, rpmutils.REQUIREFLAGS),\n\t\t\tConflicts: getEntries(rpm.Header, 1054 /*rpmutils.CONFLICTNAME*/, 1055 /*rpmutils.CONFLICTVERSION*/, 1053 /*rpmutils.CONFLICTFLAGS*/), // https://github.com/sassoftware/go-rpmutils/pull/24\n\t\t\tObsoletes: getEntries(rpm.Header, rpmutils.OBSOLETENAME, rpmutils.OBSOLETEVERSION, rpmutils.OBSOLETEFLAGS),\n\t\t\tFiles: getFiles(rpm.Header),\n\t\t\tChangelogs: getChangelogs(rpm.Header),\n\t\t},\n\t}\n\n\tif !validation.IsValidURL(p.VersionMetadata.ProjectURL) {\n\t\tp.VersionMetadata.ProjectURL = \"\"\n\t}\n\n\treturn p, nil\n}", "func (u *Unpacker) ReadPackageFilelist(r io.ReadSeeker) (fileList []structures.FileInfo, err error) {\n\n\tvalid, err := u.isValidPackage(r)\n\n\tif !valid {\n\t\terr = errors.New(\"not a valid package\")\n\t\treturn\n\t}\n\t// reader is in position, start extracting\n\n\tfileList, err = u.getFileList(r)\n\n\tu.log.WithField(\"fileList\", fileList).Debug(\"file list\")\n\n\treturn\n}", "func (self *Event) GetLeadOrganiser() (*Person, error) {\n\tdebug.Nop()\n\t// if len(self.Organisers)>0 {\n\t// \tdebug.Print(\"organiser: \", self.Organisers[0].Name.First)\n\t// \t// self.Organisers[0] = self.Organisers[0]\n\t// \t// doc, err := self.Organisers[0].Get()\n\t// \torga, err:= People.DocumentWithID(self.Organisers[0].ID)\n\t// \tif err != nil {\n\t// \t\treturn nil, err\n\t// \t}\n\t// \treturn orga.(*Person), nil\n\n\t// }\n\treturn nil, errs.Format(\"No organisers at this event\")\n}", "func NewLead(cslug, source, owner, status string, teamsize, rate, duration float64,\n\tstart string, comments []string) (*lead, error) {\n\tdoc := lead{\n\t\tID: bson.NewObjectId(),\n\t\tContactSlug: cslug,\n\t\tSource: strings.Title(source),\n\t\tOwner: strings.Title(owner),\n\t\tStatus: strings.Title(status),\n\t\tTeamSize: teamsize,\n\t\tRatePerHour: rate,\n\t\tDurationInMonths: duration,\n\t\tEstimatedStartDate: start,\n\t\tComments: comments,\n\t}\n\n\tif err := (&doc).Validate(); err != nil {\n\t\treturn &lead{}, err\n\t}\n\n\tdoc.CreatedAt = doc.ID.Time()\n\tdoc.UpdatedAt = doc.CreatedAt\n\n\terr := config.LeadsCollection.Insert(doc)\n\tif err != nil {\n\t\treturn &lead{}, err\n\t}\n\treturn &doc, nil\n}", "func (session *NetSession) ReadPackage() (interface{}, error) {\n\tfmt.Println(\"reading package from rtsp session\")\n\tnewPackage := new(Package)\n\tnewPackage.RtspHeaderMap = make(map[string]string)\n\tnewPackage.Error = Ok\n\treqData := bytes.NewBuffer(nil)\n\tfor ifFirstLine := true; ; {\n\t\tline, isPrefix, err :=\n\t\t\tsession.Bufio.ReadLine()\n\t\tif err != nil {\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"session.Bufio.ReadLine() : %v\", err)\n\t\t}\n\t\treqData.Write(line)\n\t\treqData.WriteString(\"\\r\\n\")\n\t\tif !isPrefix {\n\t\t\tif ifFirstLine {\n\t\t\t\titems := regexp.MustCompile(\"\\\\s+\").\n\t\t\t\t\tSplit(strings.\n\t\t\t\t\t\tTrimSpace(string(line)), -1)\n\t\t\t\tif len(items) < 3 ||\n\t\t\t\t\t!strings.HasPrefix(items[2], \"RTSP\") {\n\t\t\t\t\treturn nil,\n\t\t\t\t\t\tfmt.Errorf(\"first request line error\")\n\t\t\t\t}\n\t\t\t\tnewPackage.Method = items[0]\n\t\t\t\tnewPackage.URL = items[1]\n\t\t\t\tnewPackage.Version = items[2]\n\t\t\t\tifFirstLine = false\n\t\t\t} else {\n\t\t\t\tif items := regexp.MustCompile(\":\\\\s+\").Split(strings.\n\t\t\t\t\tTrimSpace(string(line)), 2); len(items) == 2 {\n\t\t\t\t\tnewPackage.RtspHeaderMap[items[0]] = items[1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(line) == 0 {\n\t\t\tfmt.Printf(\"%v\", reqData.String())\n\t\t\tif length, exist :=\n\t\t\t\tnewPackage.RtspHeaderMap[\"Content-Length\"]; exist {\n\t\t\t\tif lengthInt, err := strconv.Atoi(length); err == nil && lengthInt > 0 {\n\t\t\t\t\tcontent := make([]byte, lengthInt)\n\t\t\t\t\tif _, err := io.ReadFull(session.Bufio, content); err == nil {\n\t\t\t\t\t\tnewPackage.Content = content\n\t\t\t\t\t\tfmt.Print(string(content))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treqData.Reset()\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn newPackage, nil\n}", "func (repo *Repository) ReadDescription() string {\n\tpath := filepath.Join(repo.Path, \"description\")\n\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(dat)\n}", "func ReadBundle(manifestsDir string) (*operatorsv1alpha1.ClusterServiceVersion, error) {\n\tbundle, err := manifests.GetBundleFromDir(manifestsDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bundle.CSV, nil\n}", "func (m *MeshConfig) GetRdsRefreshDelay() *types.Duration {\n\tif m != nil {\n\t\treturn m.RdsRefreshDelay\n\t}\n\treturn nil\n}", "func (m *MeshConfig) GetRdsRefreshDelay() *types.Duration {\n\tif m != nil {\n\t\treturn m.RdsRefreshDelay\n\t}\n\treturn nil\n}", "func (m *MeshConfig) GetRdsRefreshDelay() *types.Duration {\n\tif m != nil {\n\t\treturn m.RdsRefreshDelay\n\t}\n\treturn nil\n}", "func ReadRenewOption(row *sql.Row, a *RenewOption) error {\n\terr := row.Scan(\n\t\t&a.ROID,\n\t\t&a.ROLID,\n\t\t&a.Dt,\n\t\t&a.Opt,\n\t\t&a.Rent,\n\t\t&a.FLAGS,\n\t\t&a.CreateTime,\n\t\t&a.CreateBy,\n\t\t&a.LastModTime,\n\t\t&a.LastModBy)\n\tSkipSQLNoRowsError(&err)\n\treturn err\n}", "func (g *Generator) GoWrapPackage(depfile *fdep.DepFile) string {\n\tif g.PkgSource != nil {\n\t\tif p, ok := g.PkgSource.GetPkg(g, depfile); ok {\n\t\t\treturn p\n\t\t}\n\t}\n\n\tfor _, o := range depfile.ProtoFile.Options {\n\t\tif o.Name == \"gowrap_package\" {\n\t\t\treturn o.Value.String()\n\t\t}\n\t}\n\n\t// prepend \"fpwrap\"\n\tfor _, o := range depfile.ProtoFile.Options {\n\t\tif o.Name == \"go_package\" {\n\t\t\treturn path.Join(\"fpwrap\", o.Value.String())\n\t\t}\n\t}\n\treturn path.Join(\"fpwrap\", path.Dir(depfile.FilePath))\n}", "func Bcm2835_peri_read(Paddr []uint32) uint32 {\n\tcPaddr, _ := (*C.uint32_t)(unsafe.Pointer((*sliceHeader)(unsafe.Pointer(&Paddr)).Data)), cgoAllocsUnknown\n\t__ret := C.bcm2835_peri_read(cPaddr)\n\t__v := (uint32)(__ret)\n\treturn __v\n}", "func ReadLessons(cfg config.AntidoteConfig) ([]*models.Lesson, error) {\n\n\t// Get lesson definitions\n\tfileList := []string{}\n\tlessonDir := fmt.Sprintf(\"%s/lessons\", cfg.CurriculumDir)\n\tlog.Debugf(\"Searching %s for lesson definitions\", lessonDir)\n\terr := filepath.Walk(lessonDir, func(path string, f os.FileInfo, err error) error {\n\t\tlessonDefFile := fmt.Sprintf(\"%s/lesson.meta.yaml\", path)\n\t\tif _, err := os.Stat(lessonDefFile); err == nil {\n\t\t\tlog.Debugf(\"Found lesson definition at: %s\", lessonDefFile)\n\t\t\tfileList = append(fileList, lessonDefFile)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tretLds := []*models.Lesson{}\n\n\tfor f := range fileList {\n\n\t\tfile := fileList[f]\n\n\t\tlog.Infof(\"Importing lesson definition at: %s\", file)\n\n\t\tyamlDef, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Encountered problem %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar lesson models.Lesson\n\t\terr = yaml.Unmarshal([]byte(yamlDef), &lesson)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to import %s: %s\", file, err)\n\t\t}\n\t\tlesson.LessonFile = file\n\t\tlesson.LessonDir = filepath.Dir(file)\n\n\t\terr = validateLesson(&lesson)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Lesson '%s' failed to validate\", lesson.Slug)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif tierMap[lesson.Tier] < tierMap[cfg.Tier] {\n\t\t\tlog.Warnf(\"Skipping lesson %s due to configured tier\", lesson.Slug)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Successfully imported lesson '%s' with %d endpoints.\", lesson.Slug, len(lesson.Endpoints))\n\t\tretLds = append(retLds, &lesson)\n\t}\n\n\tlog.Info(\"Performing post-import lesson prereq validation check\")\n\tfor _, lesson := range retLds {\n\t\tfor _, prereqSlug := range lesson.Prereqs {\n\t\t\tif !lessonInSlice(retLds, prereqSlug) {\n\t\t\t\terr := fmt.Errorf(\"Lesson %s listed an unknown prereq: %s\", lesson.Slug, prereqSlug)\n\t\t\t\tlog.Error(err.Error())\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Infof(\"Imported %d lesson definitions.\", len(retLds))\n\treturn retLds, nil\n}", "func (c *Client) GetCrmLeadTags(ids []int64) (*CrmLeadTags, error) {\n\tclts := &CrmLeadTags{}\n\tif err := c.Read(CrmLeadTagModel, ids, nil, clts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn clts, nil\n}", "func (f Float) Lead() int {\n\treturn int(f.m >> 63)\n}", "func (c *Client) GetLoyaltyRule(id int64) (*LoyaltyRule, error) {\n\tlrs, err := c.GetLoyaltyRules([]int64{id})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif lrs != nil && len(*lrs) > 0 {\n\t\treturn &((*lrs)[0]), nil\n\t}\n\treturn nil, fmt.Errorf(\"id %v of loyalty.rule not found\", id)\n}", "func (s *liiklusScaler) getLag(ctx context.Context) (uint64, map[uint32]uint64, error) {\n\tvar totalLag uint64 = 0\n\tctx1, cancel1 := context.WithTimeout(ctx, 10*time.Second)\n\tdefer cancel1()\n\tgor, err := s.client.GetOffsets(ctx1, &liiklus_service.GetOffsetsRequest{\n\t\tTopic: s.metadata.topic,\n\t\tGroup: s.metadata.group,\n\t\tGroupVersion: s.metadata.groupVersion,\n\t})\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel2()\n\tgeor, err := s.client.GetEndOffsets(ctx2, &liiklus_service.GetEndOffsetsRequest{\n\t\tTopic: s.metadata.topic,\n\t})\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tlags := make(map[uint32]uint64, len(geor.Offsets))\n\n\tfor part, o := range geor.GetOffsets() {\n\t\tdiff := o - gor.Offsets[part]\n\t\tlags[part] = diff\n\t\ttotalLag += diff\n\t}\n\treturn totalLag, lags, nil\n\n}", "func (p *Plugins) readLockPlugin(name string) {\n\tlocked, err := golock.IsLocked(p.lockfile(name))\n\tLogIfError(err)\n\tif locked {\n\t\tp.lockPlugin(name)\n\t\tp.unlockPlugin(name)\n\t}\n}", "func (d *PartialDriver) ReadDown(version uint) (r io.ReadCloser, identifier string, err error) {\n\tif m, ok := d.migrations.Down(version); ok {\n\t\tbody, err := d.open(path.Join(d.path, m.Raw))\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\treturn body, m.Identifier, nil\n\t}\n\treturn nil, \"\", &fs.PathError{\n\t\tOp: \"read down for version \" + strconv.FormatUint(uint64(version), 10),\n\t\tPath: d.path,\n\t\tErr: fs.ErrNotExist,\n\t}\n}", "func LookupLedger(ctx *pulumi.Context, args *LookupLedgerArgs, opts ...pulumi.InvokeOption) (*LookupLedgerResult, error) {\n\tvar rv LookupLedgerResult\n\terr := ctx.Invoke(\"azure-native:confidentialledger/v20201201preview:getLedger\", args, &rv, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &rv, nil\n}", "func (c *Client) FindCrmLeadTagId(criteria *Criteria, options *Options) (int64, error) {\n\tids, err := c.Search(CrmLeadTagModel, criteria, options)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif len(ids) > 0 {\n\t\treturn ids[0], nil\n\t}\n\treturn -1, fmt.Errorf(\"crm.lead.tag was not found with criteria %v and options %v\", criteria, options)\n}", "func (s *SparkCoreAdaptor) DigitalRead(pin string) (val int, err error) {\n\tparams := url.Values{\n\t\t\"params\": {pin},\n\t\t\"access_token\": {s.AccessToken},\n\t}\n\turl := fmt.Sprintf(\"%v/digitalread\", s.deviceURL())\n\tresp, err := s.requestToSpark(\"POST\", url, params)\n\tif err == nil {\n\t\tval = int(resp[\"return_value\"].(float64))\n\t\treturn\n\t}\n\treturn -1, err\n}", "func BuildLorad(gtw *ttnpb.Gateway, fps *frequencyplans.Store) (*LoradConfig, error) {\n\tfp, err := fps.GetByID(gtw.FrequencyPlanId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsx1301Conf := &shared.SX1301Config{}\n\tif len(fp.Radios) != 0 {\n\t\tsx1301Conf, err = shared.BuildSX1301Config(fp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar gatewayConf LoradGatewayConf\n\tif antennas := gtw.GetAntennas(); len(antennas) > 0 {\n\t\tantenna := antennas[0]\n\t\tsx1301Conf.AntennaGain = antenna.Gain\n\t\tif location := antenna.Location; location != nil {\n\t\t\tgatewayConf.BeaconLatitude = location.Latitude\n\t\t\tgatewayConf.BeaconLongitude = location.Longitude\n\t\t}\n\t}\n\t// TODO: Configure Class B (https://github.com/TheThingsNetwork/lorawan-stack/issues/1748).\n\treturn &LoradConfig{\n\t\tSX1301Conf: LoradSX1301Conf{\n\t\t\tSX1301Config: *sx1301Conf,\n\t\t\t// Following fields are set equal to defaults present in CPF 1.1.6 DOTA for Kerlink Wirnet Station.\n\t\t\tAntennaGainDesc: \"Antenna gain, in dBi\",\n\t\t\tInsertionLoss: 0.5,\n\t\t\tInsertionLossDesc: \"Insertion loss, in dBi\",\n\t\t},\n\t\tGatewayConf: gatewayConf,\n\t}, nil\n}", "func (g *goldTrybotProcessor) getRietveldPatchset(issueID int64, patchsetID int64, name string) (*rietveld.Patchset, error) {\n\t// TODO(stephana): This should be a side effect of Rietveld to Gerrit transition.\n\t// Remove once transition complete. In the meantime log a warning for ingestigation.\n\tif issueID == 0 {\n\t\tsklog.Warningf(\"Received issue number 0 in file %s\", name)\n\t\treturn nil, ingestion.IgnoreResultsFileErr\n\t}\n\n\tpatchinfo, err := g.rietveldReview.GetPatchset(issueID, patchsetID)\n\tif err == nil {\n\t\treturn patchinfo, nil\n\t}\n\n\t// If we can find the issue, check if the patchset has been removed.\n\tvar issueInfo *rietveld.Issue\n\tif issueInfo, err = g.rietveldReview.GetIssueProperties(issueID, false); err == nil {\n\t\tfound := false\n\t\tfor _, pset := range issueInfo.Patchsets {\n\t\t\tif pset == patchsetID {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// This patchset is no longer available ignore the result file.\n\t\tif !found {\n\t\t\tsklog.Warningf(\"Rietveld issue/patchset (%d/%d) does not exist.\", issueID, patchsetID)\n\t\t\treturn nil, ingestion.IgnoreResultsFileErr\n\t\t}\n\t\t// We should not reach this point. Investigate manually if we do.\n\t\treturn nil, fmt.Errorf(\"Found patchset %d for issue %d, but unable to retrieve it.\", patchsetID, issueID)\n\t}\n\n\treturn nil, fmt.Errorf(\"Failed to retrieve trybot issue and patch info for (%d, %d). Got Error: %s\", issueID, patchsetID, err)\n}", "func readGroup(c *cli.Context) *app.Group {\n\tname := c.Args().First()\n\tf, err := os.Open(name)\n\tlog.ErrFatal(err, \"Couldn't open group definition file\")\n\tgroup, err := app.ReadGroupDescToml(f)\n\tlog.ErrFatal(err, \"Error while reading group definition file\", err)\n\tif len(group.Roster.List) == 0 {\n\t\tlog.ErrFatalf(err, \"Empty entity or invalid group defintion in: %s\",\n\t\t\tname)\n\t}\n\treturn group\n}", "func readGroup(c *cli.Context) *app.Group {\n\tname := c.Args().First()\n\tf, err := os.Open(name)\n\tlog.ErrFatal(err, \"Couldn't open group definition file\")\n\tgroup, err := app.ReadGroupDescToml(f)\n\tlog.ErrFatal(err, \"Error while reading group definition file\", err)\n\tif len(group.Roster.List) == 0 {\n\t\tlog.ErrFatalf(err, \"Empty entity or invalid group defintion in: %s\",\n\t\t\tname)\n\t}\n\treturn group\n}", "func ReadApproachModeEngaged(data []byte) ApproachModeEngaged {\n\tbits := (data[6] & 0x10) >> 4\n\treturn ApproachModeEngaged(bits)\n}", "func (o *DriveAta) GetReadLookaheadEnabled(ctx context.Context) (readLookaheadEnabled bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDriveAta, \"ReadLookaheadEnabled\").Store(&readLookaheadEnabled)\n\treturn\n}", "func (p *Packet6) Lease() *dhcpv6.OptIAAddress {\n\tiana := p.p.Options.OneIANA()\n\tif iana == nil {\n\t\treturn nil\n\t}\n\treturn iana.Options.OneAddress()\n}", "func rpmReadSigHeader(r io.Reader) (*Header, error) {\n\t// read package lead\n\tif lead, err := ReadPackageLead(r); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\t// check signature type\n\t\tif lead.SignatureType != RPMSIGTYPE_HEADERSIG {\n\t\t\treturn nil, fmt.Errorf(\"Unsupported signature type: 0x%x\", lead.SignatureType)\n\t\t}\n\t}\n\n\t// read signature header\n\tsigheader, err := ReadPackageHeader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sigheader, nil\n}", "func (c *Processor) readLong(ea uint16) (n uint32, opr string, err error) {\n\tmod := ea & 0x38 >> 3\n\treg := ea & 0x07\n\tswitch mod {\n\tdefault:\n\t\terr = errBadAddress\n\t\treturn\n\n\tcase 0x00: // data register\n\t\tn = c.D[reg]\n\t\topr = fmt.Sprintf(\"D%d\", reg)\n\n\tcase 0x01: // address register\n\t\tn = c.A[reg]\n\t\topr = fmt.Sprintf(\"A%d\", reg)\n\n\tcase 0x02: // memory address\n\t\tn, err = c.M.Long(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"(A%d)\", reg)\n\n\tcase 0x03: // memory address with post-increment\n\t\tn, err = c.M.Long(int(c.A[reg]))\n\t\tc.A[reg] += 4\n\t\topr = fmt.Sprintf(\"(A%d)+\", reg)\n\n\tcase 0x04: // memory address with pre-decrement\n\t\tc.A[reg] -= 4\n\t\tn, err = c.M.Long(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"-(A%d)\", reg)\n\n\tcase 0x05: // memory address with displacement\n\t\tvar d int16\n\t\td, err = c.M.Sword(int(c.PC))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tc.PC += 2\n\t\taddr := int(c.A[reg]) + int(d)\n\t\tn, err = c.M.Long(addr)\n\t\topr = fmt.Sprintf(\"($%X,A%d)\", d, reg)\n\n\tcase 0x07: // other\n\t\tswitch reg {\n\t\tdefault:\n\t\t\terr = errBadAddress\n\t\t\treturn\n\n\t\tcase 0x00: // absolute word\n\t\t\tvar addr uint16\n\t\t\taddr, err = c.M.Word(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 2\n\t\t\tn, err = c.M.Long(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x01: // absolute long\n\t\t\tvar addr uint32\n\t\t\taddr, err = c.M.Long(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 4\n\t\t\tn, err = c.M.Long(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x04: // immediate long\n\t\t\tn, err = c.M.Long(int(c.PC))\n\t\t\tc.PC += 4\n\t\t\topr = fmt.Sprintf(\"#$%X\", int32(n))\n\t\t}\n\t}\n\treturn\n}", "func (d *DBGenerator) readLicense(ctx context.Context) error {\n\t// If no license file given, then we omit the license from the manifests\n\tif d.Opts.LicenseFile == \"\" {\n\t\treturn nil\n\t}\n\n\tvar err error\n\td.LicenseData, err = ioutil.ReadFile(d.Opts.LicenseFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *Dev) GetLedR() gpio.PinOut {\n\treturn d.ledR\n}", "func (c *Client) FindCrmLeadTags(criteria *Criteria, options *Options) (*CrmLeadTags, error) {\n\tclts := &CrmLeadTags{}\n\tif err := c.SearchRead(CrmLeadTagModel, criteria, options, clts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn clts, nil\n}", "func (c PeerRpc) Lead(ips []string, clusterAddr *string) error {\n\t_, err := node.BecomeLeader(ips, PeerRpcAddr)\n\t*clusterAddr = ClusterRpcAddr\n\treturn err\n}", "func (o *DriveAta) GetReadLookaheadSupported(ctx context.Context) (readLookaheadSupported bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDriveAta, \"ReadLookaheadSupported\").Store(&readLookaheadSupported)\n\treturn\n}", "func (f *FileDescriptor) GetPackageComments() *Comment { return f.PackageComments }", "func (a *Adaptor) DigitalRead(pin string) (val int, err error) {\n\n\tp, err := strconv.Atoi(pin)\n\tif err != nil {\n\t\treturn val, err\n\t}\n\tctx := context.TODO()\n\t\n\n\tif a.Board.Pins()[p] == nil {\n\t\tif err = a.Board.SetPinMode(ctx, p, client.ModeInput); err != nil {\n\t\t\treturn val, err\n\t\t}\n\t}\n\n\treturn a.Board.DigitalRead(ctx, p)\n}", "func (r *Repo) ReadDatabase() (pacman.Packages, error) {\n\tdbpath := r.DatabasePath()\n\tex, err := osutil.FileExists(dbpath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot read database %s: %w\", dbpath, err)\n\t} else if !ex {\n\t\treturn make(pacman.Packages, 0), nil\n\t}\n\tpkgs, err := pacman.ReadDatabase(dbpath)\n\tr.MakeAbs(pkgs)\n\treturn pkgs, err\n}", "func (projectL) LoadLead(ctx context.Context, e boil.ContextExecutor, singular bool, maybeProject interface{}, mods queries.Applicator) error {\n\tvar slice []*Project\n\tvar object *Project\n\n\tif singular {\n\t\tobject = maybeProject.(*Project)\n\t} else {\n\t\tslice = *maybeProject.(*[]*Project)\n\t}\n\n\targs := make([]interface{}, 0, 1)\n\tif singular {\n\t\tif object.R == nil {\n\t\t\tobject.R = &projectR{}\n\t\t}\n\t\tif !queries.IsNil(object.LeadID) {\n\t\t\targs = append(args, object.LeadID)\n\t\t}\n\n\t} else {\n\tOuter:\n\t\tfor _, obj := range slice {\n\t\t\tif obj.R == nil {\n\t\t\t\tobj.R = &projectR{}\n\t\t\t}\n\n\t\t\tfor _, a := range args {\n\t\t\t\tif queries.Equal(a, obj.LeadID) {\n\t\t\t\t\tcontinue Outer\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !queries.IsNil(obj.LeadID) {\n\t\t\t\targs = append(args, obj.LeadID)\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\n\tquery := NewQuery(qm.From(`users`), qm.WhereIn(`id in ?`, args...))\n\tif mods != nil {\n\t\tmods.Apply(query)\n\t}\n\n\tresults, err := query.QueryContext(ctx, e)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to eager load User\")\n\t}\n\n\tvar resultSlice []*User\n\tif err = queries.Bind(results, &resultSlice); err != nil {\n\t\treturn errors.Wrap(err, \"failed to bind eager loaded slice User\")\n\t}\n\n\tif err = results.Close(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to close results of eager load for users\")\n\t}\n\tif err = results.Err(); err != nil {\n\t\treturn errors.Wrap(err, \"error occurred during iteration of eager loaded relations for users\")\n\t}\n\n\tif len(projectAfterSelectHooks) != 0 {\n\t\tfor _, obj := range resultSlice {\n\t\t\tif err := obj.doAfterSelectHooks(ctx, e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(resultSlice) == 0 {\n\t\treturn nil\n\t}\n\n\tif singular {\n\t\tforeign := resultSlice[0]\n\t\tobject.R.Lead = foreign\n\t\tif foreign.R == nil {\n\t\t\tforeign.R = &userR{}\n\t\t}\n\t\tforeign.R.LeadProjects = append(foreign.R.LeadProjects, object)\n\t\treturn nil\n\t}\n\n\tfor _, local := range slice {\n\t\tfor _, foreign := range resultSlice {\n\t\t\tif queries.Equal(local.LeadID, foreign.ID) {\n\t\t\t\tlocal.R.Lead = foreign\n\t\t\t\tif foreign.R == nil {\n\t\t\t\t\tforeign.R = &userR{}\n\t\t\t\t}\n\t\t\t\tforeign.R.LeadProjects = append(foreign.R.LeadProjects, local)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ctx *Context) Provides(filename string) ([]*yum.Package, error) {\n\tvar err error\n\tre_file, err := regexp.Compile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstalled, err := ctx.listInstalledPackages()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trpms := make([]*yum.Package, 0, len(installed))\n\tfor i := range installed {\n\t\tipkg := installed[i]\n\t\tpkg, err := ctx.yum.FindLatestProvider(ipkg[0], ipkg[1], ipkg[2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trpms = append(rpms, pkg)\n\t}\n\n\ttype pair struct {\n\t\tpkg *yum.Package\n\t\tfile string\n\t}\n\tlist := make([]pair, 0)\n\tfor _, rpm := range rpms {\n\t\trpmfile := filepath.Join(ctx.tmpdir, rpm.RPMFileName())\n\t\tif _, errstat := os.Stat(rpmfile); errstat != nil {\n\t\t\t// try to re-download the package\n\t\t\terrdl := ctx.downloadPackages([]Package{{Package: rpm}}, ctx.tmpdir)\n\t\t\tif errdl != nil {\n\t\t\t\terr = fmt.Errorf(\"lbpkr: no such file [%s] (%v)\", rpmfile, errstat)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tout, err := ctx.rpm(false, \"-qlp\", rpmfile)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"lbpkr: error querying rpm-db: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tscan := bufio.NewScanner(bytes.NewBuffer(out))\n\t\tfor scan.Scan() {\n\t\t\tfile := ctx.cfg.RelocateFile(scan.Text())\n\t\t\tif re_file.MatchString(file) {\n\t\t\t\tlist = append(list, pair{\n\t\t\t\t\tpkg: rpm,\n\t\t\t\t\tfile: ctx.cfg.RelocateFile(file),\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\terr = scan.Err()\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"lbpkr: error scaning rpm-output: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(list) <= 0 {\n\t\tfmt.Printf(\"** No Match found **\\n\")\n\t\treturn nil, err\n\t}\n\n\tpkgs := make([]string, 0, len(list))\n\tfor _, p := range list {\n\t\tpkgs = append(pkgs,\n\t\t\tfmt.Sprintf(\"%s (%s)\", p.pkg.ID(), p.file),\n\t\t)\n\t}\n\n\tsort.Strings(pkgs)\n\tfor _, p := range pkgs {\n\t\tfmt.Printf(\"%s\\n\", p)\n\t}\n\treturn rpms, err\n}", "func readPackage() Package {\n raw, err := ioutil.ReadFile(\"./gopackage.json\")\n if err != nil {\n fmt.Printf(\"Problem reading gopackage.json: %s\\n\", err)\n os.Exit(1)\n }\n\n var mypackage Package\n json.Unmarshal(raw, &mypackage)\n\n return mypackage\n}", "func leftAngle(p *parser, out *bytes.Buffer, data []byte, offset int) int {\n\tif p.flags&EXTENSION_INCLUDE != 0 {\n\t\tif j := p.codeInclude(out, data[offset:]); j > 0 {\n\t\t\treturn j\n\t\t}\n\t}\n\n\tdata = data[offset:]\n\taltype := _LINK_TYPE_NOT_AUTOLINK\n\tend := tagLength(data, &altype)\n\tif size := p.inlineHTMLComment(out, data); size > 0 {\n\t\tend = size\n\t}\n\tif end > 2 {\n\t\tallnum := 0\n\t\tfor j := 1; j < end-1; j++ {\n\t\t\tif isnum(data[j]) {\n\t\t\t\tallnum++\n\t\t\t}\n\t\t}\n\t\tif allnum+2 == end {\n\t\t\tindex := string(data[1 : end-1])\n\t\t\tif _, ok := p.callouts[index]; ok {\n\t\t\t\tp.r.CalloutText(out, index, p.callouts[index])\n\t\t\t\treturn end\n\t\t\t}\n\t\t\treturn 0\n\t\t}\n\n\t\tif altype != _LINK_TYPE_NOT_AUTOLINK {\n\t\t\tvar uLink bytes.Buffer\n\t\t\tunescapeText(&uLink, data[1:end+1-2])\n\t\t\tif uLink.Len() > 0 {\n\t\t\t\tp.r.AutoLink(out, uLink.Bytes(), altype)\n\t\t\t}\n\t\t} else {\n\t\t\tp.r.RawHtmlTag(out, data[:end])\n\t\t}\n\t}\n\n\treturn end\n}", "func ReadLeaderMigrationConfiguration(configFilePath string) (*internal.LeaderMigrationConfiguration, error) {\n\tdata, err := os.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read leader migration configuration from %q: %w\", configFilePath, err)\n\t}\n\tconfig, gvk, err := serializer.NewCodecFactory(cfgScheme).UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinternalConfig, ok := config.(*internal.LeaderMigrationConfiguration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected config type: %v\", gvk)\n\t}\n\treturn internalConfig, nil\n}", "func LoadPackLate(fs *axis2.FileSystem, log rblutil.Logger, data *Database, name string) {\n\tlog.Println(\" Loading Pack:\", name)\n\tlog.Println(\" No local file, trying to download...\")\n\tmeta, ds := downloadPack(fs, data, name, nil, nil, log)\n\tif meta == nil {\n\t\treturn\n\t}\n\n\tif meta.Name != \"\" && meta.Name != name {\n\t\terrors.RaiseError(\"Pack name mismatch error, the requested pack name does not match the canonical pack name\")\n\t}\n\n\tlog.Println(\" Checking versions...\")\n\tif meta.MatchVersions(&HostVersions{\n\t\tDFMajor: rblutil.DFVMajor,\n\t\tDFPatch: rblutil.DFVMinor,\n\n\t\tRblRewrite: rblutil.VMajor,\n\t\tRblMajor: rblutil.VMinor,\n\t\tRblPatch: rblutil.VPatch,\n\t}) {\n\t\tlog.Println(\" OK!\")\n\t\tlog.Println(\" Loading...\")\n\t} else {\n\t\tlog.Println(\" This pack is not compatible with the local DF and/or Rubble version!\")\n\t\tlog.Println(\" Skipping.\")\n\t\treturn\n\t}\n\n\tfs.Mount(\"addonpacks/\"+name, ds, false)\n\tdata.Writers = append(data.Writers, meta.Writers...)\n\tloadDir(fs, data, name, \"addonpacks/\"+name, meta.TagsFirst, meta.TagsLast, nil)\n\n\tmeta.Name = name\n\tdata.Packs[name] = meta\n\n\tfor _, pack := range meta.Dependencies {\n\t\tloadPack(fs, log, data, pack, fs.Exists(\"addons/\"+name+\".zip\"))\n\t}\n}", "func ReadClosePeriod(row *sql.Row, a *ClosePeriod) error {\n\terr := row.Scan(&a.CPID, &a.BID, &a.TLID, &a.Dt, &a.CreateTS, &a.CreateBy, &a.LastModTime, &a.LastModBy)\n\tSkipSQLNoRowsError(&err)\n\treturn err\n}", "func (o JavaSettingsPtrOutput) LibraryPackage() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *JavaSettings) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.LibraryPackage\n\t}).(pulumi.StringPtrOutput)\n}", "func (w *wrapper) Readlink(path string) (int, string) {\n\tif sfs, ok := w.underlying.(billy.Symlink); ok {\n\t\tfn, err := sfs.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn convertError(err), \"\"\n\t\t}\n\t\treturn 0, fn\n\t}\n\treturn -fuse.ENOSYS, \"\"\n}", "func (znp *Znp) SysAdcRead(channel Channel, resolution Resolution) (rsp *SysAdcReadResponse, err error) {\n\treq := &SysAdcRead{Channel: channel, Resolution: resolution}\n\terr = znp.ProcessRequest(unp.C_SREQ, unp.S_SYS, 0x0D, req, &rsp)\n\treturn\n}", "func Read(path string) (*Package, error) {\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\treturn ReadDir(path)\n\t}\n\treturn ReadFile(path)\n}", "func (fsys *FS) Readlink(path string) (errc int, linkPath string) {\n\tdefer fs.Trace(path, \"\")(\"linkPath=%q, errc=%d\", &linkPath, &errc)\n\treturn -fuse.ENOSYS, \"\"\n}", "func ParsePackage(r io.Reader) (*Package, error) {\n\t// Alpine packages are concated .tar.gz streams. Usually the first stream contains the package metadata.\n\n\tbr := bufio.NewReader(r) // needed for gzip Multistream\n\n\th := sha1.New()\n\n\tgzr, err := gzip.NewReader(&teeByteReader{br, h})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer gzr.Close()\n\n\tfor {\n\t\tgzr.Multistream(false)\n\n\t\ttr := tar.NewReader(gzr)\n\t\tfor {\n\t\t\thd, err := tr.Next()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif hd.Name == \".PKGINFO\" {\n\t\t\t\tp, err := ParsePackageInfo(tr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t// drain the reader\n\t\t\t\tfor {\n\t\t\t\t\tif _, err := tr.Next(); err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tp.FileMetadata.Checksum = \"Q1\" + base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n\t\t\t\treturn p, nil\n\t\t\t}\n\t\t}\n\n\t\th = sha1.New()\n\n\t\terr = gzr.Reset(&teeByteReader{br, h})\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn nil, ErrMissingPKGINFOFile\n}", "func (m *Message) LDP() (*LDP, error) {\n\tps, err := m.Parse(\"LDP\")\n\tpst, ok := ps.(*LDP)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (rw *RWLock) DowngradeToRead() bool {\n\trw.lock.Lock()\n\tif !rw.init() {\n\t\trw.lock.Unlock()\n\t\treturn false\n\t}\n\n\tif rw.state != stateLocked {\n\t\trw.lock.Unlock()\n\t\tpanic(\"lock was not acquired for write\")\n\t}\n\n\trw.writers--\n\tif rw.writers == 0 {\n\t\trw.state = stateInit\n\t\tatomic.AddInt32(&rw.readers, rwLockMaxReaders+1)\n\t} else {\n\t\trw.state = stateWaiting\n\t\tatomic.AddInt32(&rw.readers, 1)\n\t}\n\n\t// let readers know, if any, that there is no writers anymore\n\tif rw.rrCh != nil {\n\t\tclose(rw.rrCh)\n\t\trw.rrCh = nil\n\t}\n\n\trw.lock.Unlock()\n\treturn true\n}", "func (r *reader) GetAdsBlocking() (blocking bool, err error) {\n\treturn r.envParams.GetOnOff(\"BLOCK_ADS\", libparams.Default(\"off\"))\n}", "func (c *readConverter) ensureLeftover() error {\n\tif len(c.leftover) > 0 {\n\t\treturn nil\n\t}\n\tpayload, err := c.cr.ReadChunk()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.leftover = payload\n\treturn nil\n}", "func (rp *CFGoReadPackage) Read(stateNode *snreader.StateNode, input snreader.InputItf) (isEnd bool, err error) {\n\tlex := read(input)\n\n\tif ignoreWithoutBreakline(lex) {\n\t\treturn false, nil\n\t}\n\n\tif rp.first {\n\t\trp.first = false\n\t\treturn false, nil\n\t}\n\n\tif !lex_pgl.IsIdent(lex) {\n\t\treturn true, onErr(rp, lex, \"package name want a ident\")\n\t}\n\n\trp.goFile.Package = lex.Value\n\n\treturn true, nil\n}", "func (s *DataStore) GetLHVolumeAttachmentRO(name string) (*longhorn.VolumeAttachment, error) {\n\treturn s.lhVALister.VolumeAttachments(s.namespace).Get(name)\n}", "func (k Keeper) GetRejectedUpgrade(\n\tctx sdk.Context,\n\tname string,\n) (val types.RejectedUpgrade, found bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedUpgradeKeyPrefix))\n\n\tb := store.Get(types.RejectedUpgradeKey(\n\t\tname,\n\t))\n\tif b == nil {\n\t\treturn val, false\n\t}\n\n\tk.cdc.MustUnmarshal(b, &val)\n\n\treturn val, true\n}", "func (ee *EncryptionEngine) ReadWdek() {\n\tfo, err := os.Open(ee.wDekPathName)\n\tif err != nil {\n\t\terr := errors.Wrapf(err, \"cannot read wdek to unmarshal it %s\", ee.wDekPathName)\n\t\tee.logger.Fatalf(\"%+v\", err)\n\t}\n\tdefer fo.Close()\n\n\tbackend, errClient := ee.gcpClient.GetAEAD(ee.kekName)\n\tif errClient != nil {\n\t\terrClient := errors.Wrap(errClient, \"cannot retrieve dek from KMS\")\n\t\tee.logger.Fatalf(\"%+v\", errClient)\n\t}\n\n\tjreader := keyset.NewJSONReader(fo)\n\tmasterKey := aead.NewKMSEnvelopeAEAD(*aead.AES256GCMKeyTemplate(), backend)\n\n\t// Read the encrypted keyset handle back from the io.Reader implementation\n\t// and decrypt it using the master key.\n\tee.dekHandle, err = keyset.Read(jreader, masterKey)\n\tif err != nil {\n\t\terr := errors.Wrap(err, \"cannot created wdek handle\")\n\t\tee.logger.Fatalf(\"%+v\", err)\n\t}\n}", "func (driver *Driver) readAdditionalVariables() error {\n\terr := driver.readAdditionalVariablesInline()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn driver.readAdditionalVariablesFile()\n}", "func (d DocLanguageHelper) GetModuleDocLink(pkg *schema.Package, modName string) (string, string) {\n\tvar displayName string\n\tvar link string\n\tif modName == \"\" {\n\t\tdisplayName = fmt.Sprintf(\"@pulumi/%s\", pkg.Name)\n\t} else {\n\t\tdisplayName = fmt.Sprintf(\"@pulumi/%s/%s\", pkg.Name, strings.ToLower(modName))\n\t}\n\tlink = d.GetDocLinkForResourceType(pkg, modName, \"\")\n\treturn displayName, link\n}", "func (driver *Driver) readAdditionalVariablesFile() error {\n\tif driver.AdditionalVariablesFile == \"\" {\n\t\treturn nil // Nothing to do\n\t}\n\n\tvariablesFileName := driver.AdditionalVariablesFile\n\tif !path.IsAbs(variablesFileName) {\n\t\tworkingDirectory, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvariablesFileName = path.Join(workingDirectory, variablesFileName)\n\t}\n\n\tlog.Debugf(\"Reading additional Terraform variables from '%s'...\", variablesFileName)\n\n\t// This operation is additive (preserves exising variables).\n\terr := driver.ConfigVariables.Read(variablesFileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to read additional variables from '%s': %s\",\n\t\t\tvariablesFileName,\n\t\t\terr.Error(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (w *wrapper) Read(path string, buff []byte, ofst int64, fd uint64) int {\n\tfh, ok := w.getFileDescriptor(fd)\n\tif !ok {\n\t\treturn -fuse.EINVAL\n\t}\n\tn, err := fh.ReadAt(buff, ofst)\n\tif n > 0 || err == io.EOF {\n\t\treturn n\n\t}\n\treturn convertError(err)\n}", "func Lead(c rune) rune {\n\tif LeadG <= c && c <= LeadH {\n\t\treturn c\n\t}\n\tif l, ok := toLead[c]; ok {\n\t\treturn l\n\t}\n\n\treturn 0\n}", "func RequireReadLink(t *testing.T, path string) string {\n\ttarget, err := os.Readlink(path)\n\trequire.NoError(t, err)\n\treturn target\n}", "func dis_instrDDCB__LD_L_RES_7_iREGpDD(memory MemoryReader, address uint16, shift int) (string, uint16, int) {\n\tresult := \"LD \"\n\tshift = 0\n\tresult += \"L\" + \",\" + \"RES\"\n\treturn result, address + 1, shift\n}", "func (e RepairinvoiceEdges) LeaseOrErr() (*Lease, error) {\n\tif e.loadedTypes[2] {\n\t\tif e.Lease == nil {\n\t\t\t// The edge Lease was loaded in eager-loading,\n\t\t\t// but was not found.\n\t\t\treturn nil, &NotFoundError{label: lease.Label}\n\t\t}\n\t\treturn e.Lease, nil\n\t}\n\treturn nil, &NotLoadedError{edge: \"Lease\"}\n}", "func IsLead(r rune) bool {\n\tif LeadG <= r && r <= LeadH {\n\t\treturn true\n\t}\n\treturn false\n}", "func (ref OpenDB) ParseLEFTechnology(filepath string) (err error) {\n\trc := C.ReadTech(ref.db, C.CString(filepath))\n\tif rc != 0 {\n\t\tcErr := C.GoString(C.LastError)\n\t\tif len(cErr) > 0 {\n\t\t\terr = fmt.Errorf(\"%v\", C.GoString(C.LastError))\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Unknown error has occured\")\n\t\t}\n\t}\n\treturn\n\n}", "func (r *reader) GetDNSAdsBlocking() (blocking bool, err error) {\n\treturn r.envParams.GetOnOff(\"BLOCK_ADS\", libparams.Default(\"off\"))\n}", "func dis_instrDDCB__LD_B_SLA_iREGpDD(memory MemoryReader, address uint16, shift int) (string, uint16, int) {\n\tresult := \"LD \"\n\tshift = 0\n\tresult += \"B\" + \",\" + \"SLA\"\n\treturn result, address + 1, shift\n}", "func dis_instrDDCB__LD_L_SLA_iREGpDD(memory MemoryReader, address uint16, shift int) (string, uint16, int) {\n\tresult := \"LD \"\n\tshift = 0\n\tresult += \"L\" + \",\" + \"SLA\"\n\treturn result, address + 1, shift\n}", "func (r *Repo) ReadMeta(h errs.Handler, pkgnames ...string) (meta.Packages, error) {\n\terrs.Init(&h)\n\n\tpkgs, err := meta.Read(h, r.Directory, r.DatabasePath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pkgnames) == 0 {\n\t\treturn pkgs, nil\n\t}\n\treturn pu.Filter(pkgs, pu.NameFltr(pkgnames)).(meta.Packages), nil\n}", "func dis_instrDDCB__LD_B_RES_7_iREGpDD(memory MemoryReader, address uint16, shift int) (string, uint16, int) {\n\tresult := \"LD \"\n\tshift = 0\n\tresult += \"B\" + \",\" + \"RES\"\n\treturn result, address + 1, shift\n}", "func (d DocLanguageHelper) GetModuleDocLink(pkg *schema.Package, modName string) (string, string) {\n\tvar displayName string\n\tvar link string\n\tif modName == \"\" {\n\t\tdisplayName = pyPack(pkg.Name)\n\t} else {\n\t\tdisplayName = fmt.Sprintf(\"%s/%s\", pyPack(pkg.Name), strings.ToLower(modName))\n\t}\n\tlink = fmt.Sprintf(\"/docs/reference/pkg/python/%s\", displayName)\n\treturn displayName, link\n}", "func ReadModule(r io.Reader) (*module.Module, error) {\n\n\twr := &reader{r: r, n: 0}\n\tmodule, err := readModule(wr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"offset 0x%x: %w\", wr.n, err)\n\t}\n\n\treturn module, nil\n}", "func ReadRentalAgreements(rows *sql.Rows, a *RentalAgreement) error {\n\treturn rows.Scan(\n\t\t&a.RAID,\n\t\t&a.PRAID,\n\t\t&a.ORIGIN,\n\t\t&a.RATID,\n\t\t&a.BID,\n\t\t&a.NLID,\n\t\t&a.DocumentDate,\n\t\t&a.AgreementStart,\n\t\t&a.AgreementStop,\n\t\t&a.PossessionStart,\n\t\t&a.PossessionStop,\n\t\t&a.RentStart,\n\t\t&a.RentStop,\n\t\t&a.RentCycleEpoch,\n\t\t&a.UnspecifiedAdults,\n\t\t&a.UnspecifiedChildren,\n\t\t&a.Renewal,\n\t\t&a.SpecialProvisions,\n\t\t&a.LeaseType,\n\t\t&a.ExpenseAdjustmentType,\n\t\t&a.ExpensesStop,\n\t\t&a.ExpenseStopCalculation,\n\t\t&a.BaseYearEnd,\n\t\t&a.ExpenseAdjustment,\n\t\t&a.EstimatedCharges,\n\t\t&a.RateChange,\n\t\t&a.CSAgent,\n\t\t&a.NextRateChange,\n\t\t&a.PermittedUses,\n\t\t&a.ExclusiveUses,\n\t\t&a.ExtensionOption,\n\t\t&a.ExtensionOptionNotice,\n\t\t&a.ExpansionOption,\n\t\t&a.ExpansionOptionNotice,\n\t\t&a.RightOfFirstRefusal,\n\t\t&a.DesiredUsageStartDate,\n\t\t&a.RentableTypePreference,\n\t\t&a.FLAGS,\n\t\t&a.ApplicationReadyUID,\n\t\t&a.ApplicationReadyDate,\n\t\t&a.Approver1,\n\t\t&a.DecisionDate1,\n\t\t&a.DeclineReason1,\n\t\t&a.Approver2,\n\t\t&a.DecisionDate2,\n\t\t&a.DeclineReason2,\n\t\t&a.MoveInUID,\n\t\t&a.MoveInDate,\n\t\t&a.ActiveUID,\n\t\t&a.ActiveDate,\n\t\t&a.Outcome,\n\t\t&a.NoticeToMoveUID,\n\t\t&a.NoticeToMoveDate,\n\t\t&a.NoticeToMoveReported,\n\t\t&a.TerminatorUID,\n\t\t&a.TerminationDate,\n\t\t&a.LeaseTerminationReason,\n\t\t&a.LastModTime,\n\t\t&a.LastModBy,\n\t\t&a.CreateTS,\n\t\t&a.CreateBy,\n\t)\n}", "func dis_instrDDCB__LD_D_SLA_iREGpDD(memory MemoryReader, address uint16, shift int) (string, uint16, int) {\n\tresult := \"LD \"\n\tshift = 0\n\tresult += \"D\" + \",\" + \"SLA\"\n\treturn result, address + 1, shift\n}", "func (ref OpenDB) ParseLEF(filepath string) (err error) {\n\trc := C.ReadTechAndLib(ref.db, C.CString(filepath), C.CString(generateLibraryName(filepath)))\n\tif rc != 0 {\n\t\tcErr := C.GoString(C.LastError)\n\t\tif len(cErr) > 0 {\n\t\t\terr = fmt.Errorf(\"%v\", C.GoString(C.LastError))\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Unknown error has occured\")\n\t\t}\n\t}\n\treturn\n\n}", "func ReadSymlinkedDirectory(path string) (string, error) {\n\trealPath, err := ReadSymlink(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trealPathInfo, err := os.Stat(realPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to stat target '%s' of '%s': %s\", realPath, path, err)\n\t}\n\tif !realPathInfo.Mode().IsDir() {\n\t\treturn \"\", fmt.Errorf(\"canonical path points to a file '%s'\", realPath)\n\t}\n\treturn realPath, nil\n}" ]
[ "0.5112405", "0.48215428", "0.43978104", "0.42946908", "0.42732978", "0.41730243", "0.41524673", "0.41426352", "0.41032988", "0.4071604", "0.40617675", "0.40382263", "0.4014421", "0.40023905", "0.3999429", "0.3993476", "0.39913538", "0.39892584", "0.3976118", "0.39751792", "0.39730215", "0.39578146", "0.39430103", "0.39386222", "0.392017", "0.39045182", "0.39045182", "0.39045182", "0.39032426", "0.38988715", "0.38832757", "0.38554168", "0.3854232", "0.3819312", "0.38157585", "0.38077337", "0.38041747", "0.3790673", "0.37902844", "0.3789149", "0.37866372", "0.37849426", "0.37824804", "0.3774954", "0.3774954", "0.37623954", "0.37589484", "0.3750476", "0.37455443", "0.37438574", "0.37421438", "0.37386498", "0.37321633", "0.37281474", "0.37227002", "0.3717515", "0.37172514", "0.3709218", "0.37059516", "0.3704332", "0.37039003", "0.37030816", "0.36977512", "0.3696032", "0.36831555", "0.3672166", "0.36645827", "0.3650726", "0.3643371", "0.36423066", "0.36405477", "0.3639896", "0.36368936", "0.36346367", "0.36227185", "0.36225662", "0.3617304", "0.3617224", "0.36143062", "0.36117905", "0.36112323", "0.3605194", "0.3601287", "0.3592833", "0.3591506", "0.35912246", "0.35851437", "0.357916", "0.3578485", "0.3574484", "0.35743648", "0.35722318", "0.3568744", "0.3563902", "0.35635898", "0.35618553", "0.35596362", "0.35570136", "0.35552138", "0.355299" ]
0.8347728
0
NewSettingsObjectUpdate instantiates a new SettingsObjectUpdate object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed
func NewSettingsObjectUpdate(value map[string]interface{}) *SettingsObjectUpdate { this := SettingsObjectUpdate{} this.Value = value return &this }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewSettingsObjectUpdateWithDefaults() *SettingsObjectUpdate {\n\tthis := SettingsObjectUpdate{}\n\treturn &this\n}", "func NewIntentsItemUpdateSettingsPostRequestBody()(*IntentsItemUpdateSettingsPostRequestBody) {\n m := &IntentsItemUpdateSettingsPostRequestBody{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (settings *Settings) Update(newSettings *Settings) {\n\tif settings == nil {\n\t\treturn\n\t}\n\tif newSettings.ViewsPath == \"\" {\n\t\tsettings.ViewsPath = \".\"\n\t} else {\n\t\tsettings.ViewsPath = newSettings.ViewsPath\n\t}\n\tif newSettings.StaticPath == \"\" {\n\t\tsettings.StaticPath = \".\"\n\t} else {\n\t\tsettings.StaticPath = newSettings.StaticPath\n\t}\n\tif newSettings.ViewExtension == \"\" {\n\t\tsettings.ViewExtension = \"html\"\n\t} else {\n\t\tsettings.ViewExtension = newSettings.ViewExtension\n\t}\n}", "func NewUpdateTimezoneSettingsParams() *UpdateTimezoneSettingsParams {\n\tvar ()\n\treturn &UpdateTimezoneSettingsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewUpdateEHRSettingsRequest(server string, clinicId ClinicId, body UpdateEHRSettingsJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdateEHRSettingsRequestWithBody(server, clinicId, \"application/json\", bodyReader)\n}", "func (c *Client) Update(ctx context.Context, i *UpdateRequest) (*Secret, error) {\n\tif i == nil {\n\t\treturn nil, errors.New(\"missing request\")\n\t}\n\n\tbucket := i.Bucket\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"missing bucket name\")\n\t}\n\n\tobject := i.Object\n\tif object == \"\" {\n\t\treturn nil, errors.New(\"missing object name\")\n\t}\n\n\t// Key and Plaintext may be required depending on whether the object exists.\n\tkey := i.Key\n\tplaintext := i.Plaintext\n\n\tgeneration := i.Generation\n\tmetageneration := i.Metageneration\n\tcreateIfMissing := i.CreateIfMissing\n\n\tlogger := c.Logger().WithFields(logrus.Fields{\n\t\t\"bucket\": bucket,\n\t\t\"object\": object,\n\t\t\"key\": key,\n\t\t\"generation\": generation,\n\t\t\"metageneration\": metageneration,\n\t\t\"create_if_missing\": createIfMissing,\n\t})\n\n\tlogger.Debug(\"update.start\")\n\tdefer logger.Debug(\"update.finish\")\n\n\t// If no specific generations were given, lookup the latest generation to make\n\t// sure we don't conflict with another write.\n\tattrs, err := c.storageClient.\n\t\tBucket(bucket).\n\t\tObject(object).\n\t\tAttrs(ctx)\n\tswitch err {\n\tcase nil:\n\t\tlogger = logger.WithFields(logrus.Fields{\n\t\t\t\"existing.bucket\": attrs.Bucket,\n\t\t\t\"existing.name\": attrs.Name,\n\t\t\t\"existing.size\": attrs.Size,\n\t\t\t\"existing.metadata\": attrs.Metadata,\n\t\t\t\"existing.generation\": attrs.Generation,\n\t\t\t\"existing.metageneration\": attrs.Metageneration,\n\t\t\t\"existing.created\": attrs.Created,\n\t\t\t\"existing.deleted\": attrs.Deleted,\n\t\t\t\"existing.updated\": attrs.Updated,\n\t\t})\n\t\tlogger.Debug(\"found existing storage object\")\n\n\t\tif generation == 0 {\n\t\t\tgeneration = attrs.Generation\n\t\t\tlogger = logger.WithField(\"generation\", generation)\n\t\t\tlogger.Debug(\"setting generation\")\n\t\t}\n\n\t\tif metageneration == 0 {\n\t\t\tmetageneration = attrs.Metageneration\n\t\t\tlogger = logger.WithField(\"metageneration\", metageneration)\n\t\t\tlogger.Debug(\"setting metageneration\")\n\t\t}\n\n\t\tif key == \"\" {\n\t\t\tkey = attrs.Metadata[MetadataKMSKey]\n\t\t\tlogger = logger.WithField(\"key\", key)\n\t\t\tlogger.Debug(\"setting key\")\n\t\t}\n\n\t\tif plaintext == nil {\n\t\t\tlogger.Debug(\"attempting to access plaintext\")\n\n\t\t\tplaintext, err = c.Access(ctx, &AccessRequest{\n\t\t\t\tBucket: bucket,\n\t\t\t\tObject: object,\n\t\t\t\tGeneration: generation,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to get plaintext\")\n\t\t\t}\n\t\t}\n\n\t\t// Get existing IAM policies\n\t\tlogger.Debug(\"getting iam policies\")\n\n\t\tstorageHandle := c.storageIAM(bucket, object)\n\t\tstorageP, err := getIAMPolicy(ctx, storageHandle)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get IAM policy\")\n\t\t}\n\n\t\t// Update the secret\n\t\tlogger.Debug(\"updating secret\")\n\n\t\tsecret, err := c.encryptAndWrite(ctx, bucket, object, key, plaintext,\n\t\t\tgeneration, metageneration)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update secret\")\n\t\t}\n\n\t\t// Copy over the existing IAM memberships, if any\n\t\tlogger.Debug(\"updating iam policies\")\n\n\t\tif err := updateIAMPolicy(ctx, storageHandle, func(p *iam.Policy) *iam.Policy {\n\t\t\t// Copy any IAM permissions from the old object over to the new object.\n\t\t\tfor _, m := range storageP.Members(iamObjectReader) {\n\t\t\t\tp.Add(m, iamObjectReader)\n\t\t\t}\n\t\t\treturn p\n\t\t}); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to update Storage IAM policy for %s\", object)\n\t\t}\n\t\treturn secret, nil\n\tcase storage.ErrObjectNotExist:\n\t\tlogger.Debug(\"secret does not exist\")\n\n\t\tif !createIfMissing {\n\t\t\treturn nil, errSecretDoesNotExist\n\t\t}\n\n\t\tif key == \"\" {\n\t\t\treturn nil, errors.New(\"missing key name\")\n\t\t}\n\n\t\tif plaintext == nil {\n\t\t\treturn nil, errors.New(\"missing plaintext\")\n\t\t}\n\n\t\tlogger.Debug(\"creating secret\")\n\n\t\t// Update the secret.\n\t\tsecret, err := c.encryptAndWrite(ctx, bucket, object, key, plaintext,\n\t\t\tgeneration, metageneration)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update secret\")\n\t\t}\n\t\treturn secret, nil\n\tdefault:\n\t\treturn nil, errors.Wrap(err, \"failed to fetch existing secret\")\n\t}\n}", "func (client *MonitoringSettingsClient) updatePutCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource, options *MonitoringSettingsClientBeginUpdatePutOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/monitoringSettings/default\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, monitoringSettingResource)\n}", "func (obj *SObject) Update() *SObject {\n\tif obj.Type() == \"\" || obj.client() == nil || obj.ID() == \"\" {\n\t\t// Sanity check.\n\t\treturn nil\n\t}\n\n\t// Make a copy of the incoming SObject, but skip certain metadata fields as they're not understood by salesforce.\n\treqObj := obj.makeCopy()\n\treqData, err := json.Marshal(reqObj)\n\tif err != nil {\n\t\tlog.Println(logPrefix, \"failed to convert sobject to json,\", err)\n\t\treturn nil\n\t}\n\n\tqueryBase := \"sobjects/\"\n\tif obj.client().useToolingAPI {\n\t\tqueryBase = \"tooling/sobjects/\"\n\t}\n\turl := obj.client().makeURL(queryBase + obj.Type() + \"/\" + obj.ID())\n\trespData, err := obj.client().httpRequest(http.MethodPatch, url, bytes.NewReader(reqData))\n\tif err != nil {\n\t\tlog.Println(logPrefix, \"failed to process http request,\", err)\n\t\treturn nil\n\t}\n\tlog.Println(string(respData))\n\n\treturn obj\n}", "func NewUpdateMRNSettingsRequest(server string, clinicId ClinicId, body UpdateMRNSettingsJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdateMRNSettingsRequestWithBody(server, clinicId, \"application/json\", bodyReader)\n}", "func (c *RequestSettingConfig) Update(serviceID string, version uint, name string, requestSetting *RequestSetting) (*RequestSetting, *http.Response, error) {\n\tu := fmt.Sprintf(\"/service/%s/version/%d/request_settings/%s\", serviceID, version, name)\n\n\treq, err := c.client.NewJSONRequest(\"PUT\", u, requestSetting)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tb := new(RequestSetting)\n\tresp, err := c.client.Do(req, b)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn b, resp, nil\n}", "func NewUpdateSettingsAclsParams() *UpdateSettingsAclsParams {\n\tvar ()\n\treturn &UpdateSettingsAclsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewSwarmUpdateParams() *SwarmUpdateParams {\n\tvar (\n\t\trotateManagerTokenDefault = bool(false)\n\t\trotateManagerUnlockKeyDefault = bool(false)\n\t\trotateWorkerTokenDefault = bool(false)\n\t)\n\treturn &SwarmUpdateParams{\n\t\tRotateManagerToken: &rotateManagerTokenDefault,\n\t\tRotateManagerUnlockKey: &rotateManagerUnlockKeyDefault,\n\t\tRotateWorkerToken: &rotateWorkerTokenDefault,\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewTeamMemberSettings()(*TeamMemberSettings) {\n m := &TeamMemberSettings{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewUpdateWidgetParams() *UpdateWidgetParams {\n\tvar (\n\t\tacceptDefault = string(\"application/json\")\n\t\tcontentTypeDefault = string(\"application/json\")\n\t)\n\treturn &UpdateWidgetParams{\n\t\tAccept: &acceptDefault,\n\t\tContentType: &contentTypeDefault,\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (client *WebAppsClient) updateApplicationSettingsCreateRequest(ctx context.Context, resourceGroupName string, name string, appSettings StringDictionary, options *WebAppsUpdateApplicationSettingsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/appsettings\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, appSettings)\n}", "func (rm *resourceManager) newUpdateRequestPayload(\n\tr *resource,\n) (*svcsdk.UpdateStageInput, error) {\n\tres := &svcsdk.UpdateStageInput{}\n\n\tif r.ko.Spec.AccessLogSettings != nil {\n\t\tf0 := &svcsdk.AccessLogSettings{}\n\t\tif r.ko.Spec.AccessLogSettings.DestinationARN != nil {\n\t\t\tf0.SetDestinationArn(*r.ko.Spec.AccessLogSettings.DestinationARN)\n\t\t}\n\t\tif r.ko.Spec.AccessLogSettings.Format != nil {\n\t\t\tf0.SetFormat(*r.ko.Spec.AccessLogSettings.Format)\n\t\t}\n\t\tres.SetAccessLogSettings(f0)\n\t}\n\tif r.ko.Spec.APIID != nil {\n\t\tres.SetApiId(*r.ko.Spec.APIID)\n\t}\n\tif r.ko.Spec.AutoDeploy != nil {\n\t\tres.SetAutoDeploy(*r.ko.Spec.AutoDeploy)\n\t}\n\tif r.ko.Spec.ClientCertificateID != nil {\n\t\tres.SetClientCertificateId(*r.ko.Spec.ClientCertificateID)\n\t}\n\tif r.ko.Spec.DefaultRouteSettings != nil {\n\t\tf4 := &svcsdk.RouteSettings{}\n\t\tif r.ko.Spec.DefaultRouteSettings.DataTraceEnabled != nil {\n\t\t\tf4.SetDataTraceEnabled(*r.ko.Spec.DefaultRouteSettings.DataTraceEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled != nil {\n\t\t\tf4.SetDetailedMetricsEnabled(*r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.LoggingLevel != nil {\n\t\t\tf4.SetLoggingLevel(*r.ko.Spec.DefaultRouteSettings.LoggingLevel)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit != nil {\n\t\t\tf4.SetThrottlingBurstLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit != nil {\n\t\t\tf4.SetThrottlingRateLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit)\n\t\t}\n\t\tres.SetDefaultRouteSettings(f4)\n\t}\n\tif r.ko.Spec.DeploymentID != nil {\n\t\tres.SetDeploymentId(*r.ko.Spec.DeploymentID)\n\t}\n\tif r.ko.Spec.Description != nil {\n\t\tres.SetDescription(*r.ko.Spec.Description)\n\t}\n\tif r.ko.Spec.RouteSettings != nil {\n\t\tf7 := map[string]*svcsdk.RouteSettings{}\n\t\tfor f7key, f7valiter := range r.ko.Spec.RouteSettings {\n\t\t\tf7val := &svcsdk.RouteSettings{}\n\t\t\tif f7valiter.DataTraceEnabled != nil {\n\t\t\t\tf7val.SetDataTraceEnabled(*f7valiter.DataTraceEnabled)\n\t\t\t}\n\t\t\tif f7valiter.DetailedMetricsEnabled != nil {\n\t\t\t\tf7val.SetDetailedMetricsEnabled(*f7valiter.DetailedMetricsEnabled)\n\t\t\t}\n\t\t\tif f7valiter.LoggingLevel != nil {\n\t\t\t\tf7val.SetLoggingLevel(*f7valiter.LoggingLevel)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingBurstLimit != nil {\n\t\t\t\tf7val.SetThrottlingBurstLimit(*f7valiter.ThrottlingBurstLimit)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingRateLimit != nil {\n\t\t\t\tf7val.SetThrottlingRateLimit(*f7valiter.ThrottlingRateLimit)\n\t\t\t}\n\t\t\tf7[f7key] = f7val\n\t\t}\n\t\tres.SetRouteSettings(f7)\n\t}\n\tif r.ko.Spec.StageName != nil {\n\t\tres.SetStageName(*r.ko.Spec.StageName)\n\t}\n\tif r.ko.Spec.StageVariables != nil {\n\t\tf9 := map[string]*string{}\n\t\tfor f9key, f9valiter := range r.ko.Spec.StageVariables {\n\t\t\tvar f9val string\n\t\t\tf9val = *f9valiter\n\t\t\tf9[f9key] = &f9val\n\t\t}\n\t\tres.SetStageVariables(f9)\n\t}\n\n\treturn res, nil\n}", "func (x *fastReflection_MsgUpdateParams) New() protoreflect.Message {\n\treturn new(fastReflection_MsgUpdateParams)\n}", "func (client AppsClient) UpdateSettingsPreparer(ctx context.Context, appID uuid.UUID, applicationSettingUpdateObject ApplicationSettingUpdateObject) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"AzureRegion\": client.AzureRegion,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"appId\": autorest.Encode(\"path\", appID),\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithCustomBaseURL(\"https://{AzureRegion}.api.cognitive.microsoft.com/luis/api/v2.0\", urlParameters),\n\t\tautorest.WithPathParameters(\"/apps/{appId}/settings\", pathParameters),\n\t\tautorest.WithJSON(applicationSettingUpdateObject))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *MonitoringSettingsClient) updatePatchCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, monitoringSettingResource MonitoringSettingResource, options *MonitoringSettingsClientBeginUpdatePatchOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/monitoringSettings/default\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, monitoringSettingResource)\n}", "func New(config Config) (*Updater, error) {\n\t// Everything we need it set?\n\tif config.InstallsDir == \"\" {\n\t\treturn nil, errors.New(\"InstallsDir must be set\")\n\t}\n\tif config.WorkingDir == \"\" {\n\t\treturn nil, errors.New(\"WorkingDir must be set\")\n\t}\n\tif config.UpdateURL == \"\" {\n\t\treturn nil, errors.New(\"UpdateURL must be set\")\n\t}\n\tif config.ClientID == \"\" {\n\t\treturn nil, errors.New(\"ClientID must be set\")\n\t}\n\t// Paths exist?\n\tfileInfo, err := os.Stat(config.InstallsDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !fileInfo.IsDir() {\n\t\treturn nil, errors.New(\"InstallDir must be a directory\")\n\t}\n\tfileInfo, err = os.Stat(config.WorkingDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !fileInfo.IsDir() {\n\t\treturn nil, errors.New(\"InstallDir must be a directory\")\n\t}\n\t// All ok\n\tupdater := Updater{\n\t\tconfig: config,\n\t}\n\terr = updater.updateVersionMap()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to update version map: %s\", err.Error())\n\t}\n\treturn &updater, nil\n}", "func NewUpdateAddonParams() *UpdateAddonParams {\n\tvar ()\n\treturn &UpdateAddonParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func newUpdateCfgCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"update\",\n\t\tShort: \"update the given config\",\n\t\tRunE: func(command *cobra.Command, _ []string) error {\n\t\t\tcomp, err := command.Flags().GetString(\"comp\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsub, err := command.Flags().GetString(\"subsystem\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsubs := strings.Split(sub, \",\")\n\t\t\tname, err := command.Flags().GetString(\"name\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalue, err := command.Flags().GetString(\"value\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstore, err := command.Flags().GetUint64(\"store\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = defaultConfigClient.Update(comp, subs, name, value, store)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcommand.Flags().StringP(\"comp\", \"c\", \"tikv\", \"update component config\")\n\tcommand.Flags().StringP(\"subsystem\", \"b\", \"raftstore\", \"update a subsystem config\")\n\tcommand.Flags().StringP(\"name\", \"k\", \"\", \"update the given config\")\n\tcommand.Flags().StringP(\"value\", \"v\", \"\",\n\t\t\"update the given config with the value\")\n\tcommand.Flags().Uint64P(\"store\", \"s\", 0,\n\t\t\"update the given store ids value\")\n\tcommand.MarkFlagRequired(\"comp\")\n\tcommand.MarkFlagRequired(\"name\")\n\tcommand.MarkFlagRequired(\"value\")\n\treturn command\n}", "func (m *IntentsDeviceManagementIntentItemRequestBuilder) UpdateSettings()(*IntentsItemUpdateSettingsRequestBuilder) {\n return NewIntentsItemUpdateSettingsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func NewUpdateProjectSettingsDefault(code int) *UpdateProjectSettingsDefault {\n\treturn &UpdateProjectSettingsDefault{\n\t\t_statusCode: code,\n\t}\n}", "func setMetadataForUpdate(existingObj *unstructured.Unstructured, objForUpdate *unstructured.Unstructured) {\n\tif logger.IsEnabled(LogTypeEntry) {\n\t\tlogger.Log(CallerName(), LogTypeEntry, fmt.Sprintf(\"setMetadataForUpdate\"))\n\t}\n\tvar objMap = existingObj.Object\n\tmetadataObj, ok := objMap[METADATA]\n\tvar metadata map[string]interface{}\n\tif !ok {\n\t\tmetadata = make(map[string]interface{})\n\t\tobjMap[METADATA] = metadata\n\t} else {\n\t\tmetadata = metadataObj.(map[string]interface{})\n\t}\n\n\tvar objMapForUpdate = objForUpdate.Object\n\tobjMapForUpdate[METADATA] = metadata\n\n\tif logger.IsEnabled(LogTypeExit) {\n\t\tlogger.Log(CallerName(), LogTypeExit, fmt.Sprintf(\"setMetadataForUpdate: update metadata %s is set\", metadata))\n\t}\n}", "func NewUpdateCommand(parent cmd.Registerer, g *global.Data, m manifest.Data) *UpdateCommand {\n\tc := UpdateCommand{\n\t\tBase: cmd.Base{\n\t\t\tGlobals: g,\n\t\t},\n\t\tmanifest: m,\n\t}\n\tc.CmdClause = parent.Command(\"update\", \"Update name of dictionary on a Fastly service version\").Alias(\"get\")\n\n\t// Required.\n\tc.CmdClause.Flag(\"name\", \"Old name of Dictionary\").Short('n').Required().StringVar(&c.input.Name)\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagVersionName,\n\t\tDescription: cmd.FlagVersionDesc,\n\t\tDst: &c.serviceVersion.Value,\n\t\tRequired: true,\n\t})\n\n\t// Optional.\n\tc.RegisterAutoCloneFlag(cmd.AutoCloneFlagOpts{\n\t\tAction: c.autoClone.Set,\n\t\tDst: &c.autoClone.Value,\n\t})\n\tc.CmdClause.Flag(\"new-name\", \"New name of Dictionary\").Action(c.newname.Set).StringVar(&c.newname.Value)\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagServiceIDName,\n\t\tDescription: cmd.FlagServiceIDDesc,\n\t\tDst: &c.manifest.Flag.ServiceID,\n\t\tShort: 's',\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tAction: c.serviceName.Set,\n\t\tName: cmd.FlagServiceName,\n\t\tDescription: cmd.FlagServiceDesc,\n\t\tDst: &c.serviceName.Value,\n\t})\n\tc.CmdClause.Flag(\"write-only\", \"Whether to mark this dictionary as write-only. Can be true or false (defaults to false)\").Action(c.writeOnly.Set).StringVar(&c.writeOnly.Value)\n\treturn &c\n}", "func (client *MockClient) Update(context ctx.Context, object ctrlClient.Object, options ...ctrlClient.UpdateOption) error {\n\tkindKey, err := buildKindKey(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.fillInMaps(kindKey)\n\n\tjsonData, err := json.Marshal(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobjectKey, err := buildJSONObjectKey(jsonData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = client.checkPresence(kindKey, objectKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingObject := client.data[kindKey][objectKey]\n\n\tnewObject := make(map[string]interface{})\n\terr = json.Unmarshal(jsonData, &newObject)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !reflect.DeepEqual(existingObject[\"spec\"], newObject[\"spec\"]) {\n\t\tgeneration, err := incrementGeneration(existingObject)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = setGeneration(newObject, generation)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tclient.data[kindKey][objectKey] = newObject\n\n\tjsonData, err = json.Marshal(newObject)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(jsonData, object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewUpdateFolderParams() *UpdateFolderParams {\n\treturn &UpdateFolderParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func newUpdateConnectionSettingsFrame(settings connectionSettings) frame {\n\t// Prepare frame.\n\tpayload := encoding.Marshal(settings)\n\tf := frame{\n\t\tframeHeader: frameHeader{\n\t\t\tid: frameIDUpdateSettings,\n\t\t\tlength: uint32(len(payload)),\n\t\t\tflags: 0,\n\t\t},\n\t\tpayload: payload,\n\t}\n\treturn f\n}", "func (a *UserServiceApiService) UpdateObject(ctx _context.Context, username string) ApiUpdateObjectRequest {\n\treturn ApiUpdateObjectRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tusername: username,\n\t}\n}", "func (client *WebAppsClient) updateAuthSettingsCreateRequest(ctx context.Context, resourceGroupName string, name string, siteAuthSettings SiteAuthSettings, options *WebAppsUpdateAuthSettingsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/authsettings\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, siteAuthSettings)\n}", "func NewUpdateAccountMemberParams() *UpdateAccountMemberParams {\n\tvar ()\n\treturn &UpdateAccountMemberParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (ag *AccountService) UpdateSettings(opts *Optionals) (newSettings *AccountSettings, err error) {\n\tif opts == nil {\n\t\topts = NewOptionals()\n\t}\n\tnewSettings = &AccountSettings{}\n\terr = ag.Call(\"POST\", \"account/settings\", opts, newSettings)\n\treturn\n}", "func (client *WebAppsClient) updateSitePushSettingsCreateRequest(ctx context.Context, resourceGroupName string, name string, pushSettings PushSettings, options *WebAppsUpdateSitePushSettingsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/pushsettings\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, pushSettings)\n}", "func (r *UpdateInstanceRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"InstanceName\")\n\tdelete(f, \"NodeNum\")\n\tdelete(f, \"EsConfig\")\n\tdelete(f, \"Password\")\n\tdelete(f, \"EsAcl\")\n\tdelete(f, \"DiskSize\")\n\tdelete(f, \"NodeType\")\n\tdelete(f, \"MasterNodeNum\")\n\tdelete(f, \"MasterNodeType\")\n\tdelete(f, \"MasterNodeDiskSize\")\n\tdelete(f, \"ForceRestart\")\n\tdelete(f, \"CosBackup\")\n\tdelete(f, \"NodeInfoList\")\n\tdelete(f, \"PublicAccess\")\n\tdelete(f, \"EsPublicAcl\")\n\tdelete(f, \"KibanaPublicAccess\")\n\tdelete(f, \"KibanaPrivateAccess\")\n\tdelete(f, \"BasicSecurityType\")\n\tdelete(f, \"KibanaPrivatePort\")\n\tdelete(f, \"ScaleType\")\n\tdelete(f, \"MultiZoneInfo\")\n\tdelete(f, \"SceneType\")\n\tdelete(f, \"KibanaConfig\")\n\tdelete(f, \"WebNodeTypeInfo\")\n\tdelete(f, \"SwitchPrivateLink\")\n\tdelete(f, \"EnableCerebro\")\n\tdelete(f, \"CerebroPublicAccess\")\n\tdelete(f, \"CerebroPrivateAccess\")\n\tdelete(f, \"EsConfigSet\")\n\tdelete(f, \"OperationDuration\")\n\tdelete(f, \"KibanaAlteringPublicAccess\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"UpdateInstanceRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func newUpdateKeyUpdateKeyRequest(ctx context.Context, f *Key, c *Client) (map[string]interface{}, error) {\n\treq := map[string]interface{}{}\n\tres := f\n\t_ = res\n\n\tif v := f.DisplayName; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"displayName\"] = v\n\t}\n\tif v, err := expandKeyWebSettings(c, f.WebSettings, res); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding WebSettings into webSettings: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"webSettings\"] = v\n\t}\n\tif v, err := expandKeyAndroidSettings(c, f.AndroidSettings, res); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding AndroidSettings into androidSettings: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"androidSettings\"] = v\n\t}\n\tif v, err := expandKeyIosSettings(c, f.IosSettings, res); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding IosSettings into iosSettings: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"iosSettings\"] = v\n\t}\n\tif v := f.Labels; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"labels\"] = v\n\t}\n\treturn req, nil\n}", "func (r *DeviceManagementDerivedCredentialSettingsRequest) Update(ctx context.Context, reqObj *DeviceManagementDerivedCredentialSettings) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (r *DeviceManagementDerivedCredentialSettingsRequest) Update(ctx context.Context, reqObj *DeviceManagementDerivedCredentialSettings) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func NewUpdateCommand(parent cmd.Registerer, g *global.Data, m manifest.Data) *UpdateCommand {\n\tc := UpdateCommand{\n\t\tBase: cmd.Base{\n\t\t\tGlobals: g,\n\t\t},\n\t\tmanifest: m,\n\t}\n\tc.CmdClause = parent.Command(\"update\", \"Update a Fastly service version\")\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagServiceIDName,\n\t\tDescription: cmd.FlagServiceIDDesc,\n\t\tDst: &c.manifest.Flag.ServiceID,\n\t\tShort: 's',\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tAction: c.serviceName.Set,\n\t\tName: cmd.FlagServiceName,\n\t\tDescription: cmd.FlagServiceDesc,\n\t\tDst: &c.serviceName.Value,\n\t})\n\tc.RegisterFlag(cmd.StringFlagOpts{\n\t\tName: cmd.FlagVersionName,\n\t\tDescription: cmd.FlagVersionDesc,\n\t\tDst: &c.serviceVersion.Value,\n\t\tRequired: true,\n\t})\n\tc.RegisterAutoCloneFlag(cmd.AutoCloneFlagOpts{\n\t\tAction: c.autoClone.Set,\n\t\tDst: &c.autoClone.Value,\n\t})\n\n\t// TODO(integralist):\n\t// Make 'comment' field mandatory once we roll out a new release of Go-Fastly\n\t// which will hopefully have better/more correct consistency as far as which\n\t// fields are supposed to be optional and which should be 'required'.\n\t//\n\tc.CmdClause.Flag(\"comment\", \"Human-readable comment\").Action(c.comment.Set).StringVar(&c.comment.Value)\n\treturn &c\n}", "func NewUpdateServiceInput(config map[string]interface{}) (*ecs.UpdateServiceInput, error){\n\t// TODO: may make a struct for this to take... then again, that basically becomes UpdateServiceInput...\n\t// but maybe can simplify it slightly or something.\n\n\tserviceName := aws.String(config[\"name\"].(string))\n\t// https://docs.aws.amazon.com/sdk-for-go/api/service/ecs/#UpdateServiceInput\n\tinput := &ecs.UpdateServiceInput{Service: serviceName}\n\n\tif taskDef, ok := config[\"task_definition\"]; ok {\n\t\tinput = input.SetTaskDefinition(taskDef.(string)) // seems to be not required - perhaps can update things without changing the task def.\n\t}\n\n\tif cluster, ok := config[\"cluster\"]; ok {\n\t\tinput = input.SetCluster(cluster.(string))\n\t}\n\n\tif desiredCount, ok := config[\"desired_count\"]; ok {\n\t\tinput = input.SetDesiredCount(desiredCount.(int64))\n\t}\n\n\t// TODO: Unsure if this should come in on config or be passed in as a standalone arg. It feels like a standlone arg\n\t// and command line only flag rather than config file thing.\n\tif forceDeployment, ok := config[\"force_deployment\"]; ok {\n\t\tif forceDeployment.(bool) {\n\t\t\tinput = input.SetForceNewDeployment(true)\n\t\t}\n\t}\n\n\tnetworkConfig, err := netconfig.NewNetworkConfiguration(config)\n\tinput.SetNetworkConfiguration(&networkConfig)\n\tif err != nil {\n\t\treturn input, err\n\t}\n\n\t// TODO: other otpions\n\t// fmt.Printf(\"\\n\\nINPUT: %v\\n\\n\", input)\n\treturn input, input.Validate()\n}", "func (xdcrf *XDCRFactory) ConstructUpdateSettingsForService(pipeline common.Pipeline, service common.PipelineService, settings metadata.ReplicationSettingsMap) (metadata.ReplicationSettingsMap, error) {\n\tswitch service.(type) {\n\tcase *pipeline_svc.PipelineSupervisor:\n\t\txdcrf.logger.Debug(\"Construct update settings for PipelineSupervisor\")\n\t\treturn xdcrf.constructUpdateSettingsForSupervisor(pipeline, settings)\n\tcase *pipeline_svc.StatisticsManager:\n\t\txdcrf.logger.Debug(\"Construct update settings for StatisticsManager\")\n\t\treturn xdcrf.constructUpdateSettingsForStatsManager(pipeline, settings)\n\tcase *pipeline_svc.CheckpointManager:\n\t\txdcrf.logger.Debug(\"Construct update settings for CheckpointManager\")\n\t\treturn xdcrf.constructUpdateSettingsForCheckpointManager(pipeline, settings)\n\tcase *pipeline_svc.BandwidthThrottler:\n\t\txdcrf.logger.Debug(\"Construct update settings for BandwidthThrottler\")\n\t\treturn xdcrf.constructUpdateSettingsForBandwidthThrottler(pipeline, settings)\n\t}\n\treturn settings, nil\n}", "func (u UpdateShortMessage) construct() UpdatesClass { return &u }", "func (r *AndroidManagedStoreAccountEnterpriseSettingsRequest) Update(ctx context.Context, reqObj *AndroidManagedStoreAccountEnterpriseSettings) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (r *DeviceManagementSettingInstanceRequest) Update(ctx context.Context, reqObj *DeviceManagementSettingInstance) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (r *DeviceManagementSettingInstanceRequest) Update(ctx context.Context, reqObj *DeviceManagementSettingInstance) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func newUpdateDefaultObjectAccessControlUpdateRequest(ctx context.Context, f *DefaultObjectAccessControl, c *Client) (map[string]interface{}, error) {\n\treq := map[string]interface{}{}\n\n\tif v := f.Entity; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"entity\"] = v\n\t}\n\tif v := f.Role; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"role\"] = v\n\t}\n\treturn req, nil\n}", "func (r *DeviceManagementComplexSettingInstanceRequest) Update(ctx context.Context, reqObj *DeviceManagementComplexSettingInstance) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func NewUpdateBuildPropertiesParams() *UpdateBuildPropertiesParams {\n\tvar ()\n\treturn &UpdateBuildPropertiesParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func updateToCreateOptions(uo *metav1.UpdateOptions) *metav1.CreateOptions {\n\tif uo == nil {\n\t\treturn nil\n\t}\n\tco := &metav1.CreateOptions{\n\t\tDryRun: uo.DryRun,\n\t\tFieldManager: uo.FieldManager,\n\t\tFieldValidation: uo.FieldValidation,\n\t}\n\tco.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"CreateOptions\"))\n\treturn co\n}", "func NewUpdateProjectSettingsOK() *UpdateProjectSettingsOK {\n\treturn &UpdateProjectSettingsOK{}\n}", "func (r *SingleValueLegacyExtendedPropertyRequest) Update(ctx context.Context, reqObj *SingleValueLegacyExtendedProperty) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func (c *Config) Update(c2 Config) {\n\tif c2.ClientID != \"\" {\n\t\tc.ClientID = c2.ClientID\n\t}\n\tif c2.Quality != \"\" {\n\t\tc.Quality = c2.Quality\n\t}\n\tif c2.StartTime != \"\" {\n\t\tc.StartTime = c2.StartTime\n\t}\n\tif c2.EndTime != \"\" {\n\t\tc.EndTime = c2.EndTime\n\t}\n\tif c2.Length != \"\" {\n\t\tc.EndTime = c2.Length\n\t}\n\tif c2.VodID != 0 {\n\t\tc.VodID = c2.VodID\n\t}\n\tif c2.FilePrefix != \"\" {\n\t\tc.FilePrefix = c2.FilePrefix\n\t}\n\tif c2.OutputFolder != \"\" {\n\t\tc.OutputFolder = c2.OutputFolder\n\t}\n\tif c2.Workers != 0 {\n\t\tc.Workers = c2.Workers\n\t}\n}", "func NewUpdateCredentialParams() *UpdateCredentialParams {\n\tvar ()\n\treturn &UpdateCredentialParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewUpdateCommand(parent common.Registerer, globals *config.Data) *UpdateCommand {\n\tvar c UpdateCommand\n\tc.Globals = globals\n\tc.CmdClause = parent.Command(\"update\", \"Update a backend on a Fastly service version\")\n\n\tc.CmdClause.Flag(\"service-id\", \"Service ID\").Short('s').Required().StringVar(&c.Input.Service)\n\tc.CmdClause.Flag(\"version\", \"Number of service version\").Required().IntVar(&c.Input.Version)\n\tc.CmdClause.Flag(\"name\", \"backend name\").Short('n').Required().StringVar(&c.Input.Name)\n\n\tc.CmdClause.Flag(\"new-name\", \"New backend name\").Action(c.NewName.Set).StringVar(&c.NewName.Value)\n\tc.CmdClause.Flag(\"comment\", \"A descriptive note\").Action(c.Comment.Set).StringVar(&c.Comment.Value)\n\tc.CmdClause.Flag(\"address\", \"A hostname, IPv4, or IPv6 address for the backend\").Action(c.Address.Set).StringVar(&c.Address.Value)\n\tc.CmdClause.Flag(\"port\", \"Port number of the address\").Action(c.Port.Set).UintVar(&c.Port.Value)\n\tc.CmdClause.Flag(\"override-host\", \"The hostname to override the Host header\").Action(c.OverrideHost.Set).StringVar(&c.OverrideHost.Value)\n\tc.CmdClause.Flag(\"connect-timeout\", \"How long to wait for a timeout in milliseconds\").Action(c.ConnectTimeout.Set).UintVar(&c.ConnectTimeout.Value)\n\tc.CmdClause.Flag(\"max-conn\", \"Maximum number of connections\").Action(c.MaxConn.Set).UintVar(&c.MaxConn.Value)\n\tc.CmdClause.Flag(\"first-byte-timeout\", \"How long to wait for the first bytes in milliseconds\").Action(c.FirstByteTimeout.Set).UintVar(&c.MaxConn.Value)\n\tc.CmdClause.Flag(\"between-bytes-timeout\", \"How long to wait between bytes in milliseconds\").Action(c.BetweenBytesTimeout.Set).UintVar(&c.BetweenBytesTimeout.Value)\n\tc.CmdClause.Flag(\"auto-loadbalance\", \"Whether or not this backend should be automatically load balanced\").Action(c.AutoLoadbalance.Set).BoolVar(&c.AutoLoadbalance.Value)\n\tc.CmdClause.Flag(\"weight\", \"Weight used to load balance this backend against others\").Action(c.Weight.Set).UintVar(&c.Weight.Value)\n\tc.CmdClause.Flag(\"request-condition\", \"condition, which if met, will select this backend during a request\").Action(c.RequestCondition.Set).StringVar(&c.RequestCondition.Value)\n\tc.CmdClause.Flag(\"healthcheck\", \"The name of the healthcheck to use with this backend\").Action(c.HealthCheck.Set).StringVar(&c.HealthCheck.Value)\n\tc.CmdClause.Flag(\"shield\", \"The shield POP designated to reduce inbound load on this origin by serving the cached data to the rest of the network\").Action(c.Shield.Set).StringVar(&c.Shield.Value)\n\tc.CmdClause.Flag(\"use-ssl\", \"Whether or not to use SSL to reach the backend\").Action(c.UseSSL.Set).BoolVar(&c.UseSSL.Value)\n\tc.CmdClause.Flag(\"ssl-check-cert\", \"Be strict on checking SSL certs\").Action(c.SSLCheckCert.Set).BoolVar(&c.SSLCheckCert.Value)\n\tc.CmdClause.Flag(\"ssl-ca-cert\", \"CA certificate attached to origin\").Action(c.SSLCACert.Set).StringVar(&c.SSLCACert.Value)\n\tc.CmdClause.Flag(\"ssl-client-cert\", \"Client certificate attached to origin\").Action(c.SSLClientCert.Set).StringVar(&c.SSLClientCert.Value)\n\tc.CmdClause.Flag(\"ssl-client-key\", \"Client key attached to origin\").Action(c.SSLClientKey.Set).StringVar(&c.SSLClientKey.Value)\n\tc.CmdClause.Flag(\"ssl-cert-hostname\", \"Overrides ssl_hostname, but only for cert verification. Does not affect SNI at all.\").Action(c.SSLCertHostname.Set).StringVar(&c.SSLCertHostname.Value)\n\tc.CmdClause.Flag(\"ssl-sni-hostname\", \"Overrides ssl_hostname, but only for SNI in the handshake. Does not affect cert validation at all.\").Action(c.SSLSNIHostname.Set).StringVar(&c.SSLSNIHostname.Value)\n\tc.CmdClause.Flag(\"min-tls-version\", \"Minimum allowed TLS version on SSL connections to this backend\").Action(c.MinTLSVersion.Set).StringVar(&c.MinTLSVersion.Value)\n\tc.CmdClause.Flag(\"max-tls-version\", \"Maximum allowed TLS version on SSL connections to this backend\").Action(c.MaxTLSVersion.Set).StringVar(&c.MaxTLSVersion.Value)\n\tc.CmdClause.Flag(\"ssl-ciphers\", \"List of OpenSSL ciphers (see https://www.openssl.org/docs/man1.0.2/man1/ciphers for details)\").Action(c.SSLCiphers.Set).StringsVar(&c.SSLCiphers.Value)\n\n\treturn &c\n}", "func (r *DeviceManagementAbstractComplexSettingInstanceRequest) Update(ctx context.Context, reqObj *DeviceManagementAbstractComplexSettingInstance) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func newUpdateParam4Update(req *http.Request) (*UpdateParam, error) {\n\tparam := &UpdateParam{}\n\terr := xreq.BindURI(req, param)\n\n\treturn param, err\n}", "func NewUpdate(zone string, class uint16) *Msg {\n\tu := new(Msg)\n\tu.MsgHdr.Response = false\n\tu.MsgHdr.Opcode = OpcodeUpdate\n\tu.Compress = false // Seems BIND9 at least cannot handle compressed update pkgs\n\tu.Question = make([]Question, 1)\n\tu.Question[0] = Question{zone, TypeSOA, class}\n\treturn u\n}", "func (d *DynamoConn) UpdateSettings(settings *models.Settings) error {\n\tvar SettingsUpdate struct {\n\t\tSOSSMS bool `json:\":a\"`\n\t\tSOSCalls bool `json:\":b\"`\n\t\tSOSLockscreenInfo bool `json:\":c\"`\n\t\tUpdates bool `json:\":d\"`\n\t\tUpdateFrequency int `json:\":e\"`\n\t}\n\n\t// Marshal the update expression struct for DynamoDB\n\tSettingsUpdate.SOSSMS = settings.SOSSMS\n\tSettingsUpdate.SOSCalls = settings.SOSCalls\n\tSettingsUpdate.SOSLockscreenInfo = settings.SOSLockscreenInfo\n\tSettingsUpdate.Updates = settings.Updates\n\tSettingsUpdate.UpdateFrequency = settings.UpdateFrequency\n\n\texpr, err := dynamodbattribute.MarshalMap(SettingsUpdate)\n\tif err != nil {\n\t\treturn err\n\n\t}\n\n\t// Define table schema's key\n\tkey := map[string]*dynamodb.AttributeValue{\n\t\t\"user_id\": {\n\t\t\tS: aws.String(settings.UserID),\n\t\t},\n\t}\n\n\t// Use marshalled map for UpdateItemInput\n\titem := &dynamodb.UpdateItemInput{\n\t\tExpressionAttributeValues: expr,\n\t\tTableName: aws.String(common.SettingsTableName),\n\t\tKey: key,\n\t\tReturnValues: aws.String(\"UPDATED_NEW\"),\n\t\tUpdateExpression: aws.String(\"set sos_sms = :a, sos_calls = :b, sos_lockscreen = :c, updates = :d, update_frequency = :e\"),\n\t}\n\n\t// Invoke the update\n\t_, err = d.Client.UpdateItem(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (x *fastReflection_MsgUpdateParamsResponse) New() protoreflect.Message {\n\treturn new(fastReflection_MsgUpdateParamsResponse)\n}", "func NewUpdateProjectSettingsNoContent() *UpdateProjectSettingsNoContent {\n\treturn &UpdateProjectSettingsNoContent{}\n}", "func newUpdateHttpsHealthCheckUpdateRequest(ctx context.Context, f *HttpsHealthCheck, c *Client) (map[string]interface{}, error) {\n\treq := map[string]interface{}{}\n\n\tif v := f.CheckIntervalSec; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"checkIntervalSec\"] = v\n\t}\n\tif v := f.Description; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"description\"] = v\n\t}\n\tif v := f.HealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"healthyThreshold\"] = v\n\t}\n\tif v := f.Host; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"host\"] = v\n\t}\n\tif v := f.Port; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"port\"] = v\n\t}\n\tif v := f.RequestPath; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"requestPath\"] = v\n\t}\n\tif v := f.TimeoutSec; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"timeoutSec\"] = v\n\t}\n\tif v := f.UnhealthyThreshold; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"unhealthyThreshold\"] = v\n\t}\n\treturn req, nil\n}", "func NewUpdateDeviceParams() *UpdateDeviceParams {\n\tvar ()\n\treturn &UpdateDeviceParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (w *wireguardServerConfig) Update(obj *api.WireguardServerConfig) error {\n\tobj.UpdatedAt = time.Now().UTC().Format(time.RFC3339)\n\tjsonData, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// if err := w.store.CreateBucketIfNotExists(obj.UID); err != nil {\n\t// \treturn err\n\t// }\n\treturn w.store.Set(path.Join(w.prefix, obj.UID), jsonData)\n}", "func (s *Service) Update(r *http.Request, args *UpdateEntryArgs, result *UpdateResponse) error {\n\t// Since there is no fixed data schema, we can update as we like, so be careful\n\tif args.UserID == \"\" {\n\t\tresult.Message = uidMissing\n\t\treturn nil\n\t}\n\tuuid := args.UUID\n\tif uuid != \"\" {\n\t\tcoll := s.Session.DB(MentatDatabase).C(args.UserID)\n\t\tentry := Entry{}\n\t\tmgoErr := coll.Find(bson.M{\"uuid\": uuid}).One(&entry)\n\t\tif mgoErr != nil {\n\t\t\tif mgoErr.Error() == MongoNotFound {\n\t\t\t\tresult.Message = \"No entry with provided UUID\"\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ts.Log.Infof(\"mgo error: %s\", mgoErr)\n\t\t\tresult.Message = fmt.Sprintf(\"mgo error: %s\", mgoErr)\n\t\t\treturn nil\n\t\t}\n\t\t// TODO: maybe use reflection\n\t\tif args.Type != \"\" {\n\t\t\tentry.Type = args.Type\n\t\t}\n\t\tif args.Content != \"\" {\n\t\t\tentry.Content = args.Content\n\t\t}\n\t\tif len(args.Tags) > 0 {\n\t\t\tentry.Tags = args.Tags\n\t\t}\n\t\tif args.Scheduled != \"\" {\n\t\t\tscheduled, err := time.Parse(DatetimeLayout, args.Scheduled)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tentry.Scheduled = scheduled\n\t\t}\n\t\tif args.Deadline != \"\" {\n\t\t\tdeadline, err := time.Parse(DatetimeLayout, args.Deadline)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tentry.Deadline = deadline\n\t\t}\n\n\t\tif args.Priority != \"\" {\n\t\t\trexp, err := regexp.Compile(\"\\\\#[A-Z]$\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // sentinel, should fail, because such error is predictable\n\t\t\t}\n\t\t\tif rexp.Match([]byte(args.Priority)) {\n\t\t\t\tentry.Priority = args.Priority\n\t\t\t} else {\n\t\t\t\tresult.Message = \"Malformed priority value\"\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif args.TodoStatus != \"\" {\n\t\t\tentry.TodoStatus = strings.ToUpper(args.TodoStatus)\n\t\t}\n\t\tentry.ModifiedAt = time.Now()\n\t\t_, err := coll.Upsert(bson.M{\"uuid\": uuid}, entry)\n\t\tif err != nil {\n\t\t\tresult.Message = fmt.Sprintf(\"update failed: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t\tresult.Message = \"updated\"\n\t\treturn nil\n\t}\n\tresult.Message = \"No UUID found, cannot proceed with updating\"\n\treturn nil\n}", "func NewUpdateParamsCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"update [change-file]\",\n\t\tShort: \"UpdateValidator params\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclientCtx, err := client.GetClientTxContext(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tchanges, _ := utils.ParseParamChange(clientCtx.LegacyAmino, args[0])\n\n\t\t\tmsg := types.NewMsgUpdateParams(\n\t\t\t\tchanges.ToParamChanges(),\n\t\t\t\tclientCtx.GetFromAddress(),\n\t\t\t)\n\n\t\t\tif err := msg.ValidateBasic(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)\n\t\t},\n\t}\n\n\tflags.AddTxFlagsToCmd(cmd)\n\t_ = cmd.MarkFlagRequired(flags.FlagFrom)\n\n\treturn cmd\n}", "func NewMobileAppInstallTimeSettings()(*MobileAppInstallTimeSettings) {\n m := &MobileAppInstallTimeSettings{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func (a *APIUpdatingApplicator) Apply(ctx context.Context, o client.Object, ao ...ApplyOption) error {\n\tm, ok := o.(Object)\n\tif !ok {\n\t\treturn errors.New(\"cannot access object metadata\")\n\t}\n\n\tif m.GetName() == \"\" && m.GetGenerateName() != \"\" {\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\n\tcurrent := o.DeepCopyObject().(client.Object)\n\n\terr := a.client.Get(ctx, types.NamespacedName{Name: m.GetName(), Namespace: m.GetNamespace()}, current)\n\tif kerrors.IsNotFound(err) {\n\t\t// TODO: Apply ApplyOptions here too?\n\t\treturn errors.Wrap(a.client.Create(ctx, m), \"cannot create object\")\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get object\")\n\t}\n\n\tfor _, fn := range ao {\n\t\tif err := fn(ctx, current, m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// NOTE: we must set the resource version of the desired object\n\t// to that of the current or the update will always fail.\n\tm.SetResourceVersion(current.(metav1.Object).GetResourceVersion())\n\treturn errors.Wrap(a.client.Update(ctx, m), \"cannot update object\")\n}", "func (a *apiEndpoint) Update() error {\n\ta.e.mutex.RLock()\n\ta.SetEntry(\"server\", api.String(a.e.poolEntry.Desc))\n\ta.SetEntry(\"status\", api.String(a.e.status.String()))\n\tif a.e.lastErr != nil {\n\t\ta.SetEntry(\"last_error\", api.String(a.e.lastErr.Error()))\n\t\ta.SetEntry(\"last_error_time\", api.String(a.e.lastErrTime.Format(time.RFC3339)))\n\t} else {\n\t\ta.SetEntry(\"last_error\", api.Null)\n\t\ta.SetEntry(\"last_error_time\", api.Null)\n\t}\n\ta.SetEntry(\"pendingPayloads\", api.Number(a.e.NumPending()))\n\ta.SetEntry(\"publishedLines\", api.Number(a.e.LineCount()))\n\ta.SetEntry(\"averageLatency\", api.Float(a.e.AverageLatency()/time.Millisecond))\n\ta.e.mutex.RUnlock()\n\n\treturn nil\n}", "func Update() *UpdateOptions {\n\treturn &UpdateOptions{}\n}", "func (rm *resourceManager) newUpdateRequestPayload(\n\tctx context.Context,\n\tr *resource,\n) (*svcsdk.UpdateModelPackageInput, error) {\n\tres := &svcsdk.UpdateModelPackageInput{}\n\n\tif r.ko.Spec.ApprovalDescription != nil {\n\t\tres.SetApprovalDescription(*r.ko.Spec.ApprovalDescription)\n\t}\n\tif r.ko.Spec.ModelApprovalStatus != nil {\n\t\tres.SetModelApprovalStatus(*r.ko.Spec.ModelApprovalStatus)\n\t}\n\tif r.ko.Status.ACKResourceMetadata != nil && r.ko.Status.ACKResourceMetadata.ARN != nil {\n\t\tres.SetModelPackageArn(string(*r.ko.Status.ACKResourceMetadata.ARN))\n\t} else {\n\t\tres.SetModelPackageArn(rm.ARNFromName(*r.ko.Spec.ModelPackageName))\n\t}\n\n\treturn res, nil\n}", "func (client MockStatusClient) Update(context ctx.Context, object ctrlClient.Object, options ...ctrlClient.UpdateOption) error {\n\tkindKey, err := buildKindKey(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.rawClient.fillInMaps(kindKey)\n\n\tjsonData, err := json.Marshal(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobjectKey, err := buildJSONObjectKey(jsonData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = client.rawClient.checkPresence(kindKey, objectKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingObject := client.rawClient.data[kindKey][objectKey]\n\n\tnewObject := make(map[string]interface{})\n\terr = json.Unmarshal(jsonData, &newObject)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingObject[\"status\"] = newObject[\"status\"]\n\tclient.rawClient.data[kindKey][objectKey] = existingObject\n\n\treturn nil\n}", "func UpdateUpstream(original, desired *v1.Upstream) {\n\n\t// do not override ssl and subset config if none specified by discovery\n\tif desired.GetSslConfig() == nil {\n\t\tdesired.SslConfig = original.GetSslConfig()\n\t}\n\n\tif desired.GetHttpConnectSslConfig() == nil {\n\t\tdesired.HttpConnectSslConfig = original.GetHttpConnectSslConfig()\n\t}\n\n\tif desired.GetCircuitBreakers() == nil {\n\t\tdesired.CircuitBreakers = original.GetCircuitBreakers()\n\t}\n\n\tif desired.GetLoadBalancerConfig() == nil {\n\t\tdesired.LoadBalancerConfig = original.GetLoadBalancerConfig()\n\t}\n\n\tif desired.GetConnectionConfig() == nil {\n\t\tdesired.ConnectionConfig = original.GetConnectionConfig()\n\t}\n\n\tif desired.GetFailover() == nil {\n\t\tdesired.Failover = original.GetFailover()\n\t}\n\n\tif len(desired.GetHealthChecks()) == 0 {\n\t\tdesired.HealthChecks = original.GetHealthChecks()\n\t}\n\n\tif desired.GetOutlierDetection() == nil {\n\t\tdesired.OutlierDetection = original.GetOutlierDetection()\n\t}\n\n\tif desired.GetUseHttp2() == nil {\n\t\tdesired.UseHttp2 = original.GetUseHttp2()\n\t}\n\n\tif desired.GetInitialConnectionWindowSize() == nil {\n\t\tdesired.InitialConnectionWindowSize = original.GetInitialConnectionWindowSize()\n\t}\n\n\tif desired.GetInitialStreamWindowSize() == nil {\n\t\tdesired.InitialStreamWindowSize = original.GetInitialStreamWindowSize()\n\t}\n\n\tif desired.GetOverrideStreamErrorOnInvalidHttpMessage() == nil {\n\t\tdesired.OverrideStreamErrorOnInvalidHttpMessage = original.GetOverrideStreamErrorOnInvalidHttpMessage()\n\t}\n\n\tif desired.GetHttpProxyHostname() == nil {\n\t\tdesired.HttpProxyHostname = original.GetHttpProxyHostname()\n\t}\n\n\tif desiredSubsetMutator, ok := desired.GetUpstreamType().(v1.SubsetSpecMutator); ok {\n\t\tif desiredSubsetMutator.GetSubsetSpec() == nil {\n\t\t\tdesiredSubsetMutator.SetSubsetSpec(original.GetUpstreamType().(v1.SubsetSpecGetter).GetSubsetSpec())\n\t\t}\n\t}\n\n\tif desired.GetIgnoreHealthOnHostRemoval() == nil {\n\t\tdesired.IgnoreHealthOnHostRemoval = original.GetIgnoreHealthOnHostRemoval()\n\t}\n\n\tif desired.GetRespectDnsTtl() == nil {\n\t\tdesired.RespectDnsTtl = original.GetRespectDnsTtl()\n\t}\n\n\tif desired.GetDnsRefreshRate() == nil {\n\t\tdesired.DnsRefreshRate = original.GetDnsRefreshRate()\n\t}\n\n\tif desired.GetProxyProtocolVersion() == nil {\n\t\tdesired.ProxyProtocolVersion = original.GetProxyProtocolVersion()\n\t}\n}", "func NewUpdateTimezoneSettingsParamsWithHTTPClient(client *http.Client) *UpdateTimezoneSettingsParams {\n\tvar ()\n\treturn &UpdateTimezoneSettingsParams{\n\t\tHTTPClient: client,\n\t}\n}", "func (u Updates) construct() UpdatesClass { return &u }", "func (r *DeviceManagementSettingDefinitionRequest) Update(ctx context.Context, reqObj *DeviceManagementSettingDefinition) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}", "func NewUpdateDeviceProfileParams() *UpdateDeviceProfileParams {\n\tvar ()\n\treturn &UpdateDeviceProfileParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (u UpdateShortSentMessage) construct() UpdatesClass { return &u }", "func (c *Default) Update(opts ...DefaultOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyDefault(c)\n\t}\n}", "func NewUpdateSettingsAclsParamsWithTimeout(timeout time.Duration) *UpdateSettingsAclsParams {\n\tvar ()\n\treturn &UpdateSettingsAclsParams{\n\n\t\ttimeout: timeout,\n\t}\n}", "func (a *EventSettingsApiService) Update(ctx _context.Context, id string, websiteAlertConfig WebsiteAlertConfig) ([]WebsiteAlertConfigWithMetadata, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []WebsiteAlertConfigWithMetadata\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/events/settings/website-alert-configs/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(id, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &websiteAlertConfig\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tvar v []WebsiteAlertConfigWithMetadata\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (accountStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {\n}", "func (o *UpdateFolderParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func New(removeUnusedDeclarations bool, updateComments bool, bazelAnalyze BazelAnalyzer, updateFile UpdateFile) *Updater {\n\treturn &Updater{removeUnusedDeclarations, updateComments, bazelAnalyze, updateFile}\n}", "func (c *FakeApiGatewayMethodSettingses) Update(apiGatewayMethodSettings *v1alpha1.ApiGatewayMethodSettings) (result *v1alpha1.ApiGatewayMethodSettings, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewUpdateAction(apigatewaymethodsettingsesResource, c.ns, apiGatewayMethodSettings), &v1alpha1.ApiGatewayMethodSettings{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.ApiGatewayMethodSettings), err\n}", "func (a *SyncApiService) UpdateSyncSettings(ctx context.Context, syncSettings SyncSettingsExtended) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/platform/3/sync/settings\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &syncSettings\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\treturn localVarHttpResponse, err\n}", "func (a *StreamsApiService) UpdateSubscriptionSettingsExecute(r ApiUpdateSubscriptionSettingsRequest) (JsonSuccessBase, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue JsonSuccessBase\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"StreamsApiService.UpdateSubscriptionSettings\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/users/me/subscriptions/properties\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.subscriptionData == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"subscriptionData is required and must be specified\")\n\t}\n\n\t{\n\t\tt := *r.subscriptionData\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"subscription_data\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"subscription_data\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Update(c client.Client, obj runtime.Object) error {\n\tkind := obj.GetObjectKind().GroupVersionKind().Kind\n\n\t// Only allow updates on specic kinds.\n\tif kind != \"ConfigMap\" {\n\t\treturn errors.New(\"update not supported for this object kind\")\n\t}\n\n\tif err := c.Update(context.Background(), obj); err != nil {\n\t\treturn fmt.Errorf(\"failed to update %s: %v\", kind, err)\n\t}\n\treturn nil\n}", "func (r *UpdateIndexRequest) FromJsonString(s string) error {\n\tf := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(s), &f); err != nil {\n\t\treturn err\n\t}\n\tdelete(f, \"InstanceId\")\n\tdelete(f, \"IndexType\")\n\tdelete(f, \"IndexName\")\n\tdelete(f, \"UpdateMetaJson\")\n\tdelete(f, \"Username\")\n\tdelete(f, \"Password\")\n\tdelete(f, \"RolloverBackingIndex\")\n\tif len(f) > 0 {\n\t\treturn tcerr.NewTencentCloudSDKError(\"ClientError.BuildRequestError\", \"UpdateIndexRequest has unknown keys!\", \"\")\n\t}\n\treturn json.Unmarshal([]byte(s), &r)\n}", "func NewUpdateStats(\n\trootDir string,\n\tfilesToImport *[]string,\n\timportFilesCount int,\n\tupdatedFilesCount int,\n\tfailedFiles *[]string,\n) *UpdateStats {\n\n\ttotalCountOfFiles := len(*filesToImport)\n\tcountOfFailedFiles := len(*failedFiles)\n\n\treturn &UpdateStats{\n\t\tImportStats: ImportStats{\n\t\t\tRootDirectory: rootDir,\n\t\t\tScannedFilesCount: totalCountOfFiles,\n\t\t\tImportedFilesCount: importFilesCount,\n\t\t\tFailedFilesCount: countOfFailedFiles,\n\t\t\tFailedFiles: *failedFiles,\n\t\t},\n\t\tUpdatedFilesCount: updatedFilesCount,\n\t}\n}", "func NewSearchAlterationOptions()(*SearchAlterationOptions) {\n m := &SearchAlterationOptions{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func (m *TenantManager) Update(t *Tenant, opts ...RequestOption) (err error) {\n\treturn m.Request(\"PATCH\", m.URI(\"tenants\", \"settings\"), t, opts...)\n}", "func BuildUpdatePayload(projectUpdateBody string, projectUpdateProjectID string, projectUpdateAuth string) (*project.UpdatePayload, error) {\n\tvar err error\n\tvar body UpdateRequestBody\n\t{\n\t\terr = json.Unmarshal([]byte(projectUpdateBody), &body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid JSON for body, \\nerror: %s, \\nexample of valid JSON:\\n%s\", err, \"'{\\n \\\"description\\\": \\\"Voluptatem adipisci dicta recusandae dolores assumenda.\\\",\\n \\\"endTime\\\": \\\"Consequuntur totam impedit nobis inventore nesciunt.\\\",\\n \\\"goal\\\": \\\"Qui doloremque nemo similique fuga voluptatem.\\\",\\n \\\"location\\\": \\\"Non quae voluptatem.\\\",\\n \\\"name\\\": \\\"Corporis enim harum.\\\",\\n \\\"privacy\\\": 2011573778,\\n \\\"startTime\\\": \\\"Optio qui architecto perspiciatis nulla inventore ut.\\\",\\n \\\"tags\\\": \\\"Eius aut.\\\"\\n }'\")\n\t\t}\n\t}\n\tvar projectID int32\n\t{\n\t\tvar v int64\n\t\tv, err = strconv.ParseInt(projectUpdateProjectID, 10, 32)\n\t\tprojectID = int32(v)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid value for projectID, must be INT32\")\n\t\t}\n\t}\n\tvar auth string\n\t{\n\t\tauth = projectUpdateAuth\n\t}\n\tv := &project.AddProjectFields{\n\t\tName: body.Name,\n\t\tDescription: body.Description,\n\t\tGoal: body.Goal,\n\t\tLocation: body.Location,\n\t\tTags: body.Tags,\n\t\tPrivacy: body.Privacy,\n\t\tStartTime: body.StartTime,\n\t\tEndTime: body.EndTime,\n\t}\n\tres := &project.UpdatePayload{\n\t\tProject: v,\n\t}\n\tres.ProjectID = projectID\n\tres.Auth = auth\n\n\treturn res, nil\n}", "func newUpdateAttestorUpdateAttestorRequest(ctx context.Context, f *Attestor, c *Client) (map[string]interface{}, error) {\n\treq := map[string]interface{}{}\n\n\treturn req, nil\n}", "func newUpdateServiceUpdateServiceRequest(ctx context.Context, f *Service, c *Client) (map[string]interface{}, error) {\n\treq := map[string]interface{}{}\n\tres := f\n\t_ = res\n\n\tif v := f.DisplayName; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"displayName\"] = v\n\t}\n\tif v, err := expandServiceCustom(c, f.Custom, res); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Custom into custom: %w\", err)\n\t} else if v != nil {\n\t\treq[\"custom\"] = v\n\t}\n\tif v, err := expandServiceTelemetry(c, f.Telemetry, res); err != nil {\n\t\treturn nil, fmt.Errorf(\"error expanding Telemetry into telemetry: %w\", err)\n\t} else if !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"telemetry\"] = v\n\t}\n\tif v := f.UserLabels; !dcl.IsEmptyValueIndirect(v) {\n\t\treq[\"userLabels\"] = v\n\t}\n\treturn req, nil\n}", "func (t *CCHandler) ObjectUpdated(obj interface{}) {\n\tlog.Info(\"CCHandler.ObjectUpdated\")\n\n\tcc, ok1 := obj.(*v1.CustomConfig)\n\tlog.Info(\"ok is\", ok1)\n\n\tlog.Info(\"cc is \", cc.Spec.Key, cc.Spec.Value, cc.Spec.ConfigmapName)\n\n\tns := os.Getenv(\"NAMESPACE\")\n\tlog.Info(\"ns is\", ns)\n\tif ns == \"\" {\n\t\tns = \"default\"\n\t}\n\n\tcm, err := t.Client.CoreV1().ConfigMaps(ns).Get(cc.Spec.ConfigmapName, meta_v1.GetOptions{})\n\tif err != nil {\n\t\tlog.Error(\"error is\", err)\n\t\treturn\n\t}\n\n\tcm.Data[cc.Spec.Key] = cc.Spec.Value\n\t_, err = t.Client.CoreV1().ConfigMaps(ns).Update(cm)\n\n\tif err != nil {\n\t\tlog.Error(\"error is\", err)\n\t\treturn\n\t}\n}", "func (client *DefenderSettingsClient) createOrUpdateCreateRequest(ctx context.Context, defenderSettingsModel DefenderSettingsModel, options *DefenderSettingsClientCreateOrUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/defenderSettings/default\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, defenderSettingsModel)\n}", "func NewUpdateAliasParams() *UpdateAliasParams {\n\tvar ()\n\treturn &UpdateAliasParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (client *WebAppsClient) updateAuthSettingsV2CreateRequest(ctx context.Context, resourceGroupName string, name string, siteAuthSettingsV2 SiteAuthSettingsV2, options *WebAppsUpdateAuthSettingsV2Options) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/authsettingsV2\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, siteAuthSettingsV2)\n}", "func (x *Rest) ConfigurationUpdate(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer panicCatcher(w)\n\n\trequest := msg.New(r, params)\n\trequest.Section = msg.SectionConfiguration\n\trequest.Action = msg.ActionUpdate\n\n\tswitch request.Version {\n\tcase msg.ProtocolOne:\n\t\tcReq := &v1.ConfigurationItem{}\n\t\tif err := decodeJSONBody(r, cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = v2.ConfigurationFromV1(cReq)\n\n\tcase msg.ProtocolTwo:\n\t\tcReq := v2.NewConfigurationRequest()\n\t\tif err := decodeJSONBody(r, &cReq); err != nil {\n\t\t\tx.replyUnprocessableEntity(&w, &request, err)\n\t\t\treturn\n\t\t}\n\t\trequest.Configuration = *cReq.Configuration\n\n\t\t// only the v2 API has request flags\n\t\tif err := resolveFlags(&cReq, &request); err != nil {\n\t\t\tx.replyBadRequest(&w, &request, err)\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tx.replyInternalError(&w, &request, nil)\n\t\treturn\n\t}\n\n\trequest.Configuration.InputSanatize()\n\trequest.LookupHash = calculateLookupID(\n\t\trequest.Configuration.HostID,\n\t\trequest.Configuration.Metric,\n\t)\n\trequest.Configuration.LookupID = request.LookupHash\n\n\tif request.Configuration.ID != strings.ToLower(params.ByName(`ID`)) {\n\t\tx.replyBadRequest(&w, &request, fmt.Errorf(\n\t\t\t\"Mismatched IDs in update: [%s] vs [%s]\",\n\t\t\trequest.Configuration.ID,\n\t\t\tstrings.ToLower(params.ByName(`ID`)),\n\t\t))\n\t}\n\n\tif _, err := uuid.FromString(request.Configuration.ID); err != nil {\n\t\tx.replyBadRequest(&w, &request, err)\n\t\treturn\n\t}\n\n\tx.somaSetFeedbackURL(&request)\n\n\tif !x.isAuthorized(&request) {\n\t\tx.replyForbidden(&w, &request, nil)\n\t\treturn\n\t}\n\n\thandler := x.handlerMap.Get(`configuration_w`)\n\thandler.Intake() <- request\n\tresult := <-request.Reply\n\tx.respond(&w, &result)\n}", "func NewModifyAppGeneralSettingByIdRequestWithoutParam() *ModifyAppGeneralSettingByIdRequest {\n\n return &ModifyAppGeneralSettingByIdRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/smsAppGeneralSettings/{id}:modify\",\n Method: \"GET\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}" ]
[ "0.6326984", "0.5555253", "0.54686856", "0.54638505", "0.5456541", "0.53774154", "0.5316063", "0.5289187", "0.5279723", "0.52544224", "0.5238205", "0.5192056", "0.5162522", "0.5158689", "0.5124117", "0.5112922", "0.5106321", "0.5096599", "0.508947", "0.5078126", "0.5062241", "0.50383544", "0.50353825", "0.50240785", "0.50132006", "0.5010197", "0.50012034", "0.49947298", "0.4992126", "0.49854198", "0.49771512", "0.49733564", "0.49396956", "0.49344286", "0.49076515", "0.4895972", "0.48907086", "0.48907086", "0.48826712", "0.48800895", "0.48777798", "0.48688114", "0.48597708", "0.4848899", "0.4848899", "0.48462844", "0.48452258", "0.48226655", "0.4818894", "0.48076203", "0.48060706", "0.48043907", "0.48004606", "0.4789093", "0.4785032", "0.47838295", "0.47797674", "0.47758052", "0.47598597", "0.47554266", "0.4754456", "0.4745012", "0.474371", "0.47400984", "0.47370142", "0.47342193", "0.47310323", "0.47213864", "0.47209135", "0.47161967", "0.4714566", "0.4693483", "0.4687854", "0.46751013", "0.46603432", "0.46535325", "0.46521068", "0.4651977", "0.46486688", "0.46414277", "0.4639328", "0.46366975", "0.4634896", "0.46311313", "0.46205738", "0.4617461", "0.46135652", "0.46108016", "0.46070248", "0.4604868", "0.46025556", "0.45983467", "0.45961192", "0.45876998", "0.45870242", "0.45842153", "0.45829347", "0.45764154", "0.45695147", "0.45668888" ]
0.71646416
0
NewSettingsObjectUpdateWithDefaults instantiates a new SettingsObjectUpdate object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set
func NewSettingsObjectUpdateWithDefaults() *SettingsObjectUpdate { this := SettingsObjectUpdate{} return &this }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *PutNmsUpdateParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func NewSettingsObjectUpdate(value map[string]interface{}) *SettingsObjectUpdate {\n\tthis := SettingsObjectUpdate{}\n\tthis.Value = value\n\treturn &this\n}", "func (o *UpdateFolderParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (suo *SettingUpdateOne) defaults() {\n\tif _, ok := suo.mutation.UpdatedAt(); !ok {\n\t\tv := setting.UpdateDefaultUpdatedAt()\n\t\tsuo.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := suo.mutation.DeletedAt(); !ok {\n\t\tv := setting.UpdateDefaultDeletedAt()\n\t\tsuo.mutation.SetDeletedAt(v)\n\t}\n}", "func (su *SettingUpdate) defaults() {\n\tif _, ok := su.mutation.UpdatedAt(); !ok {\n\t\tv := setting.UpdateDefaultUpdatedAt()\n\t\tsu.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := su.mutation.DeletedAt(); !ok {\n\t\tv := setting.UpdateDefaultDeletedAt()\n\t\tsu.mutation.SetDeletedAt(v)\n\t}\n}", "func (o *UpdateFlowParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (uuo *UserUpdateOne) defaults() error {\n\tif _, ok := uuo.mutation.UpdateTime(); !ok && !uuo.mutation.UpdateTimeCleared() {\n\t\tif user.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized user.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := user.UpdateDefaultUpdateTime()\n\t\tuuo.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func NewUpdateProjectSettingsDefault(code int) *UpdateProjectSettingsDefault {\n\treturn &UpdateProjectSettingsDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (oumuo *OrgUnitMemberUpdateOne) defaults() error {\n\tif _, ok := oumuo.mutation.UpdateTime(); !ok && !oumuo.mutation.UpdateTimeCleared() {\n\t\tif orgunitmember.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized orgunitmember.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := orgunitmember.UpdateDefaultUpdateTime()\n\t\toumuo.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (ouo *OrganizationUpdateOne) defaults() error {\n\tif _, ok := ouo.mutation.UpdateTime(); !ok && !ouo.mutation.UpdateTimeCleared() {\n\t\tif organization.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized organization.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := organization.UpdateDefaultUpdateTime()\n\t\touo.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (oumu *OrgUnitMemberUpdate) defaults() error {\n\tif _, ok := oumu.mutation.UpdateTime(); !ok && !oumu.mutation.UpdateTimeCleared() {\n\t\tif orgunitmember.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized orgunitmember.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := orgunitmember.UpdateDefaultUpdateTime()\n\t\toumu.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) defaults() error {\n\tif _, ok := uu.mutation.UpdateTime(); !ok && !uu.mutation.UpdateTimeCleared() {\n\t\tif user.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized user.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := user.UpdateDefaultUpdateTime()\n\t\tuu.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func assignDefaultAddonVals(addon, defaults KubernetesAddon, isUpdate bool) KubernetesAddon {\n\tif addon.Enabled == nil {\n\t\taddon.Enabled = defaults.Enabled\n\t}\n\tfor i := range defaults.Containers {\n\t\tc := addon.GetAddonContainersIndexByName(defaults.Containers[i].Name)\n\t\tif c < 0 {\n\t\t\taddon.Containers = append(addon.Containers, defaults.Containers[i])\n\t\t} else {\n\t\t\tif addon.Containers[c].Image == \"\" || isUpdate {\n\t\t\t\taddon.Containers[c].Image = defaults.Containers[i].Image\n\t\t\t}\n\t\t\tif addon.Containers[c].CPURequests == \"\" {\n\t\t\t\taddon.Containers[c].CPURequests = defaults.Containers[i].CPURequests\n\t\t\t}\n\t\t\tif addon.Containers[c].MemoryRequests == \"\" {\n\t\t\t\taddon.Containers[c].MemoryRequests = defaults.Containers[i].MemoryRequests\n\t\t\t}\n\t\t\tif addon.Containers[c].CPULimits == \"\" {\n\t\t\t\taddon.Containers[c].CPULimits = defaults.Containers[i].CPULimits\n\t\t\t}\n\t\t\tif addon.Containers[c].MemoryLimits == \"\" {\n\t\t\t\taddon.Containers[c].MemoryLimits = defaults.Containers[i].MemoryLimits\n\t\t\t}\n\t\t}\n\t}\n\tfor key, val := range defaults.Config {\n\t\tif addon.Config == nil {\n\t\t\taddon.Config = make(map[string]string)\n\t\t}\n\t\tif v, ok := addon.Config[key]; !ok || v == \"\" {\n\t\t\taddon.Config[key] = val\n\t\t}\n\t}\n\treturn addon\n}", "func (puo *PostUpdateOne) defaults() error {\n\tif _, ok := puo.mutation.UpdateTime(); !ok {\n\t\tif post.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized post.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := post.UpdateDefaultUpdateTime()\n\t\tpuo.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (wuo *WechatUpdateOne) defaults() {\n\tif _, ok := wuo.mutation.UpdateTime(); !ok {\n\t\tv := wechat.UpdateDefaultUpdateTime()\n\t\twuo.mutation.SetUpdateTime(v)\n\t}\n}", "func (ocuo *OAuthConnectionUpdateOne) defaults() error {\n\tif _, ok := ocuo.mutation.UpdatedAt(); !ok {\n\t\tif oauthconnection.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized oauthconnection.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := oauthconnection.UpdateDefaultUpdatedAt()\n\t\tocuo.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (ocu *OAuthConnectionUpdate) defaults() error {\n\tif _, ok := ocu.mutation.UpdatedAt(); !ok {\n\t\tif oauthconnection.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized oauthconnection.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := oauthconnection.UpdateDefaultUpdatedAt()\n\t\tocu.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (ou *OrganizationUpdate) defaults() error {\n\tif _, ok := ou.mutation.UpdateTime(); !ok && !ou.mutation.UpdateTimeCleared() {\n\t\tif organization.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized organization.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := organization.UpdateDefaultUpdateTime()\n\t\tou.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (o *Entry) Defaults() {\n if o.Type == \"\" {\n o.Type = \"ipv4\"\n }\n\n if o.ToInterface == \"\" {\n o.ToInterface = \"any\"\n }\n\n if o.Service == \"\" {\n o.Service = \"any\"\n }\n\n if len(o.SourceAddresses) == 0 {\n o.SourceAddresses = []string{\"any\"}\n }\n\n if len(o.DestinationAddresses) == 0 {\n o.DestinationAddresses = []string{\"any\"}\n }\n\n if o.SatType == \"\" {\n o.SatType = None\n }\n\n if o.DatType == \"\" {\n o.DatType = DatTypeStatic\n }\n}", "func (kcuo *K8sContainerUpdateOne) defaults() {\n\tif _, ok := kcuo.mutation.UpdatedAt(); !ok {\n\t\tv := k8scontainer.UpdateDefaultUpdatedAt()\n\t\tkcuo.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := kcuo.mutation.DeletedAt(); !ok {\n\t\tv := k8scontainer.UpdateDefaultDeletedAt()\n\t\tkcuo.mutation.SetDeletedAt(v)\n\t}\n}", "func (stcuo *SurveyTemplateCategoryUpdateOne) defaults() {\n\tif _, ok := stcuo.mutation.UpdateTime(); !ok {\n\t\tv := surveytemplatecategory.UpdateDefaultUpdateTime()\n\t\tstcuo.mutation.SetUpdateTime(v)\n\t}\n}", "func (uuo *UserUpdateOne) defaults() {\n\tif _, ok := uuo.mutation.UpdateTime(); !ok {\n\t\tv := user.UpdateDefaultUpdateTime()\n\t\tuuo.mutation.SetUpdateTime(v)\n\t}\n}", "func (gsu *GameServerUpdate) defaults() error {\n\tif _, ok := gsu.mutation.UpdatedAt(); !ok {\n\t\tif gameserver.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized gameserver.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := gameserver.UpdateDefaultUpdatedAt()\n\t\tgsu.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (oupu *OrgUnitPositionUpdate) defaults() error {\n\tif _, ok := oupu.mutation.UpdateTime(); !ok && !oupu.mutation.UpdateTimeCleared() {\n\t\tif orgunitposition.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized orgunitposition.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := orgunitposition.UpdateDefaultUpdateTime()\n\t\toupu.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (oupuo *OrgUnitPositionUpdateOne) defaults() error {\n\tif _, ok := oupuo.mutation.UpdateTime(); !ok && !oupuo.mutation.UpdateTimeCleared() {\n\t\tif orgunitposition.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized orgunitposition.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := orgunitposition.UpdateDefaultUpdateTime()\n\t\toupuo.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (mnuo *MetricNameUpdateOne) defaults() {\n\tif _, ok := mnuo.mutation.UpdatedAt(); !ok {\n\t\tv := metricname.UpdateDefaultUpdatedAt()\n\t\tmnuo.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := mnuo.mutation.DeletedAt(); !ok {\n\t\tv := metricname.UpdateDefaultDeletedAt()\n\t\tmnuo.mutation.SetDeletedAt(v)\n\t}\n}", "func (wu *WechatUpdate) defaults() {\n\tif _, ok := wu.mutation.UpdateTime(); !ok {\n\t\tv := wechat.UpdateDefaultUpdateTime()\n\t\twu.mutation.SetUpdateTime(v)\n\t}\n}", "func (gsuo *GameServerUpdateOne) defaults() error {\n\tif _, ok := gsuo.mutation.UpdatedAt(); !ok {\n\t\tif gameserver.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized gameserver.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := gameserver.UpdateDefaultUpdatedAt()\n\t\tgsuo.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (suo *StateUpdateOne) defaults() error {\n\tif _, ok := suo.mutation.UpdatedAt(); !ok {\n\t\tif state.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized state.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := state.UpdateDefaultUpdatedAt()\n\t\tsuo.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (kcu *K8sContainerUpdate) defaults() {\n\tif _, ok := kcu.mutation.UpdatedAt(); !ok {\n\t\tv := k8scontainer.UpdateDefaultUpdatedAt()\n\t\tkcu.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := kcu.mutation.DeletedAt(); !ok {\n\t\tv := k8scontainer.UpdateDefaultDeletedAt()\n\t\tkcu.mutation.SetDeletedAt(v)\n\t}\n}", "func (o *UpdateFolderParams) WithDefaults() *UpdateFolderParams {\n\to.SetDefaults()\n\treturn o\n}", "func (auo *ArticleUpdateOne) defaults() {\n\tif _, ok := auo.mutation.UpdateTime(); !ok {\n\t\tv := article.UpdateDefaultUpdateTime()\n\t\tauo.mutation.SetUpdateTime(v)\n\t}\n}", "func (o *UpdateComparisonReportParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (oiu *OrderInfoUpdate) defaults() {\n\tif _, ok := oiu.mutation.UpdatedAt(); !ok && !oiu.mutation.UpdatedAtCleared() {\n\t\tv := orderinfo.UpdateDefaultUpdatedAt()\n\t\toiu.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *FreezeParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (uuo *UserUpdateOne) defaults() {\n\tif _, ok := uuo.mutation.UpdatedAt(); !ok {\n\t\tv := user.UpdateDefaultUpdatedAt()\n\t\tuuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (uuo *UserUpdateOne) defaults() {\n\tif _, ok := uuo.mutation.UpdatedAt(); !ok {\n\t\tv := user.UpdateDefaultUpdatedAt()\n\t\tuuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func saveDefaults(defaults resource.PropertyMap, object resource.PropertyMap) resource.PropertyMap {\n\tif defaults.ContainsSecrets() {\n\t\tobject[\"__defaults\"] = resource.MakeSecret(resource.NewObjectProperty(defaults))\n\t} else {\n\t\tobject[\"__defaults\"] = resource.NewObjectProperty(defaults)\n\t}\n\treturn object\n}", "func (pu *PostUpdate) defaults() error {\n\tif _, ok := pu.mutation.UpdateTime(); !ok {\n\t\tif post.UpdateDefaultUpdateTime == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized post.UpdateDefaultUpdateTime (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := post.UpdateDefaultUpdateTime()\n\t\tpu.mutation.SetUpdateTime(v)\n\t}\n\treturn nil\n}", "func (upuo *UnsavedPostUpdateOne) defaults() {\n\tif _, ok := upuo.mutation.ModifiedAt(); !ok {\n\t\tv := unsavedpost.UpdateDefaultModifiedAt()\n\t\tupuo.mutation.SetModifiedAt(v)\n\t}\n}", "func (o *ConfigurationBackupModifyParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (puo *PhoneUpdateOne) defaults() {\n\tif _, ok := puo.mutation.ModifiedAt(); !ok {\n\t\tv := phone.UpdateDefaultModifiedAt()\n\t\tpuo.mutation.SetModifiedAt(v)\n\t}\n}", "func (uu *UserUpdate) defaults() {\n\tif _, ok := uu.mutation.UpdateTime(); !ok {\n\t\tv := user.UpdateDefaultUpdateTime()\n\t\tuu.mutation.SetUpdateTime(v)\n\t}\n}", "func NewPasswordUpdateWithDefaults() *PasswordUpdate {\n\tthis := PasswordUpdate{}\n\treturn &this\n}", "func (mnu *MetricNameUpdate) defaults() {\n\tif _, ok := mnu.mutation.UpdatedAt(); !ok {\n\t\tv := metricname.UpdateDefaultUpdatedAt()\n\t\tmnu.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := mnu.mutation.DeletedAt(); !ok {\n\t\tv := metricname.UpdateDefaultDeletedAt()\n\t\tmnu.mutation.SetDeletedAt(v)\n\t}\n}", "func NewGridViewUpdateWithDefaults() *GridViewUpdate {\n\tthis := GridViewUpdate{}\n\treturn &this\n}", "func (oiuo *OrderInfoUpdateOne) defaults() {\n\tif _, ok := oiuo.mutation.UpdatedAt(); !ok && !oiuo.mutation.UpdatedAtCleared() {\n\t\tv := orderinfo.UpdateDefaultUpdatedAt()\n\t\toiuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func setDefaults(configs MutatingWebhookConfigs) MutatingWebhookConfigs {\n\tif configs.Addr == nil {\n\t\tconfigs.Addr = &addr\n\t}\n\n\tif configs.ReadTimeout == nil {\n\t\tconfigs.ReadTimeout = &readTimeout\n\t}\n\n\tif configs.WriteTimeout == nil {\n\t\tconfigs.WriteTimeout = &writeTimeout\n\t}\n\n\tif configs.MaxHeaderBytes == nil {\n\t\tconfigs.MaxHeaderBytes = &maxHeaderBytes\n\t}\n\n\tif configs.CertFilePath == nil {\n\t\tconfigs.CertFilePath = &certFilePath\n\t}\n\n\tif configs.KeyFilePath == nil {\n\t\tconfigs.KeyFilePath = &keyFilePath\n\t}\n\n\treturn configs\n}", "func (o *UpdateMTOServiceItemStatusParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (cuo *CustomerUpdateOne) defaults() {\n\tif _, ok := cuo.mutation.UpdatedAt(); !ok {\n\t\tv := customer.UpdateDefaultUpdatedAt()\n\t\tcuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *Entry) Defaults() {\n\tif o.StaticDist == 0 {\n\t\to.StaticDist = 10\n\t}\n\n\tif o.StaticIpv6Dist == 0 {\n\t\to.StaticIpv6Dist = 10\n\t}\n\n\tif o.OspfIntDist == 0 {\n\t\to.OspfIntDist = 30\n\t}\n\n\tif o.OspfExtDist == 0 {\n\t\to.OspfExtDist = 110\n\t}\n\n\tif o.Ospfv3IntDist == 0 {\n\t\to.Ospfv3IntDist = 30\n\t}\n\n\tif o.Ospfv3ExtDist == 0 {\n\t\to.Ospfv3ExtDist = 110\n\t}\n\n\tif o.IbgpDist == 0 {\n\t\to.IbgpDist = 200\n\t}\n\n\tif o.EbgpDist == 0 {\n\t\to.EbgpDist = 20\n\t}\n\n\tif o.RipDist == 0 {\n\t\to.RipDist = 120\n\t}\n}", "func (su *StateUpdate) defaults() error {\n\tif _, ok := su.mutation.UpdatedAt(); !ok {\n\t\tif state.UpdateDefaultUpdatedAt == nil {\n\t\t\treturn fmt.Errorf(\"ent: uninitialized state.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)\")\n\t\t}\n\t\tv := state.UpdateDefaultUpdatedAt()\n\t\tsu.mutation.SetUpdatedAt(v)\n\t}\n\treturn nil\n}", "func (o *V2UpdateClusterManifestParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (au *ArticleUpdate) defaults() {\n\tif _, ok := au.mutation.UpdateTime(); !ok {\n\t\tv := article.UpdateDefaultUpdateTime()\n\t\tau.mutation.SetUpdateTime(v)\n\t}\n}", "func (upu *UnsavedPostUpdate) defaults() {\n\tif _, ok := upu.mutation.ModifiedAt(); !ok {\n\t\tv := unsavedpost.UpdateDefaultModifiedAt()\n\t\tupu.mutation.SetModifiedAt(v)\n\t}\n}", "func (duo *DatumUpdateOne) defaults() {\n\tif _, ok := duo.mutation.UpdatedAt(); !ok {\n\t\tv := datum.UpdateDefaultUpdatedAt()\n\t\tduo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *FetchIntegrationFormParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (stcu *SurveyTemplateCategoryUpdate) defaults() {\n\tif _, ok := stcu.mutation.UpdateTime(); !ok {\n\t\tv := surveytemplatecategory.UpdateDefaultUpdateTime()\n\t\tstcu.mutation.SetUpdateTime(v)\n\t}\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func NewNodeUpdateWithDefaults() *NodeUpdate {\n\tthis := NodeUpdate{}\n\treturn &this\n}", "func (nuo *NodeUpdateOne) defaults() {\n\tif _, ok := nuo.mutation.UpdatedAt(); !ok {\n\t\tv := node.UpdateDefaultUpdatedAt()\n\t\tnuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (uu *UserUpdate) defaults() {\n\tif _, ok := uu.mutation.UpdatedAt(); !ok {\n\t\tv := user.UpdateDefaultUpdatedAt()\n\t\tuu.mutation.SetUpdatedAt(v)\n\t}\n}", "func (uu *UserUpdate) defaults() {\n\tif _, ok := uu.mutation.UpdatedAt(); !ok {\n\t\tv := user.UpdateDefaultUpdatedAt()\n\t\tuu.mutation.SetUpdatedAt(v)\n\t}\n}", "func SetDefaults(doc *Doc) {\n\tdefaults.SetDefaults(doc) //changes only if empty\n}", "func (o *GetBundleByKeyParams) SetDefaults() {\n\tvar (\n\t\tauditDefault = string(\"NONE\")\n\n\t\tincludedDeletedDefault = bool(false)\n\t)\n\n\tval := GetBundleByKeyParams{\n\t\tAudit: &auditDefault,\n\t\tIncludedDeleted: &includedDeletedDefault,\n\t}\n\n\tval.timeout = o.timeout\n\tval.Context = o.Context\n\tval.HTTPClient = o.HTTPClient\n\t*o = val\n}", "func (o *CreateInstantPaymentParams) SetDefaults() {\n\tvar (\n\t\texternalPaymentDefault = bool(false)\n\t)\n\n\tval := CreateInstantPaymentParams{\n\t\tExternalPayment: &externalPaymentDefault,\n\t}\n\n\tval.timeout = o.timeout\n\tval.Context = o.Context\n\tval.HTTPClient = o.HTTPClient\n\t*o = val\n}", "func (o *EditParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func NewUpdatesV3RequestWithDefaults() *UpdatesV3Request {\n\tthis := UpdatesV3Request{}\n\tvar thirdParty bool = false\n\tthis.ThirdParty = &thirdParty\n\tvar optimisticUpdates bool = false\n\tthis.OptimisticUpdates = &optimisticUpdates\n\treturn &this\n}", "func (o *UpdateFlowParams) WithDefaults() *UpdateFlowParams {\n\to.SetDefaults()\n\treturn o\n}", "func (du *DatumUpdate) defaults() {\n\tif _, ok := du.mutation.UpdatedAt(); !ok {\n\t\tv := datum.UpdateDefaultUpdatedAt()\n\t\tdu.mutation.SetUpdatedAt(v)\n\t}\n}", "func (s *Settings) SetDefaults(d *Settings) {\n\tif s.DailyGoal == 0 {\n\t\ts.DailyGoal = d.DailyGoal\n\t}\n\n\tif s.DefaultBreakDuration == 0 {\n\t\ts.DefaultBreakDuration = d.DefaultBreakDuration\n\t}\n\n\tif s.DefaultPomodoroDuration == 0 {\n\t\ts.DefaultPomodoroDuration = d.DefaultPomodoroDuration\n\t}\n\n\tif len(s.DefaultTags) == 0 {\n\t\ts.DefaultTags = d.DefaultTags\n\t}\n}", "func (o *PostAlertsParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (o *PutNmsUpdateParams) WithDefaults() *PutNmsUpdateParams {\n\to.SetDefaults()\n\treturn o\n}", "func (o *CreateGitWebhookUsingPOSTParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (vuuo *VacUserUpdateOne) defaults() {\n\tif _, ok := vuuo.mutation.UpdatedAt(); !ok {\n\t\tv := vacuser.UpdateDefaultUpdatedAt()\n\t\tvuuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (pu *PhoneUpdate) defaults() {\n\tif _, ok := pu.mutation.ModifiedAt(); !ok {\n\t\tv := phone.UpdateDefaultModifiedAt()\n\t\tpu.mutation.SetModifiedAt(v)\n\t}\n}", "func (biuo *BlockInstanceUpdateOne) defaults() {\n\tif _, ok := biuo.mutation.UpdateTime(); !ok {\n\t\tv := blockinstance.UpdateDefaultUpdateTime()\n\t\tbiuo.mutation.SetUpdateTime(v)\n\t}\n}", "func ApplyDefaults(obj interface{}, s *spec.Schema) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tres := false\n\n\t// Support utils.Values\n\tswitch vals := obj.(type) {\n\tcase utils.Values:\n\t\tobj = map[string]interface{}(vals)\n\tcase *utils.Values:\n\t\t// rare case\n\t\tobj = map[string]interface{}(*vals)\n\t}\n\n\tswitch obj := obj.(type) {\n\tcase map[string]interface{}:\n\t\t// Apply defaults to properties\n\t\tfor k, prop := range s.Properties {\n\t\t\tif prop.Default == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, found := obj[k]; !found {\n\t\t\t\tobj[k] = runtime.DeepCopyJSONValue(prop.Default)\n\t\t\t\tres = true\n\t\t\t}\n\t\t}\n\t\t// Apply to deeper levels.\n\t\tfor k, v := range obj {\n\t\t\tif prop, found := s.Properties[k]; found {\n\t\t\t\tdeepRes := ApplyDefaults(v, &prop)\n\t\t\t\tres = res || deepRes\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\t// Only List validation is supported.\n\t\t// See https://json-schema.org/understanding-json-schema/reference/array.html#list-validation\n\t\tfor _, v := range obj {\n\t\t\tdeepRes := ApplyDefaults(v, s.Items.Schema)\n\t\t\tres = res || deepRes\n\t\t}\n\tdefault:\n\t\t// scalars, no action\n\t}\n\n\treturn res\n}", "func (rfuo *ReportFilterUpdateOne) defaults() {\n\tif _, ok := rfuo.mutation.UpdateTime(); !ok {\n\t\tv := reportfilter.UpdateDefaultUpdateTime()\n\t\trfuo.mutation.SetUpdateTime(v)\n\t}\n}", "func (nu *NodeUpdate) defaults() {\n\tif _, ok := nu.mutation.UpdatedAt(); !ok {\n\t\tv := node.UpdateDefaultUpdatedAt()\n\t\tnu.mutation.SetUpdatedAt(v)\n\t}\n}", "func (biu *BlockInstanceUpdate) defaults() {\n\tif _, ok := biu.mutation.UpdateTime(); !ok {\n\t\tv := blockinstance.UpdateDefaultUpdateTime()\n\t\tbiu.mutation.SetUpdateTime(v)\n\t}\n}", "func (duo *DealUpdateOne) defaults() {\n\tif _, ok := duo.mutation.Mtime(); !ok {\n\t\tv := deal.UpdateDefaultMtime()\n\t\tduo.mutation.SetMtime(v)\n\t}\n}", "func (rfu *ReportFilterUpdate) defaults() {\n\tif _, ok := rfu.mutation.UpdateTime(); !ok {\n\t\tv := reportfilter.UpdateDefaultUpdateTime()\n\t\trfu.mutation.SetUpdateTime(v)\n\t}\n}", "func (piuo *ProviderIDUpdateOne) defaults() {\n\tif _, ok := piuo.mutation.UpdatedAt(); !ok {\n\t\tv := providerid.UpdateDefaultUpdatedAt()\n\t\tpiuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *GetPropertyDescriptorParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (fpsc *FloorPlanScaleCreate) defaults() {\n\tif _, ok := fpsc.mutation.CreateTime(); !ok {\n\t\tv := floorplanscale.DefaultCreateTime()\n\t\tfpsc.mutation.SetCreateTime(v)\n\t}\n\tif _, ok := fpsc.mutation.UpdateTime(); !ok {\n\t\tv := floorplanscale.DefaultUpdateTime()\n\t\tfpsc.mutation.SetUpdateTime(v)\n\t}\n}", "func (o *UpdateZoneProjectsUsingPUTParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (o ClientOptions) ApplyDefaults(ctx context.Context, defaultDesc string) ClientOptions {\n\tif o.Hostname == \"\" {\n\t\to.Hostname = GetDefaultHostName(ctx)\n\t}\n\n\tif o.Username == \"\" {\n\t\to.Username = GetDefaultUserName(ctx)\n\t}\n\n\tif o.Description == \"\" {\n\t\to.Description = defaultDesc\n\t}\n\n\tif o.FormatBlobCacheDuration == 0 {\n\t\to.FormatBlobCacheDuration = format.DefaultRepositoryBlobCacheDuration\n\t}\n\n\treturn o\n}", "func (cu *CustomerUpdate) defaults() {\n\tif _, ok := cu.mutation.UpdatedAt(); !ok {\n\t\tv := customer.UpdateDefaultUpdatedAt()\n\t\tcu.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *QueryChangesParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func NewDefaultUpdateChecker() (checker Checker) {\n\tpoliceDataCollector := NewHttpDataCollector(dateCheckEndpoint)\n\tlastUpdated := NewDefaultS3DataCollector()\n\tchecker = &UpdateChecker{\n\t\tpoliceDateCollector: policeDataCollector,\n\t\tlastUpdatedDateCollector: lastUpdated,\n\t}\n\treturn\n}", "func (o *DeleteVersionControlRequestParams) SetDefaults() {\n\tvar (\n\t\tdisconnectedNodeAcknowledgedDefault = bool(false)\n\t)\n\n\tval := DeleteVersionControlRequestParams{\n\t\tDisconnectedNodeAcknowledged: &disconnectedNodeAcknowledgedDefault,\n\t}\n\n\tval.timeout = o.timeout\n\tval.Context = o.Context\n\tval.HTTPClient = o.HTTPClient\n\t*o = val\n}", "func (o *FileInfoCreateParams) SetDefaults() {\n\tvar (\n\t\treturnRecordsDefault = bool(false)\n\t)\n\n\tval := FileInfoCreateParams{\n\t\tReturnRecords: &returnRecordsDefault,\n\t}\n\n\tval.timeout = o.timeout\n\tval.Context = o.Context\n\tval.HTTPClient = o.HTTPClient\n\t*o = val\n}", "func (rc *ResourceCreate) defaults() {\n\tif _, ok := rc.mutation.UpdatedAt(); !ok {\n\t\tv := resource.DefaultUpdatedAt()\n\t\trc.mutation.SetUpdatedAt(v)\n\t}\n}", "func (csuo *CardScheduleUpdateOne) defaults() {\n\tif _, ok := csuo.mutation.UpdateTime(); !ok {\n\t\tv := cardschedule.UpdateDefaultUpdateTime()\n\t\tcsuo.mutation.SetUpdateTime(v)\n\t}\n}", "func updateOptionalKubeDefaults(desired []entry) {\n\tdefaults := map[string]interface{}{\n\t\t\"disable_local_ca_jwt\": false,\n\t\t\"kubernetes_ca_cert\": \"\",\n\t}\n\tfor _, auth := range desired {\n\t\tif strings.ToLower(auth.Type) == \"kubernetes\" {\n\t\t\tfor _, cfg := range auth.Settings {\n\t\t\t\tfor k, v := range defaults {\n\t\t\t\t\t// denotes that attr was not included in definition and graphql assigned nil\n\t\t\t\t\t// proceed with assigning default value that api would assign if attribute was omitted\n\t\t\t\t\tif cfg[k] == nil {\n\t\t\t\t\t\tcfg[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (csu *CardScheduleUpdate) defaults() {\n\tif _, ok := csu.mutation.UpdateTime(); !ok {\n\t\tv := cardschedule.UpdateDefaultUpdateTime()\n\t\tcsu.mutation.SetUpdateTime(v)\n\t}\n}", "func (ktuo *KqiTargetUpdateOne) defaults() {\n\tif _, ok := ktuo.mutation.UpdateTime(); !ok {\n\t\tv := kqitarget.UpdateDefaultUpdateTime()\n\t\tktuo.mutation.SetUpdateTime(v)\n\t}\n}", "func (o *SetUniverseBackupFlagParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (du *DealUpdate) defaults() {\n\tif _, ok := du.mutation.Mtime(); !ok {\n\t\tv := deal.UpdateDefaultMtime()\n\t\tdu.mutation.SetMtime(v)\n\t}\n}" ]
[ "0.62908655", "0.6283833", "0.62664723", "0.62579656", "0.62496364", "0.60108656", "0.59566194", "0.5885696", "0.58122045", "0.58115685", "0.5792474", "0.5787971", "0.5761175", "0.5750238", "0.57485837", "0.57468826", "0.57381827", "0.56904393", "0.56875664", "0.5686873", "0.56634367", "0.5645026", "0.562854", "0.56278414", "0.5627566", "0.5627289", "0.5618848", "0.56174344", "0.56126505", "0.5598796", "0.5578648", "0.55753756", "0.5569256", "0.5554719", "0.5528244", "0.55272985", "0.55272985", "0.5517892", "0.5513918", "0.5506184", "0.5505546", "0.5494627", "0.5492677", "0.548305", "0.5479576", "0.5479429", "0.54698926", "0.54586935", "0.545506", "0.5441769", "0.54363185", "0.5435227", "0.54315764", "0.5428602", "0.54264015", "0.5424897", "0.54229", "0.54204386", "0.54183483", "0.5413128", "0.5410248", "0.54038256", "0.54038256", "0.5401314", "0.53948337", "0.5390785", "0.5375922", "0.537543", "0.5364405", "0.5358832", "0.53457445", "0.53335613", "0.5333332", "0.5323737", "0.5321949", "0.5321394", "0.5320675", "0.53177017", "0.5313859", "0.5307788", "0.5298077", "0.5292555", "0.5290689", "0.52811617", "0.5280504", "0.52751714", "0.52711844", "0.526295", "0.52615696", "0.5248866", "0.5247908", "0.52460605", "0.52398056", "0.52353525", "0.5233241", "0.52171856", "0.52163", "0.5216179", "0.5215533", "0.5215145" ]
0.76742965
0
GetSchemaVersion returns the SchemaVersion field value if set, zero value otherwise.
func (o *SettingsObjectUpdate) GetSchemaVersion() string { if o == nil || o.SchemaVersion == nil { var ret string return ret } return *o.SchemaVersion }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AssetReportFreddieGetResponse) GetSchemaVersion() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.SchemaVersion\n}", "func (r *Document) SchemaVersion() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"schemaVersion\"])\n}", "func (o *AssetReportFreddieGetResponse) GetSchemaVersionOk() (*float32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.SchemaVersion, true\n}", "func (st *Store) schemaVersion() (int, error) {\n\tvar n string\n\terr := st.db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name='version';`).Scan(&n)\n\tif err == sql.ErrNoRows {\n\t\treturn 0, nil // assume db is blank\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar v int\n\terr = st.db.QueryRow(`SELECT MAX(ver) FROM version`).Scan(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn v, nil\n}", "func (o *AssetReportFreddieGetResponse) SetSchemaVersion(v float32) {\n\to.SchemaVersion = v\n}", "func (o *SettingsObjectUpdate) GetSchemaVersionOk() (*string, bool) {\n\tif o == nil || o.SchemaVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SchemaVersion, true\n}", "func (o SchemaOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Schema) pulumi.StringOutput { return v.Version }).(pulumi.StringOutput)\n}", "func (o *SchemaDefinitionRestDto) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (o *SettingsObjectUpdate) SetSchemaVersion(v string) {\n\to.SchemaVersion = &v\n}", "func (a *Client) GetSchemaByVersion(params *GetSchemaByVersionParams) (*GetSchemaByVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaByVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaByVersion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaByVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetSchemaByVersionOK), nil\n\n}", "func (m *SynchronizationSchema) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (a *Client) GetSchemaByVersion(params *GetSchemaByVersionParams) (*GetSchemaByVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaByVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaByVersion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaByVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSchemaByVersionOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSchemaByVersion: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportPtrOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExport) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OutputSchemaVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationStorageClassAnalysisDataExport) *string { return v.OutputSchemaVersion }).(pulumi.StringPtrOutput)\n}", "func GetDefaultSchemaVersion() schema.Version {\n\tver, err := schema.GetSemver(CNABSpecVersion)\n\tif err != nil {\n\t\t// We check that this can compile at build time, so if this fails, something is seriously wrong\n\t\tpanic(err)\n\t}\n\treturn ver\n}", "func (tr *SQLFunction) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (tr *Service) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (tr *Cluster) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (c *DefaultApiService) FetchSchemaVersion(Id string, SchemaVersion int32) (*EventsV1SchemaSchemaVersion, error) {\n\tpath := \"/v1/Schemas/{Id}/Versions/{SchemaVersion}\"\n\tpath = strings.Replace(path, \"{\"+\"Id\"+\"}\", Id, -1)\n\tpath = strings.Replace(path, \"{\"+\"SchemaVersion\"+\"}\", fmt.Sprint(SchemaVersion), -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &EventsV1SchemaSchemaVersion{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (o *ConnectorTypeAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (o *ConnectorTypeAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (tr *Account) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *WorkflowWorkflowDefinitionAllOf) GetVersion() int64 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (tr *SQLTrigger) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *SettingsObjectUpdate) HasSchemaVersion() bool {\n\tif o != nil && o.SchemaVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UpdateMetricRulesetRequest) GetVersion() int64 {\n\tif o == nil || isNil(o.Version) {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (o *DeviceStatusTrigger) GetVersion() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Version\n}", "func (tr *SQLStoredProcedure) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (tr *SQLDatabase) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (tr *Table) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func getChartVersionSchema(w http.ResponseWriter, req *http.Request, params Params) {\n\tdb, closer := dbSession.DB()\n\tdefer closer()\n\tvar files models.ChartFiles\n\tfileID := fmt.Sprintf(\"%s/%s-%s\", params[\"repo\"], params[\"chartName\"], params[\"version\"])\n\tif err := db.C(filesCollection).FindId(fileID).One(&files); err != nil {\n\t\tlog.WithError(err).Errorf(\"could not find values.schema.json with id %s\", fileID)\n\t\thttp.NotFound(w, req)\n\t\treturn\n\t}\n\n\tw.Write([]byte(files.Schema))\n}", "func (tr *SQLContainer) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (client *CachedSchemaRegistryClient) GetSchemaByVersion(subject string, version int) (*goavro.Codec, error) {\n\treturn client.SchemaRegistryClient.GetSchemaByVersion(subject, version)\n}", "func (tr *TaskDefinition) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (o *SchemaDefinitionRestDto) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (tr *CapacityProvider) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (tr *MongoDatabase) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (swagger *MgwSwagger) GetVersion() string {\n\treturn swagger.version\n}", "func (o *DeviceResourceVersionValueWeb) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (c *DefaultApiService) ListSchemaVersion(Id string, params *ListSchemaVersionParams) (*ListSchemaVersionResponse, error) {\n\tpath := \"/v1/Schemas/{Id}/Versions\"\n\tpath = strings.Replace(path, \"{\"+\"Id\"+\"}\", Id, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.PageSize != nil {\n\t\tdata.Set(\"PageSize\", fmt.Sprint(*params.PageSize))\n\t}\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &ListSchemaVersionResponse{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (m *DigicamControl) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}", "func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRef) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)\n}", "func (o *WorkflowServiceItemDefinitionAllOf) GetVersion() int64 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (m *Heartbeat) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}", "func (m *AdapTuning) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}", "func (tr *CassandraTable) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (tr *MongoCollection) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetVersion() int32 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (s *DatabaseServerV3) GetVersion() string {\n\treturn s.Version\n}", "func (o *LoraNetworkTrigger) GetVersion() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Version\n}", "func (s *DescribeHubContentOutput) SetDocumentSchemaVersion(v string) *DescribeHubContentOutput {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (s *HubContentInfo) SetDocumentSchemaVersion(v string) *HubContentInfo {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (tr *NotebookWorkspace) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *DnsZoneDataData) GetServerVersion() string {\n\tif o == nil || o.ServerVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ServerVersion\n}", "func (o VirtualDatabaseSpecEnvValueFromFieldRefOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecEnvValueFromFieldRef) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)\n}", "func (o *ZoneZone) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (s *ImportHubContentInput) SetDocumentSchemaVersion(v string) *ImportHubContentInput {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *GroupPolicyDefinition) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (policy ServersConnectionPolicy) GetAPIVersion() string {\n\treturn string(APIVersion_Value)\n}", "func (o *NSQProducer) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (ls ListSchema) XMsVersion() string {\n\treturn ls.rawResponse.Header.Get(\"x-ms-version\")\n}", "func (o *WebhooksJsonWebhook) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (obj *Edge) GetVersion() int {\n\treturn obj.getVersion()\n}", "func (tr *CassandraKeySpace) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (tr *GremlinDatabase) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (o *Version) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (s *AppServerV3) GetVersion() string {\n\treturn s.Version\n}", "func (tee *Tee) GetVSchema(ctx context.Context) (string, error) {\n\treturn tee.readFrom.GetVSchema(ctx)\n}", "func (o VirtualDatabaseSpecBuildEnvValueFromFieldRefOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuildEnvValueFromFieldRef) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)\n}", "func (o *HyperflexHealthCheckPackageChecksum) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (a *Client) DeleteSchemaVersion(params *DeleteSchemaVersionParams) (*DeleteSchemaVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteSchemaVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteSchemaVersion\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteSchemaVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*DeleteSchemaVersionOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for deleteSchemaVersion: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *DefaultConstr) GetSchema(conn *sql.DB) (string, error) {\n\treturn \"\", ErrorNotSupport\n}", "func (o VirtualDatabaseSpecEnvValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecEnvValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func (wlt *Wallet) GetVersion() string {\n\treturn wlt.Meta[\"version\"]\n}", "func (database SqlDatabase) GetAPIVersion() string {\n\treturn string(APIVersion_Value)\n}", "func (tr *GremlinGraph) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (o *KubernetesAddonDefinitionAllOf) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func checkSchemaVersion(version string) error {\n\t// First get the major version number from the schema. The schema version string should be in the format\n\t// \"major.minor.patch\", \"major.minor\", or \"major\".\n\n\tparts := strings.Split(version, \".\")\n\tif len(parts) == 0 {\n\t\treturn fmt.Errorf(\"error splitting schema version %q into parts\", version)\n\t}\n\n\tmajorVersion, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting major version component %q to an integer: %v\", parts[0], err)\n\t}\n\n\t// Find the latest supported version for the major version and use that to determine if the provided version is\n\t// supported.\n\tsupportedVersion, ok := supportedSchemaVersions[majorVersion]\n\tif !ok {\n\t\treturn fmt.Errorf(\"major version %d not supported\", majorVersion)\n\t}\n\tif mtest.CompareServerVersions(supportedVersion, version) < 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"latest version supported for major version %d is %q, which is incompatible with specified version %q\",\n\t\t\tmajorVersion, supportedVersion, version,\n\t\t)\n\t}\n\treturn nil\n}", "func (o HiveMetastoreConfigPtrOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *HiveMetastoreConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Version\n\t}).(pulumi.StringPtrOutput)\n}", "func (ds *DatasetAPI) GetVersion(ctx context.Context, userAuthToken, serviceAuthToken, downloadServiceAuthToken, collectionID, datasetID, edition, version string) (m dataset.Version, err error) {\n\tif ds.Cfg.InternalServerError {\n\t\treturn m, errorInternalServer\n\t}\n\n\tif ds.Cfg.VersionNotFound {\n\t\treturn m, filters.ErrVersionNotFound\n\t}\n\n\tif ds.Cfg.Unpublished {\n\t\treturn dataset.Version{\n\t\t\tLinks: dataset.Links{\n\t\t\t\tDataset: dataset.Link{\n\t\t\t\t\tID: \"123\",\n\t\t\t\t},\n\t\t\t\tEdition: dataset.Link{\n\t\t\t\t\tID: \"2017\",\n\t\t\t\t},\n\t\t\t\tVersion: dataset.Link{\n\t\t\t\t\tID: \"1\",\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn dataset.Version{\n\t\tLinks: dataset.Links{\n\t\t\tDataset: dataset.Link{\n\t\t\t\tID: \"123\",\n\t\t\t},\n\t\t\tEdition: dataset.Link{\n\t\t\t\tID: \"2017\",\n\t\t\t},\n\t\t\tVersion: dataset.Link{\n\t\t\t\tID: \"1\",\n\t\t\t},\n\t\t},\n\t\tState: \"published\",\n\t}, nil\n}", "func (a *Client) DeleteSchemaVersion(params *DeleteSchemaVersionParams) (*DeleteSchemaVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteSchemaVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteSchemaVersion\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteSchemaVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*DeleteSchemaVersionOK), nil\n\n}", "func (m *ComponentInformation) GetVersion() int {\n\tif m.HasExtensionFieldValues {\n\t\treturn 2\n\t}\n\n\treturn 1\n}", "func (vdb *VspDatabase) Version() (uint32, error) {\n\tvar version uint32\n\terr := vdb.db.View(func(tx *bolt.Tx) error {\n\t\tbytes := tx.Bucket(vspBktK).Get(versionK)\n\t\tversion = bytesToUint32(bytes)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn version, nil\n}", "func (o *EntityWatchlistScreeningSearchTerms) GetVersion() int32 {\n\tif o == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\n\treturn o.Version\n}", "func (d DB) GetWorkflowDataVersion(ctx context.Context, workflowID string) (int32, error) {\n\tif workflowID == workflowForErr {\n\t\treturn -1, errors.New(\"SELECT from workflow_data\")\n\t}\n\tif workflowID == firstWorkflowID {\n\t\treturn 2, nil\n\t}\n\treturn 0, nil\n}", "func (a *BaseAggregateSourced) GetVersion() int {\n\treturn a.Version\n}", "func (m *GraphDef) GetVersion() int32 {\n\tif m != nil {\n\t\treturn m.Version\n\t}\n\treturn 0\n}", "func (o *VirtualizationIweHost) GetVersion() string {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (o Hl7SchemaConfigOutput) Version() VersionSourceArrayOutput {\n\treturn o.ApplyT(func(v Hl7SchemaConfig) []VersionSource { return v.Version }).(VersionSourceArrayOutput)\n}", "func (o VirtualDatabaseSpecBuildEnvValueFromFieldRefPtrOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *VirtualDatabaseSpecBuildEnvValueFromFieldRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ApiVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func (f *Features) getVersion(ctx context.Context, adminDB *mongo.Database) {\n\tcmd := bson.D{\n\t\t{\n\t\t\tKey: \"buildInfo\",\n\t\t\tValue: 1,\n\t\t},\n\t}\n\tvar result buildInfo\n\terr := adminDB.RunCommand(ctx, cmd).Decode(&result)\n\tif err != nil {\n\t\tf.MongoVersion = &semver.Version{}\n\t\treturn\n\t}\n\n\tf.MongoVersion = semver.MustParse(result.Version)\n}", "func (m *Migrate) Version() (uint64, string, error) {\n\tif err := m.createCollectionIfNotExist(m.migrationsCollection); err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\tfilter := bson.D{{}}\n\tsort := bson.D{bson.E{Key: \"_id\", Value: -1}}\n\toptions := options.FindOne().SetSort(sort)\n\n\t// find record with greatest id (assuming it`s latest also)\n\tresult := m.db.Collection(m.migrationsCollection).FindOne(context.TODO(), filter, options)\n\terr := result.Err()\n\tswitch {\n\tcase err == mongo.ErrNoDocuments:\n\t\treturn 0, \"\", nil\n\tcase err != nil:\n\t\treturn 0, \"\", err\n\t}\n\n\tvar rec versionRecord\n\tif err := result.Decode(&rec); err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treturn rec.Version, rec.Description, nil\n}", "func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}", "func (entry *Entry) GetVersion() int {\n\tversion := 1\n\tif entry.Sys != nil {\n\t\tversion = entry.Sys.Version\n\t}\n\n\treturn version\n}", "func (o *MicrosoftGraphSharedPcConfiguration) GetVersion() int32 {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Version\n}", "func (s *LDBStore) GetSchema() (string, error) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tdata, err := s.db.Get(keySchema)\n\tif err != nil {\n\t\tif err == leveldb.ErrNotFound {\n\t\t\treturn DbSchemaNone, nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn string(data), nil\n}", "func (s *Store) GetVersion(ctx context.Context) (string, error) {\n\t// We treat the existence of cells_subscriptions as running on the initial\n\t// version, 1.0.0\n\tconst query = `\n\t\tSELECT EXISTS (\n \t\tSELECT *\n\t\t FROM information_schema.tables \n \t\tWHERE table_name = 'cells_subscriptions'\n )`\n\trow := s.db.QueryRowContext(ctx, query)\n\tvar ret bool\n\terr := row.Scan(&ret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif ret {\n\t\t// Base version\n\t\treturn \"v1.0.0\", nil\n\t}\n\t// Version without cells joins table.\n\t// TODO: leverage proper migrations and use something like the query below.\n\treturn \"v2.0.0\", nil\n}", "func (m *ManagedAppPolicy) GetVersion()(*string) {\n return m.version\n}" ]
[ "0.7970623", "0.74781895", "0.6867894", "0.6842162", "0.67921835", "0.6782608", "0.6602236", "0.6566277", "0.6431879", "0.6419203", "0.63856447", "0.63427097", "0.632473", "0.62778425", "0.6276965", "0.6243085", "0.6225449", "0.6055605", "0.60500544", "0.6035883", "0.6035883", "0.5999954", "0.59834623", "0.5981031", "0.5965183", "0.5948516", "0.5887489", "0.58497554", "0.5846463", "0.58167034", "0.58133996", "0.58054936", "0.5762464", "0.57343745", "0.57191354", "0.5718395", "0.57068205", "0.5665727", "0.5659685", "0.5654149", "0.5619703", "0.56184053", "0.5614731", "0.5607492", "0.55938786", "0.55898017", "0.5579822", "0.5578032", "0.55592996", "0.5544815", "0.5539096", "0.5511429", "0.55029273", "0.5500702", "0.5486255", "0.5479747", "0.54736465", "0.5472234", "0.54657257", "0.5463598", "0.54624224", "0.5460942", "0.54597014", "0.5452706", "0.5448706", "0.54445547", "0.5432812", "0.5411527", "0.5396845", "0.5386648", "0.53848857", "0.53823197", "0.5380763", "0.5377129", "0.5373061", "0.5361238", "0.5360598", "0.5358773", "0.53549683", "0.5354737", "0.5351774", "0.5345232", "0.53375834", "0.53293335", "0.5328607", "0.53238887", "0.53147584", "0.5309627", "0.5305544", "0.53046536", "0.53017724", "0.52973235", "0.5289291", "0.5286809", "0.5261971", "0.5261971", "0.5258677", "0.5252256", "0.5235146", "0.52162164" ]
0.78521794
1
GetSchemaVersionOk returns a tuple with the SchemaVersion field value if set, nil otherwise and a boolean to check if the value has been set.
func (o *SettingsObjectUpdate) GetSchemaVersionOk() (*string, bool) { if o == nil || o.SchemaVersion == nil { return nil, false } return o.SchemaVersion, true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AssetReportFreddieGetResponse) GetSchemaVersionOk() (*float32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.SchemaVersion, true\n}", "func (o *SchemaDefinitionRestDto) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ConnectorTypeAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ConnectorTypeAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *WorkflowWorkflowDefinitionAllOf) GetVersionOk() (*int64, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *DeviceStatusTrigger) GetVersionOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Version, true\n}", "func (o *NSQProducer) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *UpdateMetricRulesetRequest) GetVersionOk() (*int64, bool) {\n\tif o == nil || isNil(o.Version) {\n return nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *Version) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *AssetReportFreddieGetResponse) GetSchemaVersion() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.SchemaVersion\n}", "func (o *WorkflowServiceItemDefinitionAllOf) GetVersionOk() (*int64, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *MicrosoftGraphSharedPcConfiguration) GetVersionOk() (int32, bool) {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret, false\n\t}\n\treturn *o.Version, true\n}", "func (o *LoraNetworkTrigger) GetVersionOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Version, true\n}", "func (o *ZoneZone) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *WebhooksJsonWebhook) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *SettingsObjectUpdate) HasSchemaVersion() bool {\n\tif o != nil && o.SchemaVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *KubernetesAddonDefinitionAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *TeamConfiguration) GetVersionOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Version, true\n}", "func (o *DnsZoneDataData) GetServerVersionOk() (*string, bool) {\n\tif o == nil || o.ServerVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerVersion, true\n}", "func (o *TransactionResult) GetVersionOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version.Get(), o.Version.IsSet()\n}", "func (o *DeviceResourceVersionValueWeb) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *EnvironmentAutoUpdateConfig) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *HyperflexHealthCheckPackageChecksum) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *VirtualizationIweHost) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *VersionedFlowCoordinates) GetVersionOk() (*int32, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetVersionOk() (int32, bool) {\n\tif o == nil || o.Version == nil {\n\t\tvar ret int32\n\t\treturn ret, false\n\t}\n\treturn *o.Version, true\n}", "func (o *Content) GetPyVersionOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PyVersion.Get(), o.PyVersion.IsSet()\n}", "func (o *SoftwareTechs) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *SettingsObjectUpdate) GetSchemaVersion() string {\n\tif o == nil || o.SchemaVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SchemaVersion\n}", "func (o *EntityWatchlistScreeningSearchTerms) GetVersionOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Version, true\n}", "func (r *Document) SchemaVersion() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"schemaVersion\"])\n}", "func (o *InterfaceCapability) GetVersionOk() (*int32, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *NetworkElementSummaryAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *SoftwarerepositoryCategoryMapper) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ApplianceImageBundleAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *DhcpRangeDataData) GetServerVersionOk() (*string, bool) {\n\tif o == nil || o.ServerVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerVersion, true\n}", "func (o *SchemaDefinitionRestDto) GetSchemaIdOk() (*string, bool) {\n\tif o == nil || o.SchemaId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SchemaId, true\n}", "func (o *EquipmentIoCardBase) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *Ga4ghExternalIdentifier) GetVersionOk() (string, bool) {\n\tif o == nil || o.Version == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Version, true\n}", "func (o *NiaapiNewReleaseDetailAllOf) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func (o *ConnectorTypeAllOf) GetJsonSchemaOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.JsonSchema == nil {\n\t\treturn nil, false\n\t}\n\treturn o.JsonSchema, true\n}", "func (o *ConnectorTypeAllOf) GetJsonSchemaOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.JsonSchema == nil {\n\t\treturn nil, false\n\t}\n\treturn o.JsonSchema, true\n}", "func (o *Content) GetRVersionOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RVersion.Get(), o.RVersion.IsSet()\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) GetServerFirmwareVersionOk() (*HyperflexServerFirmwareVersionRelationship, bool) {\n\tif o == nil || o.ServerFirmwareVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerFirmwareVersion, true\n}", "func (o *HclFirmware) GetFirmwareVersionOk() (*string, bool) {\n\tif o == nil || o.FirmwareVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.FirmwareVersion, true\n}", "func (o *HyperflexSoftwareVersionPolicy) GetServerFirmwareVersionOk() (*string, bool) {\n\tif o == nil || o.ServerFirmwareVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerFirmwareVersion, true\n}", "func (o *WorkflowWorkflowDefinitionAllOf) GetDefaultVersionOk() (*bool, bool) {\n\tif o == nil || o.DefaultVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DefaultVersion, true\n}", "func (o *HyperflexSoftwareVersionPolicy) GetServerFirmwareVersionInfoOk() (*FirmwareDistributableRelationship, bool) {\n\tif o == nil || o.ServerFirmwareVersionInfo == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerFirmwareVersionInfo, true\n}", "func (st *Store) schemaVersion() (int, error) {\n\tvar n string\n\terr := st.db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name='version';`).Scan(&n)\n\tif err == sql.ErrNoRows {\n\t\treturn 0, nil // assume db is blank\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar v int\n\terr = st.db.QueryRow(`SELECT MAX(ver) FROM version`).Scan(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn v, nil\n}", "func (o *Cluster) GetBuildVersionOk() (*string, bool) {\n\tif o == nil || o.BuildVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.BuildVersion, true\n}", "func (o *SchemaDefinitionRestDto) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NetworkElementSummaryAllOf) GetFirmwareVersionOk() (*string, bool) {\n\tif o == nil || o.FirmwareVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.FirmwareVersion, true\n}", "func (o *IaasDeviceStatusAllOf) GetDeviceVersionOk() (*string, bool) {\n\tif o == nil || o.DeviceVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DeviceVersion, true\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) GetConstraintOk() (*HyperflexAppSettingConstraint, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Constraint.Get(), o.Constraint.IsSet()\n}", "func (o SchemaOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Schema) pulumi.StringOutput { return v.Version }).(pulumi.StringOutput)\n}", "func (o *VirtualizationIweClusterAllOf) GetHxVersionOk() (*string, bool) {\n\tif o == nil || o.HxVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HxVersion, true\n}", "func (o *UcsdBackupInfoAllOf) GetProductVersionOk() (*string, bool) {\n\tif o == nil || o.ProductVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ProductVersion, true\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationStorageClassAnalysisDataExport) *string { return v.OutputSchemaVersion }).(pulumi.StringPtrOutput)\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportPtrOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExport) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OutputSchemaVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func NewUpdateSchemaOK() *UpdateSchemaOK {\n\treturn &UpdateSchemaOK{}\n}", "func checkSchemaVersion(version string) error {\n\t// First get the major version number from the schema. The schema version string should be in the format\n\t// \"major.minor.patch\", \"major.minor\", or \"major\".\n\n\tparts := strings.Split(version, \".\")\n\tif len(parts) == 0 {\n\t\treturn fmt.Errorf(\"error splitting schema version %q into parts\", version)\n\t}\n\n\tmajorVersion, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting major version component %q to an integer: %v\", parts[0], err)\n\t}\n\n\t// Find the latest supported version for the major version and use that to determine if the provided version is\n\t// supported.\n\tsupportedVersion, ok := supportedSchemaVersions[majorVersion]\n\tif !ok {\n\t\treturn fmt.Errorf(\"major version %d not supported\", majorVersion)\n\t}\n\tif mtest.CompareServerVersions(supportedVersion, version) < 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"latest version supported for major version %d is %q, which is incompatible with specified version %q\",\n\t\t\tmajorVersion, supportedVersion, version,\n\t\t)\n\t}\n\treturn nil\n}", "func (o *NetworkElementSummaryAllOf) GetBundleVersionOk() (*string, bool) {\n\tif o == nil || o.BundleVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.BundleVersion, true\n}", "func (tr *SQLFunction) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *V0037Node) GetSlurmdVersionOk() (*string, bool) {\n\tif o == nil || o.SlurmdVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SlurmdVersion, true\n}", "func (o *AssetReportFreddieGetResponse) SetSchemaVersion(v float32) {\n\to.SchemaVersion = v\n}", "func (o *HclFirmware) GetDriverVersionOk() (*string, bool) {\n\tif o == nil || o.DriverVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DriverVersion, true\n}", "func (v *HandshakeResponse) IsSetLibraryVersion() bool {\n\treturn v != nil && v.LibraryVersion != nil\n}", "func (tr *Service) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetVmVersionOk() (*string, bool) {\n\tif o == nil || o.VmVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VmVersion, true\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHxdpVersionOk() (*string, bool) {\n\tif o == nil || o.HxdpVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HxdpVersion, true\n}", "func (o *ResourceVersion) GetResourceVersionIdOk() (*string, bool) {\n\tif o == nil || o.ResourceVersionId == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ResourceVersionId, true\n}", "func (o *ControllersUpdateGlobalConfigRequest) GetVersionAvailabilityOk() (*string, bool) {\n\tif o == nil || o.VersionAvailability == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VersionAvailability, true\n}", "func (o *VirtualizationIweHost) GetChassisVersionOk() (*string, bool) {\n\tif o == nil || o.ChassisVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ChassisVersion, true\n}", "func (o *DeviceResourceVersionValueWeb) GetTimestampOk() (*string, bool) {\n\tif o == nil || o.Timestamp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Timestamp, true\n}", "func (o *ResourceVersion) GetChecksumOk() (*string, bool) {\n\tif o == nil || o.Checksum == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Checksum, true\n}", "func (tr *SQLTrigger) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHypervisorVersionOk() (*string, bool) {\n\tif o == nil || o.HypervisorVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HypervisorVersion, true\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetNumberOfSchemasInMsoOk() (*int64, bool) {\n\tif o == nil || o.NumberOfSchemasInMso == nil {\n\t\treturn nil, false\n\t}\n\treturn o.NumberOfSchemasInMso, true\n}", "func (tr *SQLStoredProcedure) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (a *Client) GetSchemaByVersion(params *GetSchemaByVersionParams) (*GetSchemaByVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSchemaByVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getSchemaByVersion\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetSchemaByVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSchemaByVersionOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSchemaByVersion: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (tr *Account) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *UpdateMetricRulesetRequest) HasVersion() bool {\n\tif o != nil && !isNil(o.Version) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Service) GetOsVersionOk() (string, bool) {\n\tif o == nil || o.OsVersion == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.OsVersion, true\n}", "func (m *SynchronizationSchema) GetVersion()(*string) {\n val, err := m.GetBackingStore().Get(\"version\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (p *Peer) VersionKnown() bool {\n\tp.flagsMtx.Lock()\n\tversionKnown := p.versionKnown\n\tp.flagsMtx.Unlock()\n\n\treturn versionKnown\n}", "func SchemaUpToDate(db *sql.DB) bool {\n\tvar v int\n\trow := db.QueryRow(`SELECT version FROM schema_version`)\n\treturn row.Scan(&v) == nil && v >= SchemaVersion\n}", "func (o *HyperflexHealthCheckPackageChecksum) GetTimestampOk() (*time.Time, bool) {\n\tif o == nil || o.Timestamp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Timestamp, true\n}", "func (tr *Cluster) GetTerraformSchemaVersion() int {\n\treturn 0\n}", "func (o *AppVersion) GetNumberOk() (*int32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Number, true\n}", "func (o *ApplianceSetupInfoAllOf) GetLatestVersionOk() (*string, bool) {\n\tif o == nil || o.LatestVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.LatestVersion, true\n}", "func (o *FileversionFileversion) GetFileSizeOk() (*int32, bool) {\n\tif o == nil || o.FileSize == nil {\n\t\treturn nil, false\n\t}\n\treturn o.FileSize, true\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHxdpVersionInfoOk() (*SoftwareHyperflexDistributableRelationship, bool) {\n\tif o == nil || o.HxdpVersionInfo == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HxdpVersionInfo, true\n}", "func CfnSchemaVersion_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_glue.CfnSchemaVersion\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *KubernetesNodeGroupProfile) GetKubernetesVersionOk() (*KubernetesVersionPolicyRelationship, bool) {\n\tif o == nil || o.KubernetesVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.KubernetesVersion, true\n}", "func (c *Client) CheckSchemaVersionValidity(ctx context.Context, params *CheckSchemaVersionValidityInput, optFns ...func(*Options)) (*CheckSchemaVersionValidityOutput, error) {\n\tif params == nil {\n\t\tparams = &CheckSchemaVersionValidityInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CheckSchemaVersionValidity\", params, optFns, addOperationCheckSchemaVersionValidityMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CheckSchemaVersionValidityOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (o *DnsViewparamDataData) GetServerNameOk() (*string, bool) {\n\tif o == nil || o.ServerName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ServerName, true\n}", "func (tr *Table) GetTerraformSchemaVersion() int {\n\treturn 1\n}", "func (o *WindowsMobileMsi) GetProductVersionOk() (string, bool) {\n\tif o == nil || o.ProductVersion == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.ProductVersion, true\n}", "func (vr *VersionResponse) IsOk() bool {\n\treturn len(vr.version) > 0\n}" ]
[ "0.8131577", "0.7319821", "0.7140072", "0.7140072", "0.69523525", "0.6814122", "0.67269975", "0.672043", "0.67154175", "0.6706337", "0.66972786", "0.6662691", "0.66505027", "0.66086847", "0.659903", "0.6589485", "0.6587396", "0.6575269", "0.65545875", "0.65536755", "0.6543949", "0.65260696", "0.6508249", "0.65059984", "0.65049136", "0.64876896", "0.6427354", "0.64118147", "0.6397967", "0.6343293", "0.62846804", "0.62072486", "0.62000334", "0.61903584", "0.6185624", "0.6159641", "0.6124251", "0.61221784", "0.60365427", "0.6027319", "0.6008707", "0.59706056", "0.59706056", "0.59564877", "0.595215", "0.5943013", "0.58601296", "0.58577895", "0.5832912", "0.5737667", "0.57061255", "0.56673926", "0.565824", "0.56408566", "0.5628302", "0.5623716", "0.56146616", "0.55658567", "0.5555266", "0.5553622", "0.55533415", "0.55425537", "0.55399686", "0.55332047", "0.55134654", "0.55126643", "0.545062", "0.54262877", "0.5424804", "0.54226816", "0.5394561", "0.53905165", "0.53583115", "0.5327706", "0.53069854", "0.5293177", "0.5291638", "0.5274719", "0.52571017", "0.5246548", "0.52380764", "0.5237391", "0.5226446", "0.52131957", "0.52053887", "0.5204791", "0.52017283", "0.52006596", "0.5200179", "0.5182367", "0.5167345", "0.5156426", "0.5144741", "0.51436234", "0.51254874", "0.51246214", "0.5116985", "0.5112882", "0.51034474", "0.51003486" ]
0.8353736
0
HasSchemaVersion returns a boolean if a field has been set.
func (o *SettingsObjectUpdate) HasSchemaVersion() bool { if o != nil && o.SchemaVersion != nil { return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *SchemaDefinitionRestDto) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UpdateMetricRulesetRequest) HasVersion() bool {\n\tif o != nil && !isNil(o.Version) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ConnectorTypeAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ConnectorTypeAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *WebhooksJsonWebhook) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Version) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *WorkflowWorkflowDefinitionAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NSQProducer) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *TransactionResult) HasVersion() bool {\n\tif o != nil && o.Version.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexHealthCheckPackageChecksum) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VersionedFlowCoordinates) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *WorkflowServiceItemDefinitionAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SoftwareTechs) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *EnvironmentAutoUpdateConfig) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DeviceResourceVersionValueWeb) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VirtualizationIweHost) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ZoneZone) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DnsZoneDataData) HasServerVersion() bool {\n\tif o != nil && o.ServerVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (pr LocalPackageReference) HasApiVersion(ver string) bool {\n\treturn strings.EqualFold(pr.apiVersion, ver)\n}", "func (o *SchemaDefinitionRestDto) HasSchemaId() bool {\n\tif o != nil && o.SchemaId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SoftwarerepositoryCategoryMapper) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *KubernetesAddonDefinitionAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NetworkElementSummaryAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SettingsObjectUpdate) GetSchemaVersionOk() (*string, bool) {\n\tif o == nil || o.SchemaVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SchemaVersion, true\n}", "func (o *Content) HasPyVersion() bool {\n\tif o != nil && o.PyVersion.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NiaapiNewReleaseDetailAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (dir *Dir) HasSchema() bool {\n\t// We intentionally only return true if *this dir's option file* sets a schema,\n\t// rather than using dir.Config.Changed(\"schema\") which would also consider\n\t// parent dirs. This way, users can store arbitrary things in subdirs without\n\t// Skeema interpreting them incorrectly.\n\tif dir.OptionFile != nil {\n\t\tif val, _ := dir.OptionFile.OptionValue(\"schema\"); val != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, logicalSchema := range dir.LogicalSchemas {\n\t\tif logicalSchema.Name != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (dir *Dir) HasSchema() bool {\n\t// We intentionally only return true if *this dir's option file* sets a schema,\n\t// rather than using dir.Config.Changed(\"schema\") which would also consider\n\t// parent dirs. This way, users can store arbitrary things in subdirs without\n\t// Skeema interpreting them incorrectly.\n\tif dir.OptionFile != nil {\n\t\tif val, _ := dir.OptionFile.OptionValue(\"schema\"); val != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, logicalSchema := range dir.LogicalSchemas {\n\t\tif logicalSchema.Name != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *MicrosoftGraphSharedPcConfiguration) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasServerFirmwareVersionInfo() bool {\n\tif o != nil && o.ServerFirmwareVersionInfo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasServerFirmwareVersion() bool {\n\tif o != nil && o.ServerFirmwareVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Ga4ghExternalIdentifier) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func SchemaUpToDate(db *sql.DB) bool {\n\tvar v int\n\trow := db.QueryRow(`SELECT version FROM schema_version`)\n\treturn row.Scan(&v) == nil && v >= SchemaVersion\n}", "func (o *EquipmentIoCardBase) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HclFirmware) HasFirmwareVersion() bool {\n\tif o != nil && o.FirmwareVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (v *HandshakeResponse) IsSetLibraryVersion() bool {\n\treturn v != nil && v.LibraryVersion != nil\n}", "func (o *DhcpRangeDataData) HasServerVersion() bool {\n\tif o != nil && o.ServerVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ns *VersionNamespace) IsSet() bool {\n\treturn ns.config != nil\n}", "func (o *InterfaceCapability) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *AssetReportFreddieGetResponse) GetSchemaVersionOk() (*float32, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.SchemaVersion, true\n}", "func (o *Content) HasRVersion() bool {\n\tif o != nil && o.RVersion.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (entry *TableEntry) isColumnChangedInSchema() bool {\n\t// in commit queue, it is safe\n\tnode := entry.GetLatestNodeLocked()\n\ttoCommitted := node.BaseNode.Schema\n\tver := toCommitted.Version\n\t// skip create table\n\tif ver == 0 {\n\t\treturn false\n\t}\n\treturn toCommitted.Extra.ColumnChanged\n}", "func (o *V0037Node) HasSlurmdVersion() bool {\n\tif o != nil && o.SlurmdVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (d UserData) HasHexyaVersion() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"HexyaVersion\", \"hexya_version\"))\n}", "func (o *ApplianceImageBundleAllOf) HasVersion() bool {\n\tif o != nil && o.Version != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *AssetReportFreddieGetResponse) GetSchemaVersion() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.SchemaVersion\n}", "func (r *Document) SchemaVersion() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"schemaVersion\"])\n}", "func (o *Cluster) HasBuildVersion() bool {\n\tif o != nil && o.BuildVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *Structx) HasField(name string) bool {\n\t_, ok := s.value.Type().FieldByName(name)\n\treturn ok\n}", "func (o *HyperflexServerFirmwareVersionEntryAllOf) HasServerFirmwareVersion() bool {\n\tif o != nil && o.ServerFirmwareVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SettingsObjectUpdate) GetSchemaVersion() string {\n\tif o == nil || o.SchemaVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SchemaVersion\n}", "func (o *ControllersUpdateGlobalConfigRequest) HasVersionUpdatability() bool {\n\tif o != nil && o.VersionUpdatability != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasServerFirmwareVersions() bool {\n\tif o != nil && o.ServerFirmwareVersions != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasHypervisorVersion() bool {\n\tif o != nil && o.HypervisorVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasHxdpVersionInfo() bool {\n\tif o != nil && o.HxdpVersionInfo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (f *FlowState) HasValidVersion() bool {\n\treturn f != nil && f.Kind == FlowStateKind && f.APIVersion == SchemeGroupVersion.String()\n}", "func (s Schema) HasKey(key string) bool {\n\treturn hasKey(key, s)\n}", "func (o *ConnectorTypeAllOf) HasJsonSchema() bool {\n\tif o != nil && o.JsonSchema != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ConnectorTypeAllOf) HasJsonSchema() bool {\n\tif o != nil && o.JsonSchema != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (x *fastReflection_ValidatorSlashEventRecord) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"cosmos.distribution.v1beta1.ValidatorSlashEventRecord.validator_address\":\n\t\treturn x.ValidatorAddress != \"\"\n\tcase \"cosmos.distribution.v1beta1.ValidatorSlashEventRecord.height\":\n\t\treturn x.Height != uint64(0)\n\tcase \"cosmos.distribution.v1beta1.ValidatorSlashEventRecord.period\":\n\t\treturn x.Period != uint64(0)\n\tcase \"cosmos.distribution.v1beta1.ValidatorSlashEventRecord.validator_slash_event\":\n\t\treturn x.ValidatorSlashEvent != nil\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.ValidatorSlashEventRecord\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.ValidatorSlashEventRecord does not contain field %s\", fd.FullName()))\n\t}\n}", "func (pr LocalPackageReference) HasVersionPrefix(prefix string) bool {\n\treturn pr.generatorVersion == prefix\n}", "func (o *HyperflexSoftwareVersionPolicy) HasHxdpVersion() bool {\n\tif o != nil && o.HxdpVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ControllersUpdateGlobalConfigRequest) HasVersionAvailability() bool {\n\tif o != nil && o.VersionAvailability != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CfnSchemaVersion_IsConstruct(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_glue.CfnSchemaVersion\",\n\t\t\"isConstruct\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *UpdatesV3Request) HasReleasever() bool {\n\tif o != nil && o.Releasever != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *Struct) HasField(name string) bool {\n\tfor _, f := range s.Fields {\n\t\tif f.Name == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func CfnSchemaVersion_IsCfnElement(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_glue.CfnSchemaVersion\",\n\t\t\"isCfnElement\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (f *STAGFields) HasVID() bool {\n\treturn has3rdBit(f.Flags)\n}", "func (c *Schema) Required() bool {\n\treturn c.required\n}", "func (o *HclFirmware) HasDriverVersion() bool {\n\tif o != nil && o.DriverVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ResourceVersion) HasChecksum() bool {\n\tif o != nil && o.Checksum != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ResourceVersion) HasResourceVersionId() bool {\n\tif o != nil && o.ResourceVersionId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NetworkElementSummaryAllOf) HasFirmwareVersion() bool {\n\tif o != nil && o.FirmwareVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *AssetReportFreddieGetResponse) SetSchemaVersion(v float32) {\n\to.SchemaVersion = v\n}", "func (o *UcsdBackupInfoAllOf) HasProductVersion() bool {\n\tif o != nil && o.ProductVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SchemaDefinitionRestDto) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VirtualizationIweHost) HasChassisVersion() bool {\n\tif o != nil && o.ChassisVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *HyperflexSoftwareVersionPolicy) HasHypervisorVersionInfo() bool {\n\tif o != nil && o.HypervisorVersionInfo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *Peer) VersionKnown() bool {\n\tp.flagsMtx.Lock()\n\tversionKnown := p.versionKnown\n\tp.flagsMtx.Unlock()\n\n\treturn versionKnown\n}", "func (db DatabaseModel) Valid() bool {\n\treturn !reflect.DeepEqual(db.Schema, ovsdb.DatabaseSchema{})\n}", "func isDefinition(s spec.Schema) bool {\n\treturn len(s.SchemaProps.Ref.GetPointer().String()) > 0\n}", "func (f ExtensionField) IsSet() bool {\n\treturn f.typ != nil\n}", "func isSemverFormat(fl FieldLevel) bool {\n\tsemverString := fl.Field().String()\n\n\treturn semverRegex.MatchString(semverString)\n}", "func (db *DatabaseModel) Valid() bool {\n\tdb.mutex.RLock()\n\tdefer db.mutex.RUnlock()\n\treturn db.schema != nil\n}", "func (release Release) HasBuildStep() bool {\n\treturn len(release.ChartSpec.Dependencies) != 0\n}", "func (o *SchemaDefinitionRestDto) GetVersionOk() (*string, bool) {\n\tif o == nil || o.Version == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Version, true\n}", "func SchemaHas(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path, pred func(s *apiextensionsv1.JSONSchemaProps, fldPath, simpleLocation *field.Path) bool) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tif pred(s, fldPath, simpleLocation) {\n\t\treturn true\n\t}\n\n\tif s.Items != nil {\n\t\tif s.Items != nil && schemaHasRecurse(s.Items.Schema, fldPath.Child(\"items\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t\tfor i := range s.Items.JSONSchemas {\n\t\t\tif schemaHasRecurse(&s.Items.JSONSchemas[i], fldPath.Child(\"items\", \"jsonSchemas\").Index(i), simpleLocation.Index(i), pred) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range s.AllOf {\n\t\tif schemaHasRecurse(&s.AllOf[i], fldPath.Child(\"allOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.AnyOf {\n\t\tif schemaHasRecurse(&s.AnyOf[i], fldPath.Child(\"anyOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.OneOf {\n\t\tif schemaHasRecurse(&s.OneOf[i], fldPath.Child(\"oneOf\").Index(i), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif schemaHasRecurse(s.Not, fldPath.Child(\"not\"), simpleLocation, pred) {\n\t\treturn true\n\t}\n\tfor propertyName, s := range s.Properties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"properties\").Key(propertyName), simpleLocation.Child(propertyName), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalProperties != nil {\n\t\tif schemaHasRecurse(s.AdditionalProperties.Schema, fldPath.Child(\"additionalProperties\", \"schema\"), simpleLocation.Key(\"*\"), pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor patternName, s := range s.PatternProperties {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"allOf\").Key(patternName), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalItems != nil {\n\t\tif schemaHasRecurse(s.AdditionalItems.Schema, fldPath.Child(\"additionalItems\", \"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, s := range s.Definitions {\n\t\tif schemaHasRecurse(&s, fldPath.Child(\"definitions\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor dependencyName, d := range s.Dependencies {\n\t\tif schemaHasRecurse(d.Schema, fldPath.Child(\"dependencies\").Key(dependencyName).Child(\"schema\"), simpleLocation, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *VersionedConnection) HasPartitioningAttribute() bool {\n\tif o != nil && o.PartitioningAttribute != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VulnerabilitiesRequest) HasReleasever() bool {\n\tif o != nil && o.Releasever != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SyntheticsGlobalVariableParseTestOptions) HasField() bool {\n\treturn o != nil && o.Field != nil\n}", "func (o *SettingsObjectUpdate) SetSchemaVersion(v string) {\n\to.SchemaVersion = &v\n}", "func (o *DnsViewparamDataData) HasServerName() bool {\n\tif o != nil && o.ServerName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *WindowsMobileMsi) HasProductVersion() bool {\n\tif o != nil && o.ProductVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *Struct) HasRequiredFields() bool {\n\thasRequired := false\n\tfor _, fld := range s.Fields {\n\t\tif fld.Required() {\n\t\t\thasRequired = true\n\t\t}\n\t}\n\treturn hasRequired\n}", "func IsHasField(st interface{}, fieldName string) bool {\n\treturn HasField(st, fieldName)\n}", "func (o *StatusDescriptorDTO) HasField() bool {\n\tif o != nil && o.Field != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CfnSchemaVersionMetadata_IsCfnElement(x interface{}) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"aws-cdk-lib.aws_glue.CfnSchemaVersionMetadata\",\n\t\t\"isCfnElement\",\n\t\t[]interface{}{x},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *SchemaDefinitionRestDto) HasDocumentation() bool {\n\tif o != nil && o.Documentation != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}" ]
[ "0.73211837", "0.6730211", "0.6564918", "0.6564918", "0.648918", "0.6424302", "0.64201236", "0.6293445", "0.6239788", "0.62033796", "0.6190376", "0.61852074", "0.61417764", "0.6127439", "0.6103071", "0.6092617", "0.6045331", "0.6036138", "0.6026541", "0.6000439", "0.5981915", "0.5976526", "0.5965994", "0.59646547", "0.5947429", "0.59461904", "0.5942374", "0.59224075", "0.5918073", "0.5918073", "0.59166926", "0.5900568", "0.58828276", "0.5850728", "0.5808293", "0.5799427", "0.5741581", "0.57266337", "0.57188445", "0.5691257", "0.5677805", "0.5602033", "0.559257", "0.5592395", "0.5573236", "0.5566534", "0.5557647", "0.5555424", "0.55377686", "0.55353767", "0.5527823", "0.5526664", "0.5524097", "0.54858595", "0.5480478", "0.5448104", "0.54230285", "0.5416634", "0.5415353", "0.53978854", "0.53978854", "0.53427666", "0.5337628", "0.5330199", "0.53283894", "0.53157914", "0.5310322", "0.5305705", "0.5303665", "0.52971596", "0.52934086", "0.5282395", "0.5243323", "0.5239168", "0.5232729", "0.5202983", "0.519923", "0.51677394", "0.5160884", "0.5157749", "0.51577467", "0.5156101", "0.51537174", "0.51509625", "0.5147482", "0.5118463", "0.5114838", "0.51104516", "0.5094631", "0.5093363", "0.5085834", "0.5081304", "0.5076421", "0.50658053", "0.5061069", "0.5051656", "0.5050651", "0.5041692", "0.5035815", "0.5035303" ]
0.81351894
0
SetSchemaVersion gets a reference to the given string and assigns it to the SchemaVersion field.
func (o *SettingsObjectUpdate) SetSchemaVersion(v string) { o.SchemaVersion = &v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *SynchronizationSchema) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *AssetReportFreddieGetResponse) SetSchemaVersion(v float32) {\n\to.SchemaVersion = v\n}", "func (m *GroupPolicyDefinition) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ManagedAppPolicy) SetVersion(value *string)() {\n m.version = value\n}", "func (r *Document) SchemaVersion() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"schemaVersion\"])\n}", "func SetVersion(ver string) {\n\tversion = ver\n}", "func (db *JSONLite) SetSchema(id string, schema *jsonschema.RootSchema) error {\n\tif val, ok := db.schemas.load(id); ok && val == schema {\n\t\treturn nil\n\t}\n\n\tstmt, err := db.cursor.Prepare(\"INSERT OR REPLACE INTO \\\"_schemas\\\" (\\\"id\\\", \\\"schema\\\") VALUES (?, ?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tschemaData, err := json.Marshal(schema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb.sqlMutex.Lock()\n\t_, err = stmt.Exec(id, schemaData)\n\tdb.sqlMutex.Unlock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// db.schemas[id] = schema\n\tdb.schemas.store(id, schema)\n\treturn nil\n}", "func (m *Migrate) SetVersion(version uint64, description string) error {\n\trec := versionRecord{\n\t\tVersion: version,\n\t\tTimestamp: time.Now().UTC(),\n\t\tDescription: description,\n\t}\n\n\t_, err := m.db.Collection(m.migrationsCollection).InsertOne(context.TODO(), rec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetVersion(v string, os string, arch string, commit string, date string, goVersion string) {\n\tversion = data{\n\t\tversion: v,\n\t\tos: os,\n\t\tarch: arch,\n\t\tcommit: commit,\n\t\tdate: date,\n\t\tgoVersion: strings.ReplaceAll(goVersion, \"go\", \"\"),\n\t}\n}", "func (m *DeviceManagementConfigurationSettingDefinition) SetVersion(value *string)() {\n err := m.GetBackingStore().Set(\"version\", value)\n if err != nil {\n panic(err)\n }\n}", "func (m *ExternalConnection) SetSchema(value Schemaable)() {\n m.schema = value\n}", "func (o *AssetReportFreddieGetResponse) GetSchemaVersion() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.SchemaVersion\n}", "func (o *SettingsObjectUpdate) GetSchemaVersion() string {\n\tif o == nil || o.SchemaVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SchemaVersion\n}", "func (m *SynchronizationJob) SetSchema(value SynchronizationSchemaable)() {\n err := m.GetBackingStore().Set(\"schema\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *Server) SetVersion(newVersion uint32) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.version = newVersion\n}", "func (s *Server) SetVersion(ctx context.Context, in *pb.SetVersionRequest) (*pb.SetVersionResponse, error) {\n\ts.writeMutex.Lock()\n\tdefer s.writeMutex.Unlock()\n\n\tfound := false\n\tfor _, v := range s.versions {\n\t\tif v.GetKey() == in.GetSet().GetKey() {\n\t\t\tv.Value = in.GetSet().GetValue()\n\t\t\tv.Setter = in.GetSet().GetSetter()\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\ts.versions = append(s.versions, in.GetSet())\n\t}\n\n\terr := s.saveVersions()\n\tif err != nil {\n\t\ts.Log(fmt.Sprintf(\"Error writing: %v -> %v\", in, err))\n\t\treturn nil, err\n\t}\n\treturn &pb.SetVersionResponse{Response: in.GetSet()}, nil\n}", "func SetVersion(version string, commit string) {\n\tif version == \"\" {\n\t\tmainSemver = \"0.0.0\"\n\t} else {\n\t\tmainSemver = version\n\t}\n\tif commit == \"\" {\n\t\tmainCommit = \"0000\"\n\t} else {\n\t\tmainCommit = commit\n\t}\n}", "func (*XMLDocument) SetXMLVersion(xmlVersion string) {\n\tmacro.Rewrite(\"$_.xmlVersion = $1\", xmlVersion)\n}", "func (h *Header) SetVersion(version byte) {\n\th[1] = version\n}", "func (swagger *MgwSwagger) SetVersion(version string) {\n\tswagger.version = version\n}", "func (s *ImportHubContentInput) SetDocumentSchemaVersion(v string) *ImportHubContentInput {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (o SchemaOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Schema) pulumi.StringOutput { return v.Version }).(pulumi.StringOutput)\n}", "func (m *PrintConnector) SetAppVersion(value *string)() {\n err := m.GetBackingStore().Set(\"appVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *SchemaDefinitionRestDto) SetVersion(v string) {\n\to.Version = &v\n}", "func (requestHeader *RequestHeader) SetVersion(version uint16) {\n\t// if requestHeader.APIVersion == -1 {\n\t// \treturn\n\t// }\n\trequestHeader.APIVersion = version\n}", "func (s *HubContentInfo) SetDocumentSchemaVersion(v string) *HubContentInfo {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (h *Headers) SetVersion(version string) { h.version = version }", "func (m *msg) SetVersion(v byte) {\n\tm.LiVnMode = (m.LiVnMode & 0xc7) | v<<3\n}", "func (p *Parser) SetVersion(value interface{}) *Parser {\n\tvar setVersion bool\n\tvar versionFunc func() string\n\tif versionString, found := value.(string); found {\n\t\tif len(versionString) != 0 {\n\t\t\tsetVersion = true\n\t\t\tversionFunc = func() string {\n\t\t\t\treturn versionString\n\t\t\t}\n\t\t}\n\t} else if versionFunc, found = value.(func() string); found {\n\t\tsetVersion = true\n\t}\n\tif !setVersion {\n\t\texit(\"optparse: the SetVersion value needs to be a string or a function returning a string\")\n\t}\n\tp.version = versionFunc\n\tp.ParseVersion = true\n\treturn p\n}", "func (c *Current) SetVersion(version string) {\n\tswitch c.selectedRadio {\n\tcase FocusOnInvolved, FocusOnCurrentNamespace:\n\t\tif curr.resourceVersion < version {\n\t\t\tcurr.resourceVersion = version\n\t\t}\n\tcase FocusOnAllNamespace:\n\t\tif curr.resourceVersionAllNamespace < version {\n\t\t\tcurr.resourceVersionAllNamespace = version\n\t\t}\n\t}\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) SetVersion(opts *bind.TransactOpts, _version string) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"setVersion\", _version)\n}", "func (s *DescribeHubContentOutput) SetDocumentSchemaVersion(v string) *DescribeHubContentOutput {\n\ts.DocumentSchemaVersion = &v\n\treturn s\n}", "func (av *AppVersion) SetVersion(rw http.ResponseWriter, r *http.Request) {\n\tvar passwd, version, downloadURL string\n\n\tif len(r.URL.Query()[\"passwd\"]) > 0 {\n\t\tpasswd = r.URL.Query()[\"passwd\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get passwd\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"version\"]) > 0 {\n\t\tversion = r.URL.Query()[\"version\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get version\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"downloadurl\"]) > 0 {\n\t\tdownloadURL = r.URL.Query()[\"downloadurl\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get downloadurl\")\n\t\treturn\n\t}\n\t//fmt.Println(passwd, version, downloadURL)\n\n\tappVersion, _ := av.db.QueryAppVersion()\n\tif appVersion.ID == 0 {\n\t\tappVersion.Passwd = passwd\n\t\tappVersion.Version = version\n\t\tappVersion.DownloadURL = downloadURL\n\t\terr := av.db.InsertAppVerion(&appVersion)\n\t\tif err != nil {\n\t\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\t\treturn\n\t\t}\n\t\tutils.Respond(rw, true)\n\t\treturn\n\t} else if appVersion.Passwd != passwd {\n\t\tav.l.Printf(\"failed to set AppVersion : passwd wrong\")\n\t\treturn\n\t}\n\tappVersion.Version = version\n\tappVersion.DownloadURL = downloadURL\n\terr := av.db.UpdateAppVerion(&appVersion)\n\tif err != nil {\n\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\treturn\n\t}\n\n\tutils.Respond(rw, true)\n\treturn\n}", "func (db *DatabaseModel) SetSchema(schema *ovsdb.DatabaseSchema) []error {\n\tdb.mutex.Lock()\n\tdefer db.mutex.Unlock()\n\terrors := db.client.validate(schema)\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\tdb.schema = schema\n\tdb.mapper = mapper.NewMapper(schema)\n\terrs := db.generateModelInfo()\n\tif len(errs) > 0 {\n\t\tdb.schema = nil\n\t\tdb.mapper = nil\n\t\treturn errs\n\t}\n\treturn []error{}\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationStorageClassAnalysisDataExport) *string { return v.OutputSchemaVersion }).(pulumi.StringPtrOutput)\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportPtrOutput) OutputSchemaVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExport) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.OutputSchemaVersion\n\t}).(pulumi.StringPtrOutput)\n}", "func SetAddressVersion(name string) {\n\taddressVersion = MustVersionByName(name)\n\t//logger.Debug(\"Set address version to %s\", name)\n}", "func (info *Metadata) SetVersion(version int32) {\n\tinfo.version = version\n}", "func (rr *OPT) SetVersion(v uint8) {\n\trr.Hdr.Ttl = rr.Hdr.Ttl&0xFF00FFFF | uint32(v)<<16\n}", "func (_options *GetConfigOptions) SetVersion(version string) *GetConfigOptions {\n\t_options.Version = core.StringPtr(version)\n\treturn _options\n}", "func (obj *Edge) SetVersion(version int) {\n\tobj.setVersion(version)\n}", "func (b *Builder) SetVersion(v uint32) *Builder {\n\tb.blk.Header.version = v\n\treturn b\n}", "func (f *FacebookRequestResponse) SetVersion(v string) *FacebookRequestResponse {\n\tif f.Fields == nil {\n\t\tf.Fields = &FacebookFields{}\n\t}\n\tf.Fields.Version = v\n\treturn f\n}", "func (o *GetClientConfigV1ConfigByNameParams) SetVersion(version *string) {\n\to.Version = version\n}", "func (s *TsvVersionOptions) SetSchema(v []map[string]*string) *TsvVersionOptions {\n\ts.Schema = v\n\treturn s\n}", "func (v *Version) Set(s string) error {\n\tw, err := Parse(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = w\n\n\treturn nil\n}", "func (f *FacebookMessage) SetVersion(v string) *FacebookMessage {\n\tif f.Fields == nil {\n\t\tf.Fields = &FacebookFields{}\n\t}\n\tf.Fields.Version = v\n\treturn f\n}", "func (m *WorkforceIntegration) SetApiVersion(value *int32)() {\n m.apiVersion = value\n}", "func (ac *AppCreate) SetVersion(s string) *AppCreate {\n\tac.mutation.SetVersion(s)\n\treturn ac\n}", "func (m *WebPartData) SetDataVersion(value *string)() {\n err := m.GetBackingStore().Set(\"dataVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (u *uuid) setVersion(v byte) {\n\tu[6] = (u[6] & 0x0f) | (v << 4)\n}", "func (m *AndroidLobApp) SetVersionName(value *string)() {\n err := m.GetBackingStore().Set(\"versionName\", value)\n if err != nil {\n panic(err)\n }\n}", "func (a *Action) SetVersion(version interface{}) { a.version = version }", "func setVersion(u *UUID, v byte) {\n\tu[6] = u[6]&0x0f | v<<4\n}", "func checkSchemaVersion(version string) error {\n\t// First get the major version number from the schema. The schema version string should be in the format\n\t// \"major.minor.patch\", \"major.minor\", or \"major\".\n\n\tparts := strings.Split(version, \".\")\n\tif len(parts) == 0 {\n\t\treturn fmt.Errorf(\"error splitting schema version %q into parts\", version)\n\t}\n\n\tmajorVersion, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting major version component %q to an integer: %v\", parts[0], err)\n\t}\n\n\t// Find the latest supported version for the major version and use that to determine if the provided version is\n\t// supported.\n\tsupportedVersion, ok := supportedSchemaVersions[majorVersion]\n\tif !ok {\n\t\treturn fmt.Errorf(\"major version %d not supported\", majorVersion)\n\t}\n\tif mtest.CompareServerVersions(supportedVersion, version) < 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"latest version supported for major version %d is %q, which is incompatible with specified version %q\",\n\t\t\tmajorVersion, supportedVersion, version,\n\t\t)\n\t}\n\treturn nil\n}", "func (m *ZebraFotaArtifact) SetPatchVersion(value *string)() {\n err := m.GetBackingStore().Set(\"patchVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (st *Store) schemaVersion() (int, error) {\n\tvar n string\n\terr := st.db.QueryRow(`SELECT name FROM sqlite_master WHERE type='table' AND name='version';`).Scan(&n)\n\tif err == sql.ErrNoRows {\n\t\treturn 0, nil // assume db is blank\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar v int\n\terr = st.db.QueryRow(`SELECT MAX(ver) FROM version`).Scan(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn v, nil\n}", "func (o Chapter) SetAPIVersion(s string) error {\n\terr := o.hugo.addContent(o.part.name, o.name, markdown.Code(\"apiVersion: \"+s))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error adding GV for chapter %s/%s: %s\", o.part.name, o.name, err)\n\t}\n\treturn nil\n}", "func (options *CreateSharedDatasetOptions) SetVersion(version string) *CreateSharedDatasetOptions {\n\toptions.Version = core.StringPtr(version)\n\treturn options\n}", "func SetAppVersion(appVersion string) int {\n\tcAppVersion := goToCString(appVersion)\n\tstatus := C.SetAppVersion(cAppVersion)\n\tfreeCString(cAppVersion)\n\treturn int(status)\n}", "func (s *Semver) set(ver string) error {\n\tsv, err := semverlib.NewVersion(ver)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Version = sv\n\treturn nil\n}", "func (a *Client) DeleteSchemaVersion(params *DeleteSchemaVersionParams) (*DeleteSchemaVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteSchemaVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteSchemaVersion\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteSchemaVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*DeleteSchemaVersionOK), nil\n\n}", "func (p *EtcdClientV3) SetVersion(version *PersistentStateVersion) error {\n\tversionJSON, err := json.Marshal(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.Set(config.StoreURL, string(versionJSON))\n}", "func (o *ConnectorTypeAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (o *ConnectorTypeAllOf) SetVersion(v string) {\n\to.Version = &v\n}", "func (mi *MeshInfo) SetVersion(v *string) {\n\tmi.version = v\n}", "func (m *DeviceHealthAttestationState) SetContentVersion(value *string)() {\n err := m.GetBackingStore().Set(\"contentVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (o *LoraNetworkTrigger) SetVersion(v int32) {\n\to.Version = v\n}", "func (st *State) SetVersion(tag string, v version.Binary) error {\n\tvar results params.ErrorResults\n\targs := params.EntitiesVersion{\n\t\tAgentTools: []params.EntityVersion{{\n\t\t\tTag: tag,\n\t\t\tTools: &params.Version{v},\n\t\t}},\n\t}\n\terr := st.call(\"SetTools\", args, &results)\n\tif err != nil {\n\t\t// TODO: Not directly tested\n\t\treturn err\n\t}\n\treturn results.OneError()\n}", "func (b *ClusterUpgradeBuilder) Version(value string) *ClusterUpgradeBuilder {\n\tb.version = value\n\tb.bitmap_ |= 8\n\treturn b\n}", "func (b *ChaincodeDataBuilder) Version(value string) *ChaincodeDataBuilder {\n\tb.version = value\n\treturn b\n}", "func (o VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRefOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesPropertiesValueFromFieldRef) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)\n}", "func (r *GraphRequest) SetVersion(v GraphAPIVersion) *GraphRequest {\n\tr.Version = v\n\treturn r\n}", "func (un *Decoder) SetSchema(e *yang.Entry) { un.schema = e }", "func (options *ReplaceSharedDatasetOptions) SetVersion(version string) *ReplaceSharedDatasetOptions {\n\toptions.Version = core.StringPtr(version)\n\treturn options\n}", "func (o *Content) SetPyVersion(v string) {\n\to.PyVersion.Set(&v)\n}", "func (scl *SimpleConfigurationLayer) SetVersion(version *string) {\n\tscl.Version = version\n}", "func (s *TsvStoreOptions) SetSchema(v []map[string]*string) *TsvStoreOptions {\n\ts.Schema = v\n\treturn s\n}", "func SetVersion(version string) func(*AviSession) error {\n\treturn func(sess *AviSession) error {\n\t\treturn sess.setVersion(version)\n\t}\n}", "func (o *UpdateMetricRulesetRequest) SetVersion(v int64) {\n\to.Version = &v\n}", "func SetOSVersion(v string) { osVersionAtomic.Store(v) }", "func SetVersion(version string) {\n\trootCmd.Cmd.Version = version\n}", "func (_options *CheckConfigOptions) SetVersion(version string) *CheckConfigOptions {\n\t_options.Version = core.StringPtr(version)\n\treturn _options\n}", "func (s *ServerConfig) SchemaVersioningEndpoint(path string) string {\n\t// if s.Port == \"80\" {\n\t// \treturn s.URISchema + s.Host + \"/\" + s.ApiVer + path\n\t// }\n\treturn s.URISchema + s.Host + \":\" + s.Port + \"/api/\" + s.ApiVer + path\n}", "func (m *AppVulnerabilityTask) SetAppVersion(value *string)() {\n err := m.GetBackingStore().Set(\"appVersion\", value)\n if err != nil {\n panic(err)\n }\n}", "func (opt *optionalAttributes) SetVersion(version int) *Builder {\n\topt.Builder.optional.VersionIndex = version\n\treturn opt.Builder\n}", "func (d *Deej) SetVersion(version string) {\n\td.version = version\n}", "func (o *GetProductUpgradeURLUsingGETParams) SetVersion(version string) {\n\to.Version = version\n}", "func (o *GetInstancesDocsParams) SetVersion(version *string) {\n\to.Version = version\n}", "func (a *Client) DeleteSchemaVersion(params *DeleteSchemaVersionParams) (*DeleteSchemaVersionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteSchemaVersionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteSchemaVersion\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/subjects/{subject}/versions/{version}\",\n\t\tProducesMediaTypes: []string{\"application/json; qs=0.5\", \"application/vnd.schemaregistry+json; qs=0.9\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\", \"application/vnd.schemaregistry+json\", \"application/vnd.schemaregistry.v1+json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteSchemaVersionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*DeleteSchemaVersionOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for deleteSchemaVersion: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o VirtualDatabaseSpecEnvValueFromFieldRefOutput) ApiVersion() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecEnvValueFromFieldRef) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)\n}", "func UpdateSchema(schemaRef *SchemaReference, crd *apiextensions.CustomResourceDefinition) error {\n\tgvk := schema.GroupVersionKind{\n\t\tGroup: crd.Spec.Group,\n\t\tVersion: GetVersionFromCRD(crd),\n\t\tKind: crd.Spec.Names.Kind,\n\t}\n\tif schemaRef.GVK.String() != gvk.String() {\n\t\treturn fmt.Errorf(\"unexpected mismatch of GVK when updating schema reference for controller, old GVK = %s, new GVK = %s\", schemaRef.GVK.String(), gvk.String())\n\t}\n\tschemaRef.CRD = crd\n\tschemaRef.JsonSchema = GetOpenAPIV3SchemaFromCRD(crd)\n\treturn nil\n}", "func (s *UpdateTableInput) SetSchema(v *Schema) *UpdateTableInput {\n\ts.Schema = v\n\treturn s\n}", "func (m *GoMod) SetVersion(v string) error {\n\treturn nil\n}", "func (m *GroupPolicyDefinition) SetNextVersionDefinition(value GroupPolicyDefinitionable)() {\n err := m.GetBackingStore().Set(\"nextVersionDefinition\", value)\n if err != nil {\n panic(err)\n }\n}", "func (duo *DatumUpdateOne) SetVersion(i int) *DatumUpdateOne {\n\tduo.mutation.ResetVersion()\n\tduo.mutation.SetVersion(i)\n\treturn duo\n}", "func (du *DatumUpdate) SetVersion(i int) *DatumUpdate {\n\tdu.mutation.ResetVersion()\n\tdu.mutation.SetVersion(i)\n\treturn du\n}", "func (s *Connector) SetVersion(v string) *Connector {\n\ts.Version = &v\n\treturn s\n}", "func (self PostgresDatabase) setDBVersion(version int) (err error) {\n log.Println(\"set db version to\", version)\n _, err = self.conn.Exec(\"DELETE FROM Settings WHERE name = $1\", \"version\")\n _, err = self.conn.Exec(\"INSERT INTO Settings(name, value) VALUES($1, $2)\", \"version\", fmt.Sprintf(\"%d\", version))\n return\n}", "func (o *ZoneZone) SetVersion(v string) {\n\to.Version = &v\n}" ]
[ "0.7258049", "0.67544603", "0.6164254", "0.60584635", "0.604924", "0.58285844", "0.5774919", "0.5750832", "0.5713876", "0.5650169", "0.56149197", "0.56068105", "0.559664", "0.5581648", "0.55700785", "0.55613685", "0.5514811", "0.5513074", "0.54861796", "0.54815876", "0.547275", "0.5449919", "0.54478455", "0.5434436", "0.541509", "0.541488", "0.5408184", "0.540128", "0.5387772", "0.53795135", "0.53749865", "0.53662664", "0.53592753", "0.53558964", "0.5260168", "0.52576935", "0.52346474", "0.5224656", "0.52062285", "0.5188916", "0.5177288", "0.5155967", "0.51419187", "0.51378053", "0.51368874", "0.51237166", "0.5116078", "0.5107563", "0.5093944", "0.50818133", "0.5064953", "0.50571626", "0.5048496", "0.5046149", "0.50367284", "0.50216806", "0.50151116", "0.4993145", "0.49707302", "0.49665922", "0.49653417", "0.49536538", "0.49513796", "0.49459258", "0.49459258", "0.4940354", "0.49398068", "0.49306598", "0.49025625", "0.48956913", "0.48944953", "0.48809162", "0.48797062", "0.4864173", "0.4859668", "0.4843343", "0.48387557", "0.48319274", "0.48221666", "0.48183784", "0.48154286", "0.48123574", "0.47994778", "0.47973096", "0.47793254", "0.47774336", "0.47752395", "0.47748822", "0.47730455", "0.4769862", "0.47608018", "0.4755088", "0.47527716", "0.47503576", "0.47422022", "0.47266823", "0.47255734", "0.47244573", "0.4724036", "0.47150293" ]
0.68126214
1
GetUpdateToken returns the UpdateToken field value if set, zero value otherwise.
func (o *SettingsObjectUpdate) GetUpdateToken() string { if o == nil || o.UpdateToken == nil { var ret string return ret } return *o.UpdateToken }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *SettingsObjectUpdate) GetUpdateTokenOk() (*string, bool) {\n\tif o == nil || o.UpdateToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdateToken, true\n}", "func (o *SettingsObjectUpdate) SetUpdateToken(v string) {\n\to.UpdateToken = &v\n}", "func (o *SettingsObjectUpdate) HasUpdateToken() bool {\n\tif o != nil && o.UpdateToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o LookupFirewallPolicyResultOutput) UpdateToken() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.UpdateToken }).(pulumi.StringOutput)\n}", "func (a *ADMResponse) UpdateToken() bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\tif a.Error == ErrRemoveToken || a.Error == ErrUpdateToken {\n\t\treturn true\n\t}\n\treturn false\n}", "func (res *GrantTypeInfoResponse) SetTokenUpdate(tokenUpdate *my.MytokenResponse) {\n\tres.TokenUpdate = tokenUpdate\n}", "func (t *Token) Update() {\n\tatomic.StoreInt64(&t.unix, time.Now().Unix())\n}", "func (o *ResourceVersion) GetUpdateTs() int64 {\n\tif o == nil || o.UpdateTs == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.UpdateTs\n}", "func (controller *Controller) CheckPasswordResetToken(tokenStr string, c web.C) (models.UserToken, *models.PasswordReset, bool) {\n\tsession := controller.GetSession(c)\n\tdbMap := controller.GetDbMap(c)\n\n\tvar token models.UserToken\n\n\t// Check that the token is set.\n\tif tokenStr == \"\" {\n\t\tsession.AddFlash(\"No password update token present.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is valid.\n\tvar err error\n\ttoken, err = models.UserTokenFromStr(tokenStr)\n\tif err != nil {\n\t\tsession.AddFlash(\"Email verification token not valid.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is recognized.\n\tpasswordReset, err := helpers.PasswordResetTokenExists(dbMap, token)\n\tif err != nil {\n\t\tlog.Debugf(`Password update token \"%v\" not found in DB: %v`, token, err)\n\t\tsession.AddFlash(\"Password update token not recognized.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is not expired.\n\texpTime := time.Unix(passwordReset.Expires, 0)\n\tif expTime.Before(time.Now()) {\n\t\tsession.AddFlash(\"Password update token has expired.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, passwordReset, false\n\t}\n\n\treturn token, passwordReset, true\n}", "func (transaction *TokenUpdateTransaction) GetTokenID() TokenID {\n\tif transaction.tokenID == nil {\n\t\treturn TokenID{}\n\t}\n\n\treturn *transaction.tokenID\n}", "func CheckAndUpdateToken(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttoken := r.Header.Get(tokenHeaderName)\n\t\tif token == \"\" {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tti, err := controller.Token.GetInfo(token)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tcontroller.Token.UpdateTTL(ti)\n\t\tctx := r.Context()\n\t\tctx = context.WithValue(ctx, LoginKey, ti.Login)\n\t\thandler.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (u *UpdateShort) GetUpdate() (value UpdateClass) {\n\tif u == nil {\n\t\treturn\n\t}\n\treturn u.Update\n}", "func (is *BareMetalService) UpdateToken() error {\n\ttoken := is.provider.Token()\n\tresult, err := tokens.Validate(is.identityClient, token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Validate token err: %v\", err)\n\t}\n\tif result {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"Token is out of date, getting new token.\")\n\treAuthFunction := is.provider.ReauthFunc\n\tif reAuthFunction() != nil {\n\t\treturn fmt.Errorf(\"reAuth err: %v\", err)\n\t}\n\treturn nil\n}", "func UpdateToken(oldToken, secret string) (string, time.Time, error) {\n\toldTokParsed, err := jwt.Parse(oldToken, func(t *jwt.Token) (interface{}, error) {\n\t\tif _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected token signing: %v\", t.Header[\"alg\"])\n\t\t}\n\n\t\treturn []byte(secret), nil\n\t})\n\n\tif err != nil {\n\t\treturn \"\", time.Time{}, err\n\t}\n\n\toldClaimg, ok := oldTokParsed.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\treturn \"\", time.Time{}, fmt.Errorf(\"Error during updating token\")\n\t}\n\n\tusername, ok := oldClaimg[\"username\"].(string)\n\tif !ok {\n\t\treturn \"\", time.Time{}, fmt.Errorf(\"Can't extract one or more claims fields\")\n\t}\n\n\treturn CreateToken(username, secret)\n\n}", "func (o *CreateUser200Response) GetRefreshToken() string {\n\tif o == nil || IsNil(o.RefreshToken) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.RefreshToken\n}", "func (s *SessHelper) UpdateToken(appid, uuid, token string, expireMS int) error {\n\treturn nil\n}", "func (o *GenerateTokenResponse) GetRefreshToken() string {\n\tif o == nil || o.RefreshToken == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.RefreshToken\n}", "func (t *TemplateInvokeNode) GetToken() *token.Token {\n\treturn t.Token\n}", "func (transaction *TokenUpdateTransaction) GetTokenName() string {\n\treturn transaction.tokenName\n}", "func (l *RemoteProvider) UpdateToken(w http.ResponseWriter, r *http.Request) string {\n\tl.TokenStoreMut.Lock()\n\tdefer l.TokenStoreMut.Unlock()\n\n\ttokenString, _ := l.GetToken(r)\n\tnewts := l.TokenStore[tokenString]\n\tif newts != \"\" {\n\t\tlogrus.Debugf(\"set updated token: %v\", newts)\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: tokenName,\n\t\t\tValue: newts,\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t})\n\t\treturn newts\n\t}\n\n\treturn tokenString\n}", "func (m *TokenMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (c CommitterProbe) GetForUpdateTS() uint64 {\n\treturn c.forUpdateTS\n}", "func (o *SparseSSHAuthorizationPolicy) GetUpdateTime() (out time.Time) {\n\n\tif o.UpdateTime == nil {\n\t\treturn\n\t}\n\n\treturn *o.UpdateTime\n}", "func (token *Token) Update(db *sqlx.DB) {\n\t\n\tif strings.TrimSpace(token.AccessToken) == \"\" || strings.TrimSpace(token.RefreshToken) == \"\" || token.RefreshTokenExpiry == 0 || token.AccessTokenExpiry == 0 || strings.TrimSpace(token.DeviceID) == \"\" || strings.TrimSpace(token.MacAddress) == \"\" || strings.TrimSpace(token.APIKey) == \"\" || token.Status == 0{\n\t\tfmt.Println(\"Missing Fields from tokens\")\n\t\treturn\n\t}\n\t\n\tif strings.TrimSpace(token.ID) == \"\" {\n\t\tfmt.Println(\"Empty ID\")\n\t\treturn\n\t}\n\n\tsql := \"UPDATE tokens SET access_token=?,access_token_time=?,access_token_expiry=?,user_id=?,status=?,api_key=?,refresh_token=?,refresh_token_time=?,refresh_token_expiry=?,device_id=?,mac_address=? WHERE id='\" + token.ID + \"'\"\n\n\t_, err := db.Exec(sql,\n\t\ttoken.AccessToken,\n\t\ttoken.AccessTokenTime,\n\t\ttoken.AccessTokenExpiry,\n\t\ttoken.UserID,\n\t\ttoken.Status,\n\t\ttoken.APIKey,\n\t\ttoken.RefreshToken,\n\t\ttoken.RefreshTokenTime,\n\t\ttoken.RefreshTokenExpiry,\n\t\ttoken.DeviceID,\n\t\ttoken.MacAddress,\n\t)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (a *api) GetRefreshToken() (string, error) {\n\tif !a.checkRefreshToken() {\n\t\treturn \"\", ERR_NOREFRESHTOKEN\n\t}\n\treturn a.refreshToken, nil\n}", "func (o *OAuth2ConsentSessionExpiresAt) GetRefreshToken() time.Time {\n\tif o == nil || o.RefreshToken == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.RefreshToken\n}", "func (m *SDSConfig) GetToken() *types.Struct {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (at *AuthtokenToken) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !at._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif at._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE public.authtoken_token SET (` +\n\t\t`created, user_id` +\n\t\t`) = ( ` +\n\t\t`$1, $2` +\n\t\t`) WHERE key = $3`\n\n\t// run query\n\tXOLog(sqlstr, at.Created, at.UserID, at.Key)\n\t_, err = db.Exec(sqlstr, at.Created, at.UserID, at.Key)\n\treturn err\n}", "func (t *ServiceAccountToken) Update() error {\n\ttok, err := t.updateFn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the stored token.\n\tt.mtx.Lock()\n\tdefer t.mtx.Unlock()\n\tt.tok = tok\n\tsklog.Infof(\"Updated token: %s\", tok.AccessToken[len(tok.AccessToken)-8:])\n\treturn nil\n}", "func (t *ServiceAccountToken) Get() (*oauth2.Token, error) {\n\tt.mtx.RLock()\n\tdefer t.mtx.RUnlock()\n\treturn t.tok, nil\n}", "func (c *Client) GetToken() (string, error) {\n\t// Check if it has a refresh token.\n\tif c.RefreshToken == \"\" {\n\t\treturn \"\", microerror.Maskf(invalidConfigError, \"No refresh token saved in config file, unable to acquire new access token. Please login again.\")\n\t}\n\n\tif isTokenExpired(c.AccessToken) {\n\t\t// Get a new token.\n\t\trefreshTokenResponse, err := oidc.RefreshToken(c.RefreshToken)\n\t\tif err != nil {\n\t\t\treturn \"\", microerror.Mask(err)\n\t\t}\n\n\t\t// Parse the ID Token for the email address.\n\t\tidToken, err := oidc.ParseIDToken(refreshTokenResponse.IDToken)\n\t\tif err != nil {\n\t\t\treturn \"\", microerror.Mask(err)\n\t\t}\n\n\t\t// Update the config file with the new access token.\n\t\tc.IDToken = idToken\n\t\tc.AccessToken = refreshTokenResponse.AccessToken\n\n\t\tfmt.Println(\"DEBUG: Access token has just been refreshed.\")\n\t}\n\n\treturn c.AccessToken, nil\n}", "func (i *InstallationToken) GetToken() string {\n\tif i == nil || i.Token == nil {\n\t\treturn \"\"\n\t}\n\treturn *i.Token\n}", "func (m *SessionMutation) Token() (r string, exists bool) {\n\tv := m.token\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (i *InternalTokenHelper) Get() (string, error) {\n\ti.populateTokenPath()\n\tf, err := os.Open(i.tokenPath)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", nil\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, f); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.TrimSpace(buf.String()), nil\n}", "func (o *SparseSSHAuthorizationPolicy) GetUpdateIdempotencyKey() (out string) {\n\n\tif o.UpdateIdempotencyKey == nil {\n\t\treturn\n\t}\n\n\treturn *o.UpdateIdempotencyKey\n}", "func (ap *Provider) updateToken(client clients.AzureClient, token *v3.Token) error {\n\t// For the new flow via Microsoft Graph, the caching and updating of the token to the Microsoft Graph API\n\t// is handled separately via the SDK client cache.\n\tcfg, err := ap.GetAzureConfigK8s()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !IsConfigDeprecated(cfg) {\n\t\treturn nil\n\t}\n\n\tcurrent, err := client.MarshalTokenJSON()\n\tif err != nil {\n\t\treturn errors.New(\"failed to unmarshal token\")\n\t}\n\n\tsecret, err := ap.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{token})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// providerToken doesn't exist as a secret, update on token.\n\t\t\tif current, ok := token.ProviderInfo[\"access_token\"]; ok && current != current {\n\t\t\t\ttoken.ProviderInfo[\"access_token\"] = current\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif current == secret {\n\t\treturn nil\n\t}\n\n\treturn ap.tokenMGR.UpdateSecret(token.UserID, token.AuthProvider, current)\n}", "func (o *ZoneZone) GetUpdated() time.Time {\n\tif o == nil || o.Updated == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.Updated\n}", "func (o *GenerateTokenResponse) GetRefreshTokenOk() (*string, bool) {\n\tif o == nil || o.RefreshToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (o *UpdatePasswordReqWeb) GetTokenId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.TokenId\n}", "func (o *LocalDatabaseProvider) GetUpdated() time.Time {\n\tif o == nil || o.Updated == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.Updated\n}", "func GetToken() string {\n\treturn tokenString\n}", "func (l *Login) GetToken() string {\n\t// return zero value if Login type or Token field is nil\n\tif l == nil || l.Token == nil {\n\t\treturn \"\"\n\t}\n\n\treturn *l.Token\n}", "func (l *Login) GetToken() string {\n\t// return zero value if Login type or Token field is nil\n\tif l == nil || l.Token == nil {\n\t\treturn \"\"\n\t}\n\n\treturn *l.Token\n}", "func (c *Client) GetRefreshToken() string {\n\treturn c.refreshToken\n}", "func (m *DataTypeProgressMarker) GetTimestampTokenForMigration() int64 {\n\tif m != nil && m.TimestampTokenForMigration != nil {\n\t\treturn *m.TimestampTokenForMigration\n\t}\n\treturn 0\n}", "func (o *ResourceVersion) GetUpdateTsOk() (*int64, bool) {\n\tif o == nil || o.UpdateTs == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdateTs, true\n}", "func (s *Session) Token() SessionToken {\n\tif time.Now().Sub(s.lastUpdated) > refreshTime {\n\t\ts.updateToken()\n\t}\n\treturn s.token\n}", "func (m *UserMutation) UpdateTime() (r time.Time, exists bool) {\n\tv := m.update_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *UserMutation) UpdateTime() (r time.Time, exists bool) {\n\tv := m.update_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (transaction *TokenUpdateTransaction) GetRegenerateTransactionID() bool {\n\treturn transaction.Transaction.GetRegenerateTransactionID()\n}", "func (m *VppToken) GetToken()(*string) {\n return m.token\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (m *ChannelEdge) GetLastUpdate() uint32 {\n\tif m != nil {\n\t\treturn m.LastUpdate\n\t}\n\treturn 0\n}", "func (p *CassandraDataCentersClientCreateUpdatePoller) ResumeToken() (string, error) {\n\treturn p.pt.ResumeToken()\n}", "func (c *Client) GetRefreshToken() string {\n\treturn c.client.RefreshToken\n}", "func (m *VppToken) GetAutomaticallyUpdateApps()(*bool) {\n return m.automaticallyUpdateApps\n}", "func (cfg Config) GetToken() (token string) {\n\treturn cfg.Token\n}", "func (u *User) GetRefreshToken() (map[string]interface{}, error) {\n\tlog.info(\"========== GET REFRESH TOKEN ==========\")\n\turl := buildURL(path[\"users\"], u.UserID)\n\n\tres, err := u.do(\"GET\", url, \"\", nil)\n\n\tif res[\"refresh_token\"] != nil {\n\t\tu.RefreshToken = res[\"refresh_token\"].(string)\n\t}\n\n\treturn res, err\n}", "func (m *SDSConfig) GetToken() map[string]interface{} {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (m *SDSConfig) GetToken() map[string]interface{} {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (m *SDSConfig) GetToken() map[string]interface{} {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (m *SDSConfig) GetToken() map[string]interface{} {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (m *SDSConfig) GetToken() map[string]interface{} {\n\tif m != nil {\n\t\treturn m.Token\n\t}\n\treturn nil\n}", "func (c *Context) GetUpdater() (*Updater) {\n\tmutableMutex.Lock()\n mutableMutex.Unlock()\n\treturn c.Updater\n}", "func (settings Settings) GetToken() auth.Token {\n\treturn settings.Token\n}", "func (a *ActionNode) GetToken() *token.Token {\n\treturn a.Token\n}", "func (m *FileMutation) UpdateTime() (r time.Time, exists bool) {\n\tv := m.update_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (s *service) GetToken() string {\n\treturn s.token\n}", "func (m *SystemMutation) UpdateTime() (r time.Time, exists bool) {\n\tv := m.update_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (p *CassandraDataCentersCreateUpdatePoller) ResumeToken() (string, error) {\n\treturn p.pt.ResumeToken()\n}", "func GetToken() string {\n\treturn viper.GetString(\"auth.token\")\n}", "func (c VaultConfig) GetToken() string {\n\treturn c.Token\n}", "func (o *UpdatePasswordReqWeb) GetTokenIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.TokenId, true\n}", "func (o *CreateUser200Response) GetRefreshTokenOk() (*string, bool) {\n\tif o == nil || IsNil(o.RefreshToken) {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (s *StatsGraphAsync) GetToken() (value string) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Token\n}", "func GetRefreshToken(w http.ResponseWriter, r *http.Request) {\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tlog.Println(\"POST /refreshtoken\")\n\n\t\ttype inRefreshToken struct {\n\t\t\tRefreshToken string\n\t\t}\n\n\t\tvar rt inRefreshToken\n\t\terr := json.NewDecoder(r.Body).Decode(&rt)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tAuthorization := r.Header.Get(\"Authorization\")\n\t\t_, cUser := IsLegalUserByRefreshToken(Authorization)\n\n\t\tapiTokenResponse, _ := json.Marshal(APITokenResponse(cUser))\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, string(apiTokenResponse))\n\n\tdefault:\n\t\tfmt.Fprintf(w, \"Sorry, only POST method are supported.\")\n\t}\n}", "func (o *PostRestoreKVResponse) GetToken() string {\n\tif o == nil || o.Token == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Token\n}", "func (o *JsonMDNOAuthToken) GetToken() string {\n\tif o == nil || o.Token == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Token\n}", "func NewTokenUpdateTransaction() *TokenUpdateTransaction {\n\ttransaction := TokenUpdateTransaction{\n\t\tTransaction: _NewTransaction(),\n\t}\n\ttransaction._SetDefaultMaxTransactionFee(NewHbar(30))\n\n\treturn &transaction\n}", "func (j *JWT) GetVerifiedRefreshToken(bearerToken string) (*jwt.Token, error) {\n\ttoken := j.ExtractToken(bearerToken)\n\n\tverifiedToken, err := j.VerifyToken(token, os.Getenv(\"JWT_REFRESH_TOKEN_SECRET\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn verifiedToken, nil\n}", "func (m *DeviceHealthAttestationState) GetLastUpdateDateTime()(*string) {\n val, err := m.GetBackingStore().Get(\"lastUpdateDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (t *ACLRole) GetUpdatedAt() int64 {\n\tif t.UpdatedAt == nil {\n\t\treturn int64(0)\n\t}\n\treturn *t.UpdatedAt\n}", "func (handler *AuthHandler) UpdateToken(c *gin.Context) {\n\tif c.Request.URL.Path == \"/login\" || c.Request.URL.Path == \"/auth/callback\" {\n\t\tc.Next()\n\t}\n\n\trawTokenCookie, err := c.Request.Cookie(\"token\")\n\tif err != nil {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login\")\n\t\treturn\n\t}\n\n\ttoken := decodeToken(rawTokenCookie, c)\n\n\ttokensource := handler.Oauth2Conf.TokenSource(context.TODO(), token)\n\tupdatedToken, err := tokensource.Token()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login\")\n\t\tc.Abort()\n\t}\n\n\tupdatedRawToken, err := json.Marshal(updatedToken)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/index\")\n\t\tc.AbortWithError(400, err)\n\t}\n\n\trawTokenCookie.Value = string(updatedRawToken)\n\n\tc.Next()\n}", "func (o *LoginRequestResponseData) GetOtpToken() string {\n\tif o == nil || o.OtpToken == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.OtpToken\n}", "func (m *PlayerMutation) UpdateTime() (r time.Time, exists bool) {\n\tv := m.update_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (p *PullRequest) GetUpdatedAt() time.Time {\n\tif p == nil || p.UpdatedAt == nil {\n\t\treturn time.Time{}\n\t}\n\treturn *p.UpdatedAt\n}", "func (m *SecurityActionState) GetUpdatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"updatedDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (u *BasicUpdateOperation) SetToken(token string) {\n\tu.Token = token\n}", "func (a API) GetToken() (t string) {\r\n\treturn a.access_token\r\n}", "func (a *Authorization) GetTokenLastEight() string {\n\tif a == nil || a.TokenLastEight == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.TokenLastEight\n}", "func (r *MockRepoManager) getUpdateCount() int {\n\tr.mtx.RLock()\n\tdefer r.mtx.RUnlock()\n\treturn r.updateCount\n}", "func (o *SparseCloudSnapshotAccount) GetUpdateIdempotencyKey() (out string) {\n\n\tif o.UpdateIdempotencyKey == nil {\n\t\treturn\n\t}\n\n\treturn *o.UpdateIdempotencyKey\n}", "func (o *OAuth2ConsentSessionExpiresAt) GetRefreshTokenOk() (*time.Time, bool) {\n\tif o == nil || o.RefreshToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (o *SSHAuthorizationPolicy) GetUpdateIdempotencyKey() string {\n\n\treturn o.UpdateIdempotencyKey\n}", "func (o *Service) GetUpdatedAt() float32 {\n\tif o == nil || o.UpdatedAt == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\treturn *o.UpdatedAt\n}", "func (o *VulnUpdateNotification) GetLastUpdated() int32 {\n\tif o == nil || o.LastUpdated == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.LastUpdated\n}" ]
[ "0.67794496", "0.65891665", "0.6288857", "0.5704722", "0.5688703", "0.54490256", "0.53145146", "0.5304526", "0.5208533", "0.5138567", "0.5132322", "0.51196456", "0.5105571", "0.50356674", "0.49462926", "0.49462596", "0.49347934", "0.4928249", "0.49023333", "0.4882087", "0.48447207", "0.4829452", "0.48265108", "0.48235965", "0.47900507", "0.47871202", "0.47723413", "0.47604272", "0.4756404", "0.47393054", "0.47365674", "0.4696068", "0.4690883", "0.46894062", "0.46634075", "0.46544152", "0.46490684", "0.4643105", "0.46347684", "0.46323755", "0.46317402", "0.46283048", "0.46283048", "0.46152776", "0.46074578", "0.46000698", "0.45715076", "0.45559832", "0.45559832", "0.4542884", "0.45426127", "0.45414355", "0.45414355", "0.45414355", "0.45414355", "0.45414355", "0.45414355", "0.45398945", "0.45281905", "0.45260918", "0.45210084", "0.45166525", "0.45159668", "0.45159668", "0.45159668", "0.45159668", "0.45159668", "0.45048353", "0.44988078", "0.44906014", "0.4485197", "0.44821742", "0.4476061", "0.44738334", "0.4472694", "0.44706088", "0.4470345", "0.44553497", "0.44541323", "0.44520563", "0.4445215", "0.44358587", "0.44358534", "0.4430922", "0.4429471", "0.44253463", "0.44188654", "0.44128054", "0.44127205", "0.44112375", "0.44018567", "0.43969074", "0.43869755", "0.43837047", "0.43791342", "0.43768713", "0.4372899", "0.43632174", "0.43560624", "0.43541402" ]
0.7997217
0
GetUpdateTokenOk returns a tuple with the UpdateToken field value if set, nil otherwise and a boolean to check if the value has been set.
func (o *SettingsObjectUpdate) GetUpdateTokenOk() (*string, bool) { if o == nil || o.UpdateToken == nil { return nil, false } return o.UpdateToken, true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *SettingsObjectUpdate) HasUpdateToken() bool {\n\tif o != nil && o.UpdateToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SettingsObjectUpdate) GetUpdateToken() string {\n\tif o == nil || o.UpdateToken == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.UpdateToken\n}", "func (a *ADMResponse) UpdateToken() bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\tif a.Error == ErrRemoveToken || a.Error == ErrUpdateToken {\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *Venda) GetTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Token.Get(), o.Token.IsSet()\n}", "func (o *UpdatePasswordReqWeb) GetTokenIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.TokenId, true\n}", "func (o *Token) GetTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Token, true\n}", "func (o *JsonMDNOAuthToken) GetTokenOk() (*string, bool) {\n\tif o == nil || o.Token == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Token, true\n}", "func (o *ResourceVersion) GetUpdateTsOk() (*int64, bool) {\n\tif o == nil || o.UpdateTs == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdateTs, true\n}", "func (o *PostRestoreKVResponse) GetTokenOk() (*string, bool) {\n\tif o == nil || o.Token == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Token, true\n}", "func (o *CreateUser200Response) GetRefreshTokenOk() (*string, bool) {\n\tif o == nil || IsNil(o.RefreshToken) {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (o *GenerateTokenResponse) GetRefreshTokenOk() (*string, bool) {\n\tif o == nil || o.RefreshToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (o *CreateUser200Response) GetTokenOk() (*string, bool) {\n\tif o == nil || IsNil(o.Token) {\n\t\treturn nil, false\n\t}\n\treturn o.Token, true\n}", "func (o *LoginRequestResponseData) GetOtpTokenOk() (*string, bool) {\n\tif o == nil || o.OtpToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.OtpToken, true\n}", "func (o *BotTokens) GetVerificationTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.VerificationToken, true\n}", "func (o *Authorization) GetTokenOk() (*string, bool) {\n\tif o == nil || o.Token == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Token, true\n}", "func (o *AwsIamToken) GetTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Token, true\n}", "func (o *LogoutFlow) GetLogoutTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.LogoutToken, true\n}", "func (o *LinkTokenCreateRequestIncomeVerificationPayrollIncome) GetIsUpdateModeOk() (*bool, bool) {\n\tif o == nil || o.IsUpdateMode == nil {\n\t\treturn nil, false\n\t}\n\treturn o.IsUpdateMode, true\n}", "func (o *GenerateTokenResponse) GetFlagsOk() (*GenerateTokenResponseFlags, bool) {\n\tif o == nil || o.Flags == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Flags, true\n}", "func (o *IntrospectedOAuth2Token) GetTokenUseOk() (*string, bool) {\n\tif o == nil || o.TokenUse == nil {\n\t\treturn nil, false\n\t}\n\treturn o.TokenUse, true\n}", "func (o *BotTokens) GetAccessTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.AccessToken, true\n}", "func (o *OAuth2ConsentSessionExpiresAt) GetRefreshTokenOk() (*time.Time, bool) {\n\tif o == nil || o.RefreshToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RefreshToken, true\n}", "func (o *Token) GetCheckoutOk() (*TokenCheckout, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Checkout.Get(), o.Checkout.IsSet()\n}", "func (o *LocalDatabaseProvider) GetUpdatedOk() (*time.Time, bool) {\n\tif o == nil || o.Updated == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Updated, true\n}", "func (o *ZoneZone) GetUpdatedOk() (*time.Time, bool) {\n\tif o == nil || o.Updated == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Updated, true\n}", "func (o *UpdateLoginFlowWithCodeMethod) GetCsrfTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.CsrfToken, true\n}", "func (o *Ga4ghTumourboard) GetUpdatedOk() (string, bool) {\n\tif o == nil || o.Updated == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Updated, true\n}", "func (o *LinkSessionFinishedWebhook) GetLinkTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.LinkToken, true\n}", "func CheckAndUpdateToken(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttoken := r.Header.Get(tokenHeaderName)\n\t\tif token == \"\" {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tti, err := controller.Token.GetInfo(token)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tcontroller.Token.UpdateTTL(ti)\n\t\tctx := r.Context()\n\t\tctx = context.WithValue(ctx, LoginKey, ti.Login)\n\t\thandler.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (controller *Controller) CheckPasswordResetToken(tokenStr string, c web.C) (models.UserToken, *models.PasswordReset, bool) {\n\tsession := controller.GetSession(c)\n\tdbMap := controller.GetDbMap(c)\n\n\tvar token models.UserToken\n\n\t// Check that the token is set.\n\tif tokenStr == \"\" {\n\t\tsession.AddFlash(\"No password update token present.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is valid.\n\tvar err error\n\ttoken, err = models.UserTokenFromStr(tokenStr)\n\tif err != nil {\n\t\tsession.AddFlash(\"Email verification token not valid.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is recognized.\n\tpasswordReset, err := helpers.PasswordResetTokenExists(dbMap, token)\n\tif err != nil {\n\t\tlog.Debugf(`Password update token \"%v\" not found in DB: %v`, token, err)\n\t\tsession.AddFlash(\"Password update token not recognized.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, nil, false\n\t}\n\n\t// Check that the token is not expired.\n\texpTime := time.Unix(passwordReset.Expires, 0)\n\tif expTime.Before(time.Now()) {\n\t\tsession.AddFlash(\"Password update token has expired.\",\n\t\t\t\"passwordupdateError\")\n\t\treturn token, passwordReset, false\n\t}\n\n\treturn token, passwordReset, true\n}", "func (o *SettingsObjectUpdate) SetUpdateToken(v string) {\n\to.UpdateToken = &v\n}", "func (o *PaymentStatusUpdateWebhook) GetTransactionIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.TransactionId.Get(), o.TransactionId.IsSet()\n}", "func (o *Ga4ghChemotherapy) GetUpdatedOk() (string, bool) {\n\tif o == nil || o.Updated == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Updated, true\n}", "func (o *LinkSessionFinishedWebhook) GetPublicTokenOk() (*string, bool) {\n\tif o == nil || o.PublicToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PublicToken, true\n}", "func (o *TokenResponse) GetCheckoutOk() (*TokenResponseCheckout, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Checkout.Get(), o.Checkout.IsSet()\n}", "func (o *IntrospectedOAuth2Token) GetNbfOk() (*int64, bool) {\n\tif o == nil || o.Nbf == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Nbf, true\n}", "func (o *UpdatePasswordReqWeb) GetCaptchaTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.CaptchaToken, true\n}", "func (o *StorageRemoteKeySetting) GetIsPasswordSetOk() (*bool, bool) {\n\tif o == nil || o.IsPasswordSet == nil {\n\t\treturn nil, false\n\t}\n\treturn o.IsPasswordSet, true\n}", "func (o *GenerateTokenResponse) GetAccessTokenOk() (*string, bool) {\n\tif o == nil || o.AccessToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AccessToken, true\n}", "func (o *PaymentMethodCardRequest) GetTokenIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.TokenId, true\n}", "func (o *VulnUpdateNotification) GetLastUpdatedOk() (*int32, bool) {\n\tif o == nil || o.LastUpdated == nil {\n\t\treturn nil, false\n\t}\n\treturn o.LastUpdated, true\n}", "func (o *CreateUser200Response) GetAccessTokenOk() (*string, bool) {\n\tif o == nil || IsNil(o.AccessToken) {\n\t\treturn nil, false\n\t}\n\treturn o.AccessToken, true\n}", "func (o *NotificationConfig) GetAuthorizationTokenOk() (*string, bool) {\n\tif o == nil || o.AuthorizationToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AuthorizationToken, true\n}", "func (o *ProjectApiKey) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *OAuth2ConsentSessionExpiresAt) GetIdTokenOk() (*time.Time, bool) {\n\tif o == nil || o.IdToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.IdToken, true\n}", "func (o LookupFirewallPolicyResultOutput) UpdateToken() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.UpdateToken }).(pulumi.StringOutput)\n}", "func (o *ProcessorSignalDecisionReportRequest) GetProcessorTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.ProcessorToken, true\n}", "func (o *RumMetricUpdate) GetEnabledOk() (*bool, bool) {\n\tif o == nil || o.Enabled == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Enabled, true\n}", "func (o *NormalizedProjectRevisionHook) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *Commitstatus) GetUpdatedOnOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedOn == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedOn, true\n}", "func (o *Snippet) GetUpdatedOnOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedOn == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedOn, true\n}", "func (o *PasswordUpdate) GetNewPasswordOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.NewPassword, true\n}", "func (o *AuthenticationResponse) GetSessionTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.SessionToken, true\n}", "func (o *TokenResponse) GetUsedOk() (*bool, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Used, true\n}", "func (o *PaymentInitiationPaymentGetResponse) GetLastStatusUpdateOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.LastStatusUpdate, true\n}", "func (o *PaymentInitiationPayment) GetLastStatusUpdateOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.LastStatusUpdate, true\n}", "func (o *MemberResponse) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *IosVppEBook) GetVppTokenIdOk() (string, bool) {\n\tif o == nil || o.VppTokenId == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.VppTokenId, true\n}", "func (o *PostRestoreKVResponse) HasToken() bool {\n\tif o != nil && o.Token != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *PostWebhook) GetPrUpdatedOk() (*bool, bool) {\n\tif o == nil || o.PrUpdated == nil {\n\t\treturn nil, false\n\t}\n\treturn o.PrUpdated, true\n}", "func (o *Account) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.UpdatedAt, true\n}", "func (o *VisuallyComplete2Settings) GetMutationTimeoutOk() (*int32, bool) {\n\tif o == nil || o.MutationTimeout == nil {\n\t\treturn nil, false\n\t}\n\treturn o.MutationTimeout, true\n}", "func (o *Authorization) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *IdentityAccount) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *TokenResponse) GetLivemodeOk() (*bool, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Livemode, true\n}", "func (o *AssetReportRefreshRequest) GetAssetReportTokenOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.AssetReportToken, true\n}", "func (o *DeferredResultVoid) GetSetOrExpiredOk() (*bool, bool) {\n\tif o == nil || o.SetOrExpired == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SetOrExpired, true\n}", "func (o *StorageRemoteKeySetting) GetPasswordOk() (*string, bool) {\n\tif o == nil || o.Password == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Password, true\n}", "func (o *AuthSupportedMethods) GetInstantAuthOk() (*bool, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.InstantAuth, true\n}", "func (o *JsonMDNOAuthToken) GetVerifierOk() (*string, bool) {\n\tif o == nil || o.Verifier == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Verifier, true\n}", "func (o *DnsZoneDataData) GetZoneAllowUpdateOk() (*string, bool) {\n\tif o == nil || o.ZoneAllowUpdate == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ZoneAllowUpdate, true\n}", "func (o *InvestmentsTransactionsGetRequestOptions) GetAsyncUpdateOk() (*bool, bool) {\n\tif o == nil || o.AsyncUpdate == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AsyncUpdate, true\n}", "func (o *IdentityCredentialIdentifierOidcProperties) GetInitialRefreshTokenOk() (*string, bool) {\n\tif o == nil || o.InitialRefreshToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.InitialRefreshToken, true\n}", "func validateTokenForUpdating(tokenObj token.StructToken) (string, bool) {\n\n\tvar errorfound string\n\t//validate initiator address if exist in account data\n\taccountobj := account.GetAccountByAccountPubicKey(tokenObj.InitiatorAddress)\n\tif accountobj.AccountPublicKey == \"\" {\n\t\terrorfound = \"please enter valid initiator address (Public key)\"\n\t\treturn errorfound, false\n\t}\n\tif accountobj.AccountPassword != tokenObj.Password {\n\t\terrorfound = \"The given password is incorrect.\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens Total Supply less than or equal zero\n\tif tokenObj.TokensTotalSupply < 1 {\n\t\terrorfound = \"please enter Tokens Total Supply more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens value less than or equal zero\n\tif tokenObj.TokenValue <= 0.0 {\n\t\terrorfound = \"please enter Tokens value more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate token precision from 0 to 5\n\tif tokenObj.Precision < 0 || tokenObj.Precision > 5 {\n\t\terrorfound = \"please enter Precision range from 0 to 5 \"\n\t\treturn errorfound, false\n\t}\n\n\t//validate Tokens TokenType is mandatory public or private\n\tif tokenObj.TokenType == \"public\" || tokenObj.TokenType == \"private\" {\n\t\t// check type token is public, optianal enter contact ID\n\t\tif tokenObj.TokenType == \"public\" {\n\t\t\t// validate ContractID if empty or ==60\n\t\t\tif len(tokenObj.ContractID) < 4 || len(tokenObj.ContractID) > 60 {\n\t\t\t\terrorfound = \"enter ContractID must be more than 4 character and less than or equal 60 characters\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t\t// check type token is Private , optianal enter pentential PK ,enter the potential users public keys which can use this token\n\t\taccountList := accountdb.GetAllAccounts()\n\t\tif tokenObj.TokenType == \"private\" {\n\t\t\t//enter pentential PK which can use this token\n\t\t\tif len(tokenObj.UserPublicKey) != 0 {\n\t\t\t\tfor _, pk := range tokenObj.UserPublicKey {\n\t\t\t\t\tif pk == tokenObj.InitiatorAddress {\n\t\t\t\t\t\terrorfound = \"user create token can't be in user public key \"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t\tif !containspk(accountList, pk) {\n\t\t\t\t\t\terrorfound = \"this public key is not associated with any account\"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorfound = \"enter the potential users public keys which can use this token\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorfound = \"please enter TokenType is public or private\"\n\t\treturn errorfound, false\n\t}\n\n\treturn \"\", true\n}", "func (o *Service) GetUpdatedAtOk() (float32, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\tvar ret float32\n\t\treturn ret, false\n\t}\n\treturn *o.UpdatedAt, true\n}", "func (o *PasswordUpdate) GetOldPasswordOk() (*string, bool) {\n\tif o == nil || o.OldPassword == nil {\n\t\treturn nil, false\n\t}\n\treturn o.OldPassword, true\n}", "func (res *GrantTypeInfoResponse) SetTokenUpdate(tokenUpdate *my.MytokenResponse) {\n\tres.TokenUpdate = tokenUpdate\n}", "func (m *TokenMutation) UpdatedAt() (r time.Time, exists bool) {\n\tv := m.updated_at\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o *AuthSupportedMethods) GetInstantMatchOk() (*bool, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.InstantMatch, true\n}", "func (o *CreateUser200Response) HasToken() bool {\n\tif o != nil && !IsNil(o.Token) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Channel) GetUpdatedAtOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.UpdatedAt, true\n}", "func (conf *OnboardingConfig) HasToken() bool {\n\treturn conf.TokenValue != \"\"\n}", "func (o *SubmitSelfServiceSettingsFlowWithProfileMethodBody) GetCsrfTokenOk() (*string, bool) {\n\tif o == nil || o.CsrfToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.CsrfToken, true\n}", "func (o *PaymentStatusUpdateWebhook) GetTimestampOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Timestamp, true\n}", "func CheckToken(token string) bool {\n\tm, err := variable.Get(\"token\")\n\tif err != nil {\n\t\treturn false\n\t}\n\t_token := \"\"\n\tm.SetString(\"token\", &_token)\n\tif _token != token {\n\t\treturn false\n\t}\n\treturn true\n}", "func (o *ModelsUser) GetUpdatedAtOk() (*string, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func (o *SyntheticMonitorUpdate) GetEnabledOk() (*bool, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Enabled, true\n}", "func (o *TppCredentialsParams) GetTppApiKeyOk() (*string, bool) {\n\tif o == nil || o.TppApiKey == nil {\n\t\treturn nil, false\n\t}\n\treturn o.TppApiKey, true\n}", "func (o *ItemImportRequestOptions) GetWebhookOk() (*string, bool) {\n\tif o == nil || o.Webhook == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Webhook, true\n}", "func (o *OAuth2ConsentSessionExpiresAt) GetAccessTokenOk() (*time.Time, bool) {\n\tif o == nil || o.AccessToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.AccessToken, true\n}", "func (o *QueryTradeInfoRequest) GetTimeStampOk() (*int, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.TimeStamp, true\n}", "func (o *ApplianceDeviceClaimAllOf) GetSecurityTokenOk() (*string, bool) {\n\tif o == nil || o.SecurityToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SecurityToken, true\n}", "func (o *UpdatePasswordReqWeb) GetNewPasswordOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.NewPassword, true\n}", "func (o *IntrospectedOAuth2Token) GetUsernameOk() (*string, bool) {\n\tif o == nil || o.Username == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Username, true\n}", "func (is *BareMetalService) UpdateToken() error {\n\ttoken := is.provider.Token()\n\tresult, err := tokens.Validate(is.identityClient, token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Validate token err: %v\", err)\n\t}\n\tif result {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"Token is out of date, getting new token.\")\n\treAuthFunction := is.provider.ReauthFunc\n\tif reAuthFunction() != nil {\n\t\treturn fmt.Errorf(\"reAuth err: %v\", err)\n\t}\n\treturn nil\n}", "func (o *GenerateTokenResponse) GetDblEnabledOk() (*bool, bool) {\n\tif o == nil || o.DblEnabled == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DblEnabled, true\n}", "func (s *Secret) TokenIsRenewable() (bool, error) {\n\tif s == nil {\n\t\treturn false, nil\n\t}\n\n\tif s.Auth != nil && s.Auth.Renewable {\n\t\treturn s.Auth.Renewable, nil\n\t}\n\n\tif s.Data == nil || s.Data[\"renewable\"] == nil {\n\t\treturn false, nil\n\t}\n\n\trenewable, err := parseutil.ParseBool(s.Data[\"renewable\"])\n\tif err != nil {\n\t\treturn false, errwrap.Wrapf(\"could not convert renewable value to a boolean: {{err}}\", err)\n\t}\n\n\treturn renewable, nil\n}", "func (o *UploadResponse) GetOkOk() (*bool, bool) {\n\tif o == nil || o.Ok == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Ok, true\n}", "func (o *LogicalDatabaseResponse) GetUpdatedAtOk() (*time.Time, bool) {\n\tif o == nil || o.UpdatedAt == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdatedAt, true\n}", "func UpdateToken(username string, token string) bool {\n\tstmt, err := mydb.DBConn().Prepare(\n\t\t\"replace into tb_user_token(username, user_token) values(?,?)\")\n\tif err != nil {\n\t\tfmt.Println(\"stmt err:\", err.Error())\n\t\treturn false\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(username, token)\n\tif err != nil {\n\t\tfmt.Println(\"update token err:\", err.Error())\n\t\treturn false\n\t}\n\treturn true\n}" ]
[ "0.68318295", "0.6461256", "0.6456338", "0.640675", "0.62967545", "0.6278281", "0.62441194", "0.62144756", "0.61986005", "0.6175006", "0.6164585", "0.61463106", "0.61126053", "0.6100583", "0.6085443", "0.6024523", "0.58378875", "0.5822106", "0.5821804", "0.58118004", "0.58022815", "0.5801243", "0.5800975", "0.5737417", "0.5677808", "0.5669344", "0.5636864", "0.5623876", "0.560989", "0.55901545", "0.557602", "0.5525627", "0.55129457", "0.5503606", "0.5480429", "0.54677516", "0.5465052", "0.5448616", "0.5447836", "0.5414607", "0.5412022", "0.5410555", "0.5402143", "0.538226", "0.5374944", "0.53630245", "0.5336511", "0.5309029", "0.5302876", "0.52921116", "0.5262595", "0.52475476", "0.52402127", "0.5236743", "0.5222094", "0.5221655", "0.52170944", "0.5212282", "0.5210698", "0.5196098", "0.5194088", "0.51817465", "0.517007", "0.5169117", "0.5152944", "0.5149658", "0.5118912", "0.5117663", "0.51100796", "0.51071113", "0.51001984", "0.50932765", "0.50931585", "0.5091021", "0.5086259", "0.5083769", "0.50772125", "0.50763845", "0.5075784", "0.5075002", "0.50625205", "0.5048802", "0.50454193", "0.50442934", "0.5043299", "0.5039567", "0.5027366", "0.5026078", "0.5023026", "0.5007708", "0.49912226", "0.4987987", "0.49786407", "0.4977096", "0.4976078", "0.4974372", "0.4961711", "0.49523795", "0.49499527", "0.49247447" ]
0.8418718
0
HasUpdateToken returns a boolean if a field has been set.
func (o *SettingsObjectUpdate) HasUpdateToken() bool { if o != nil && o.UpdateToken != nil { return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *LinkTokenCreateRequestIncomeVerificationPayrollIncome) HasIsUpdateMode() bool {\n\tif o != nil && o.IsUpdateMode != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ResourceVersion) HasUpdateTs() bool {\n\tif o != nil && o.UpdateTs != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a *ADMResponse) UpdateToken() bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\tif a.Error == ErrRemoveToken || a.Error == ErrUpdateToken {\n\t\treturn true\n\t}\n\treturn false\n}", "func (o *CreateUser200Response) HasRefreshToken() bool {\n\tif o != nil && !IsNil(o.RefreshToken) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SettingsObjectUpdate) GetUpdateTokenOk() (*string, bool) {\n\tif o == nil || o.UpdateToken == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UpdateToken, true\n}", "func (u *Updater) HasUpdate() (bool, error) {\n\treturn u.pkg.CanUpdate()\n}", "func (d UserData) HasLastUpdate() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"LastUpdate\", \"__last_update\"))\n}", "func (o *InvestmentsTransactionsGetRequestOptions) HasAsyncUpdate() bool {\n\tif o != nil && o.AsyncUpdate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *GenerateTokenResponse) HasRefreshToken() bool {\n\tif o != nil && o.RefreshToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *LocalDatabaseProvider) HasUpdated() bool {\n\tif o != nil && o.Updated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m MarketDataSnapshotFullRefresh) HasPutOrCall() bool {\n\treturn m.Has(tag.PutOrCall)\n}", "func (o *PostRestoreKVResponse) HasToken() bool {\n\tif o != nil && o.Token != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *CreateUser200Response) HasToken() bool {\n\tif o != nil && !IsNil(o.Token) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *OAuth2ConsentSessionExpiresAt) HasRefreshToken() bool {\n\tif o != nil && o.RefreshToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *JsonMDNOAuthToken) HasToken() bool {\n\tif o != nil && o.Token != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (conf *OnboardingConfig) HasToken() bool {\n\treturn conf.TokenValue != \"\"\n}", "func (obj *tokenSection) HasToken() bool {\n\treturn obj.token != nil\n}", "func (o *ViewProjectBudget) HasUpdatedBy() bool {\n\tif o != nil && o.UpdatedBy != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Ga4ghTumourboard) HasUpdated() bool {\n\tif o != nil && o.Updated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ViewMilestone) HasUpdatedBy() bool {\n\tif o != nil && o.UpdatedBy != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *MemberResponse) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Ga4ghChemotherapy) HasUpdated() bool {\n\tif o != nil && o.Updated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *RumMetricUpdate) HasEnabled() bool {\n\tif o != nil && o.Enabled != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Snippet) HasUpdatedOn() bool {\n\tif o != nil && o.UpdatedOn != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Authorization) HasToken() bool {\n\tif o != nil && o.Token != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *LoginRequestResponseData) HasOtpToken() bool {\n\tif o != nil && o.OtpToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (at *AuthtokenToken) Exists() bool {\n\treturn at._exists\n}", "func (o *Venda) HasToken() bool {\n\tif o != nil && o.Token.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SettingsObjectUpdate) GetUpdateToken() string {\n\tif o == nil || o.UpdateToken == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.UpdateToken\n}", "func (t *tokenStorage) HasToken(deviceID string) (bool, error) {\n\tt.mapLock.Lock()\n\tdefer t.mapLock.Unlock()\n\n\t_, ok := t.tokens[deviceID]\n\treturn ok, nil\n}", "func (o *ProjectApiKey) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Service) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (token Token) Exists() bool {\n\treturn token.Key != \"\"\n}", "func (m OrderStatusRequest) HasPutOrCall() bool {\n\treturn m.Has(tag.PutOrCall)\n}", "func (r *RoleUpdate) HasMembers() bool {\n\treturn r.hasMembers\n}", "func (m KubedgeBaseManager) IsUpdateRequired() bool {\n\treturn m.IsUpdateRequiredFlag\n}", "func (o *IntrospectedOAuth2Token) HasTokenUse() bool {\n\tif o != nil && o.TokenUse != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *CreateUser200Response) HasAccessToken() bool {\n\tif o != nil && !IsNil(o.AccessToken) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ViewProjectBudget) HasUpdatedByUserId() bool {\n\tif o != nil && o.UpdatedByUserId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ModelsUser) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TAttlistCommentsCorrectionsRefType) IsUpdateOf() bool { return me.String() == \"UpdateOf\" }", "func HasUpdate(dir string) error {\n\th, err := hasUpdate(federalRevenueURL, dir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting updated at: %w\", err)\n\t}\n\tif !h {\n\t\tos.Exit(1)\n\t}\n\treturn nil\n}", "func (o *VulnUpdateNotification) HasLastUpdated() bool {\n\tif o != nil && o.LastUpdated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ZoneZone) HasUpdated() bool {\n\tif o != nil && o.Updated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *GenerateTokenResponse) HasAccessToken() bool {\n\tif o != nil && o.AccessToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (me TAttlistCommentsCorrectionsRefType) IsUpdateIn() bool { return me.String() == \"UpdateIn\" }", "func (o *Commitstatus) HasUpdatedOn() bool {\n\tif o != nil && o.UpdatedOn != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (x *fastReflection_MsgUpdateParams) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"cosmos.distribution.v1beta1.MsgUpdateParams.authority\":\n\t\treturn x.Authority != \"\"\n\tcase \"cosmos.distribution.v1beta1.MsgUpdateParams.params\":\n\t\treturn x.Params != nil\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgUpdateParams\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgUpdateParams does not contain field %s\", fd.FullName()))\n\t}\n}", "func (o *Authorization) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (wu *WsubUpdate) Exists() bool {\n\treturn wu._exists\n}", "func (o *UpdatesV3Request) HasReleasever() bool {\n\tif o != nil && o.Releasever != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *PostWebhook) HasPrUpdated() bool {\n\tif o != nil && o.PrUpdated != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *NormalizedProjectRevisionHook) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *IdentityAccount) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ClusterRequest) HasAutoUpdate() bool {\n\tif o != nil && o.AutoUpdate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *LogicalDatabaseResponse) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Service) HasServiceUpdatedAt() bool {\n\tif o != nil && o.ServiceUpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VisuallyComplete2Settings) HasMutationTimeout() bool {\n\tif o != nil && o.MutationTimeout != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_Rootchain *RootchainCaller) HasToken(opts *bind.CallOpts, _token common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"hasToken\", _token)\n\treturn *ret0, err\n}", "func hasUpdateArg(args []string) bool {\n\tfor _, arg := range args {\n\t\tif ArgWorkflowUpdate == arg {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *ConnectorpackUpgradeImpact) HasIsUpdateDownloaded() bool {\n\tif o != nil && o.IsUpdateDownloaded != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (container *container) HasPendingUpdates() (bool, error) {\r\n\treturn false, nil\r\n}", "func (o *ItemImportRequestOptions) HasWebhook() bool {\n\tif o != nil && o.Webhook != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (n *Sub) IsUpdate(w *model.Watcher) bool {\n\treturn n.w.Mtime.Unix() != w.Mtime.Unix()\n}", "func (o *SettingsObjectUpdate) HasSchemaVersion() bool {\n\tif o != nil && o.SchemaVersion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *OAuth2ConsentSessionExpiresAt) HasIdToken() bool {\n\tif o != nil && o.IdToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SyntheticsGlobalVariableParseTestOptions) HasField() bool {\n\treturn o != nil && o.Field != nil\n}", "func (o *SettingsObjectUpdate) SetUpdateToken(v string) {\n\to.UpdateToken = &v\n}", "func (q authTokenQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if auth_tokens exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (s *Struct) HasField(name string) bool {\n\tfor _, f := range s.Fields {\n\t\tif f.Name == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *InlineResponse200115) HasHasEditExpired() bool {\n\tif o != nil && o.HasEditExpired != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ViewUserDashboard) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *LinkSessionFinishedWebhook) HasPublicToken() bool {\n\tif o != nil && o.PublicToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UpdateRole) HasMembers() bool {\n\tif o != nil && o.Members != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a *api) checkRefreshToken() bool {\n\treturn a.refreshToken != \"\"\n}", "func (o *UpdatesV3Request) HasModulesList() bool {\n\tif o != nil && o.ModulesList != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *VersionedFlowUpdateRequestEntity) HasRequest() bool {\n\tif o != nil && o.Request != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m MarketDataSnapshotFullRefresh) HasMDReqID() bool {\n\treturn m.Has(tag.MDReqID)\n}", "func (o *Invitation) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Measurement) HasField(name string) bool {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\t_, hasField := m.fieldNames[name]\n\treturn hasField\n}", "func (s *Structx) HasField(name string) bool {\n\t_, ok := s.value.Type().FieldByName(name)\n\treturn ok\n}", "func AuthTokenExists(exec boil.Executor, token string) (bool, error) {\n\tvar exists bool\n\tsql := \"select exists(select 1 from \\\"auth_tokens\\\" where \\\"token\\\"=$1 limit 1)\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, token)\n\t}\n\n\trow := exec.QueryRow(sql, token)\n\n\terr := row.Scan(&exists)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: unable to check if auth_tokens exists\")\n\t}\n\n\treturn exists, nil\n}", "func (o *ProjectDeploymentRuleResponse) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (x *fastReflection_MsgUpdateParams) IsValid() bool {\n\treturn x != nil\n}", "func (x *fastReflection_MsgUpdateParamsResponse) IsValid() bool {\n\treturn x != nil\n}", "func (o *EnvironmentAutoUpdateConfig) HasMetadata() bool {\n\tif o != nil && o.Metadata != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UpdateMetricRulesetRequest) HasVersion() bool {\n\tif o != nil && !isNil(o.Version) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_Rootchain *RootchainSession) HasToken(_token common.Address) (bool, error) {\n\treturn _Rootchain.Contract.HasToken(&_Rootchain.CallOpts, _token)\n}", "func (o *Token) HasCheckout() bool {\n\tif o != nil && o.Checkout.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_Rootchain *RootchainCallerSession) HasToken(_token common.Address) (bool, error) {\n\treturn _Rootchain.Contract.HasToken(&_Rootchain.CallOpts, _token)\n}", "func (qp QueryParsed) IsUpdate() bool {\n\treturn qp.Structure.GetKind() == lib.QueryKindCreate ||\n\t\tqp.Structure.GetKind() == lib.QueryKindDrop ||\n\t\tqp.Structure.GetKind() == lib.QueryKindDelete ||\n\t\tqp.Structure.GetKind() == lib.QueryKindInsert ||\n\t\tqp.Structure.GetKind() == lib.QueryKindUpdate\n}", "func (o *TppCredentialsParams) HasTppApiKey() bool {\n\tif o != nil && o.TppApiKey != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *UpdatesV3Request) HasOptimisticUpdates() bool {\n\tif o != nil && o.OptimisticUpdates != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (k Keeper) HasToken(ctx sdk.Context, denom string) bool {\n\tstore := ctx.KVStore(k.storeKey)\n\tif k.HasSymbol(ctx, denom) {\n\t\treturn true\n\t}\n\n\treturn store.Has(types.KeyMinUint(denom))\n}", "func (o *PiggyBankEvent) HasUpdatedAt() bool {\n\tif o != nil && o.UpdatedAt != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Client) HasValidToken() bool {\n\treturn c.lastRefresh != nil && c.lastRefresh.Add(c.expiresIn).After(time.Now())\n}", "func (s LocalSecretManager) DoesTokenExist(reqToken string) bool {\n\ttoken := viper.GetString(\"TOKEN\")\n\treturn reqToken == token\n}", "func (o *CreditBankIncomeItem) HasLastUpdatedTime() bool {\n\tif o != nil && o.LastUpdatedTime != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func HasUserToken(userID uuid.UUID) (bool, string) {\n\tdefer mutex.Unlock()\n\tmutex.Lock()\n\n\tfor k, v := range tokenAvailable {\n\t\tif v.userID == userID {\n\t\t\treturn true, k\n\t\t}\n\t}\n\treturn false, \"\"\n}", "func (o *StorageRemoteKeySetting) HasIsPasswordSet() bool {\n\tif o != nil && o.IsPasswordSet != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}" ]
[ "0.6537793", "0.652027", "0.6315659", "0.6284824", "0.6190397", "0.6177681", "0.61633116", "0.6116406", "0.6113553", "0.605806", "0.598599", "0.59564817", "0.5915422", "0.59153587", "0.59145457", "0.58912975", "0.5877821", "0.58766997", "0.5840582", "0.5814582", "0.58042204", "0.5801325", "0.57948494", "0.57423025", "0.5738624", "0.57257706", "0.57253754", "0.5722127", "0.57164717", "0.57018733", "0.56908727", "0.56895775", "0.56608075", "0.56291264", "0.5627573", "0.561731", "0.56043434", "0.55984485", "0.5596989", "0.5595328", "0.5586753", "0.5581962", "0.5577771", "0.557501", "0.5568636", "0.5561812", "0.55312455", "0.55237085", "0.5521768", "0.5513743", "0.55019116", "0.5492284", "0.54871315", "0.548249", "0.54774517", "0.5475673", "0.54710144", "0.5470344", "0.5468596", "0.5441668", "0.54398793", "0.5437595", "0.5409851", "0.54074895", "0.540503", "0.53873193", "0.53869396", "0.5385488", "0.536589", "0.5365319", "0.53582966", "0.535513", "0.5346685", "0.5339713", "0.53382754", "0.53328395", "0.53270894", "0.53240484", "0.53116417", "0.53091985", "0.53064936", "0.52984995", "0.52965635", "0.5274135", "0.52592367", "0.525172", "0.5243998", "0.5241211", "0.5241142", "0.5233691", "0.5230105", "0.52265674", "0.52080566", "0.5200683", "0.5195786", "0.51871014", "0.51717347", "0.51667166", "0.5165583", "0.5161583" ]
0.8413846
0
SetUpdateToken gets a reference to the given string and assigns it to the UpdateToken field.
func (o *SettingsObjectUpdate) SetUpdateToken(v string) { o.UpdateToken = &v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (res *GrantTypeInfoResponse) SetTokenUpdate(tokenUpdate *my.MytokenResponse) {\n\tres.TokenUpdate = tokenUpdate\n}", "func (s *SessHelper) UpdateToken(appid, uuid, token string, expireMS int) error {\n\treturn nil\n}", "func (o *SettingsObjectUpdate) GetUpdateToken() string {\n\tif o == nil || o.UpdateToken == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.UpdateToken\n}", "func (u *BasicUpdateOperation) SetToken(token string) {\n\tu.Token = token\n}", "func (o LookupFirewallPolicyResultOutput) UpdateToken() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.UpdateToken }).(pulumi.StringOutput)\n}", "func (l *RemoteProvider) UpdateToken(w http.ResponseWriter, r *http.Request) string {\n\tl.TokenStoreMut.Lock()\n\tdefer l.TokenStoreMut.Unlock()\n\n\ttokenString, _ := l.GetToken(r)\n\tnewts := l.TokenStore[tokenString]\n\tif newts != \"\" {\n\t\tlogrus.Debugf(\"set updated token: %v\", newts)\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName: tokenName,\n\t\t\tValue: newts,\n\t\t\tPath: \"/\",\n\t\t\tHttpOnly: true,\n\t\t})\n\t\treturn newts\n\t}\n\n\treturn tokenString\n}", "func (is *BareMetalService) UpdateToken() error {\n\ttoken := is.provider.Token()\n\tresult, err := tokens.Validate(is.identityClient, token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Validate token err: %v\", err)\n\t}\n\tif result {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"Token is out of date, getting new token.\")\n\treAuthFunction := is.provider.ReauthFunc\n\tif reAuthFunction() != nil {\n\t\treturn fmt.Errorf(\"reAuth err: %v\", err)\n\t}\n\treturn nil\n}", "func (b *BoltAuthRepository) SetToken(tkn models.Token) error {\n\treturn b.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(b.bucket))\n\t\tbytes, err := json.Marshal(tkn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn b.Put([]byte(tkn.Value), bytes)\n\t})\n}", "func SetToken(t string) {\n\ttoken = t\n}", "func (c *Client) SetToken(v string) {\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\tc.token = v\n}", "func (t *ServiceAccountToken) Update() error {\n\ttok, err := t.updateFn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the stored token.\n\tt.mtx.Lock()\n\tdefer t.mtx.Unlock()\n\tt.tok = tok\n\tsklog.Infof(\"Updated token: %s\", tok.AccessToken[len(tok.AccessToken)-8:])\n\treturn nil\n}", "func SetToken(newtoken string) string {\n\tToken = newtoken\n\treturn Token\n}", "func (_m *NoteServiceHandler) SetToken(token string) {\n\t_m.Called(token)\n}", "func SetPushDeviceToken(token string) { pushDeviceTokenAtomic.Store(token) }", "func (m *VppToken) SetToken(value *string)() {\n m.token = value\n}", "func (c *Client) SetToken(t string) {\n\tc.init()\n\tc.vc.SetToken(t)\n\tc.sw = c.vc.Logical()\n}", "func UpdateToken(oldToken, secret string) (string, time.Time, error) {\n\toldTokParsed, err := jwt.Parse(oldToken, func(t *jwt.Token) (interface{}, error) {\n\t\tif _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected token signing: %v\", t.Header[\"alg\"])\n\t\t}\n\n\t\treturn []byte(secret), nil\n\t})\n\n\tif err != nil {\n\t\treturn \"\", time.Time{}, err\n\t}\n\n\toldClaimg, ok := oldTokParsed.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\treturn \"\", time.Time{}, fmt.Errorf(\"Error during updating token\")\n\t}\n\n\tusername, ok := oldClaimg[\"username\"].(string)\n\tif !ok {\n\t\treturn \"\", time.Time{}, fmt.Errorf(\"Can't extract one or more claims fields\")\n\t}\n\n\treturn CreateToken(username, secret)\n\n}", "func SetToken(token string) OptionFunc {\n\treturn func(c *Client) error {\n\t\tif token == \"\" {\n\t\t\tc.errorf(\"%v\\n\", ErrBadToken)\n\t\t\treturn ErrBadToken\n\t\t}\n\t\tc.token = token\n\t\treturn nil\n\t}\n}", "func (t *Token) Update() {\n\tatomic.StoreInt64(&t.unix, time.Now().Unix())\n}", "func (tk *TokenRedis) SetToken(ctx context.Context, userID int64, token string, duration time.Duration) error {\n\tqueryKey := fmt.Sprintf(\"%s:%s:%d\", RedisKey, TokenKey, userID)\n\n\terr := tk.redis.Set(ctx, queryKey, token, duration).Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetToken(token string) {\n\tAPI.Token = token\n}", "func (c *Client) SetToken(token string) {\n\tc.mu.Lock()\n\tc.token = token\n\tc.mu.Unlock()\n}", "func (cfg *Config) SetToken(token string) {\n\tcfg.Token = token\n}", "func (a *API) SetToken(token string) {\r\n\ta.access_token = token\r\n}", "func (l *LockArgs) SetToken(token string) {\n\tl.Token = token\n}", "func (handler *AuthHandler) UpdateToken(c *gin.Context) {\n\tif c.Request.URL.Path == \"/login\" || c.Request.URL.Path == \"/auth/callback\" {\n\t\tc.Next()\n\t}\n\n\trawTokenCookie, err := c.Request.Cookie(\"token\")\n\tif err != nil {\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login\")\n\t\treturn\n\t}\n\n\ttoken := decodeToken(rawTokenCookie, c)\n\n\ttokensource := handler.Oauth2Conf.TokenSource(context.TODO(), token)\n\tupdatedToken, err := tokensource.Token()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/login\")\n\t\tc.Abort()\n\t}\n\n\tupdatedRawToken, err := json.Marshal(updatedToken)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tc.Redirect(http.StatusTemporaryRedirect, \"/index\")\n\t\tc.AbortWithError(400, err)\n\t}\n\n\trawTokenCookie.Value = string(updatedRawToken)\n\n\tc.Next()\n}", "func (c *Client) SetToken(token string) *Client {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.token = token\n\tc.expiresAt = time.Now().Add(600 * time.Second)\n\treturn c\n}", "func (token *Token) Update(db *sqlx.DB) {\n\t\n\tif strings.TrimSpace(token.AccessToken) == \"\" || strings.TrimSpace(token.RefreshToken) == \"\" || token.RefreshTokenExpiry == 0 || token.AccessTokenExpiry == 0 || strings.TrimSpace(token.DeviceID) == \"\" || strings.TrimSpace(token.MacAddress) == \"\" || strings.TrimSpace(token.APIKey) == \"\" || token.Status == 0{\n\t\tfmt.Println(\"Missing Fields from tokens\")\n\t\treturn\n\t}\n\t\n\tif strings.TrimSpace(token.ID) == \"\" {\n\t\tfmt.Println(\"Empty ID\")\n\t\treturn\n\t}\n\n\tsql := \"UPDATE tokens SET access_token=?,access_token_time=?,access_token_expiry=?,user_id=?,status=?,api_key=?,refresh_token=?,refresh_token_time=?,refresh_token_expiry=?,device_id=?,mac_address=? WHERE id='\" + token.ID + \"'\"\n\n\t_, err := db.Exec(sql,\n\t\ttoken.AccessToken,\n\t\ttoken.AccessTokenTime,\n\t\ttoken.AccessTokenExpiry,\n\t\ttoken.UserID,\n\t\ttoken.Status,\n\t\ttoken.APIKey,\n\t\ttoken.RefreshToken,\n\t\ttoken.RefreshTokenTime,\n\t\ttoken.RefreshTokenExpiry,\n\t\ttoken.DeviceID,\n\t\ttoken.MacAddress,\n\t)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (c *EcomClient) SetToken(cfg *configmgr.EcomConfigEntry) error {\n\tfile, err := configmgr.TokenFilename(cfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"token file %q not found: %w\", file, err)\n\t}\n\ttar, err := configmgr.ReadTokenAndRefreshToken(file)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"token and refresh token cannot be read from %q: %w\", file, err)\n\t}\n\tvar p jwt.Parser\n\tt, _, err := p.ParseUnverified(tar.IDToken, &jwt.StandardClaims{})\n\tclaims := t.Claims.(*jwt.StandardClaims)\n\tutcNow := time.Now().Unix()\n\n\t// If the token has expired, use the refresh token to get another\n\tif claims.ExpiresAt-utcNow <= 0 {\n\t\tf, err := c.GetConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttar, err = c.ExchangeRefreshTokenForIDToken(f.APIKEY, tar.RefreshToken)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"exchange refresh token for id token failed: %w\", err)\n\t\t}\n\t\thostname, err := configmgr.URLToHostName(cfg.Endpoint)\n\t\tfilename := fmt.Sprintf(\"%s-%s\", hostname, cfg.DevKey[:6])\n\t\terr = configmgr.WriteTokenAndRefreshToken(filename, tar)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"write token and refresh token failed: %w\", err)\n\t\t}\n\t}\n\tc.jwt = tar.IDToken\n\treturn nil\n}", "func (c *Client) UpdateSyncToken(token string) {\n\tc.syncTokenPolicy.addToken(token)\n}", "func UpdateRefreshToken(mongo *mongo.Client, login, refreshToken, accessToken string, refreshValidUntil, validUntil time.Time) error {\n\tfieldsToUpdate := primitive.D{\n\t\t{\"auth.refreshToken\", refreshToken},\n\t\t{\"auth.refreshValidUntil\", refreshValidUntil},\n\t\t{\"auth.accessToken\", accessToken},\n\t\t{\"auth.validUntil\", validUntil},\n\t}\n\n\treturn updateUser(mongo, login, fieldsToUpdate)\n}", "func UpdateToken(username string, token string) bool {\n\tstmt, err := mydb.DBConn().Prepare(\n\t\t\"replace into tb_user_token(username, user_token) values(?,?)\")\n\tif err != nil {\n\t\tfmt.Println(\"stmt err:\", err.Error())\n\t\treturn false\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(username, token)\n\tif err != nil {\n\t\tfmt.Println(\"update token err:\", err.Error())\n\t\treturn false\n\t}\n\treturn true\n}", "func (e *Event) SetToken(token string) {\n\te.Token = token\n}", "func (ap *Provider) updateToken(client clients.AzureClient, token *v3.Token) error {\n\t// For the new flow via Microsoft Graph, the caching and updating of the token to the Microsoft Graph API\n\t// is handled separately via the SDK client cache.\n\tcfg, err := ap.GetAzureConfigK8s()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !IsConfigDeprecated(cfg) {\n\t\treturn nil\n\t}\n\n\tcurrent, err := client.MarshalTokenJSON()\n\tif err != nil {\n\t\treturn errors.New(\"failed to unmarshal token\")\n\t}\n\n\tsecret, err := ap.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{token})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// providerToken doesn't exist as a secret, update on token.\n\t\t\tif current, ok := token.ProviderInfo[\"access_token\"]; ok && current != current {\n\t\t\t\ttoken.ProviderInfo[\"access_token\"] = current\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif current == secret {\n\t\treturn nil\n\t}\n\n\treturn ap.tokenMGR.UpdateSecret(token.UserID, token.AuthProvider, current)\n}", "func (client *RestClient) SetToken(newToken string) {\n\tclient.token = newToken\n\tclient.userName = \"\"\n\tclient.userPwd = \"\"\n}", "func (l *Login) SetToken(v string) {\n\t// return if Login type is nil\n\tif l == nil {\n\t\treturn\n\t}\n\n\tl.Token = &v\n}", "func (l *Login) SetToken(v string) {\n\t// return if Login type is nil\n\tif l == nil {\n\t\treturn\n\t}\n\n\tl.Token = &v\n}", "func (at *AuthtokenToken) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !at._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif at._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE public.authtoken_token SET (` +\n\t\t`created, user_id` +\n\t\t`) = ( ` +\n\t\t`$1, $2` +\n\t\t`) WHERE key = $3`\n\n\t// run query\n\tXOLog(sqlstr, at.Created, at.UserID, at.Key)\n\t_, err = db.Exec(sqlstr, at.Created, at.UserID, at.Key)\n\treturn err\n}", "func (a *ADMResponse) UpdateToken() bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\tif a.Error == ErrRemoveToken || a.Error == ErrUpdateToken {\n\t\treturn true\n\t}\n\treturn false\n}", "func (rd *RedisHelper)UpdateToken(user user.User) (err error){\n\tif rd==nil{\n\t\tlog4go.Error(\"RedisHelper instance is nil\")\n\t\treturn errors.New(\"Nil point receivcer\")\n\t}\n\tresult, err := redis.Strings(rd.conn.Do(\"LRANGE\", user.GetUserName(), 0, -1))\n\tif err!=nil{\n\t\tlog4go.Error(err)\n\t\treturn\n\t}\n\tif len(result) == 0{\n\t\tlog4go.Error(fmt.Sprintf(\"No such user %v in redis\", user.GetUserName()))\n\t\treturn\n\t}\n\tif len(result) >= 2{\n\t\t_, err = rd.conn.Do(\"LTRIM\", user.GetUserName(), 0, 1)\n\t}\n\tif user.GetPassword() != result[0]{\n\t\tlog4go.Error(fmt.Sprintf(\"Fail to insert token due to wrong password,\" +\n\t\t\t\" user %v\", user.GetUserName()))\n\t\treturn\n\t}\n\tif len(result) == 1{\n\t\t_, err = rd.conn.Do(\"RPOP\", user.GetUserName())\n\t\tif err != nil {\n\t\t\tlog4go.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\treturn rd.InsertToken(user)\n}", "func (vuuo *VacUserUpdateOne) SetToken(s string) *VacUserUpdateOne {\n\tvuuo.mutation.SetToken(s)\n\treturn vuuo\n}", "func (me *TAttlistKeywordListOwner) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func (vuu *VacUserUpdate) SetToken(s string) *VacUserUpdate {\n\tvuu.mutation.SetToken(s)\n\treturn vuu\n}", "func (o *Venda) SetToken(v string) {\n\to.Token.Set(&v)\n}", "func UpdateFCMToken(userID string, token string) error {\n\n\tif token == \"\" {\n\t\treturn errors.New(\"invalid token\")\n\t}\n\n\t_, err := db.SQL.Exec(`UPDATE \"UserSettings\" SET fcmToken = ? WHERE userID = ?;`, token, userID)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn errors.New(\"database error\")\n\t}\n\n\treturn nil\n}", "func (a *UserPassAuthStrategy) SetToken(req *http.Request) {\n\t// no-op\n}", "func (c *Client) SetToken(token string) {\n\tc.token = \"JWT \" + token\n}", "func (s *TokenStorage) Update(token storage.Token) error {\n\tif token.Refresh == \"\" {\n\t\treturn errors.New(\"RefreshToken is mandatory for DB save\")\n\t}\n\n\tcollection := s.client.MD.Collection(TokenCollectionName)\n\t_, err := collection.UpdateOne(nil, bson.M{\"refresh\": token.Refresh}, bson.M{\n\t\t\"access\": token.Access,\n\t\t\"username\": token.Username,\n\t\t\"parent\": token.Parent,\n\t\t\"expired\": token.Expired,\n\t})\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"function\": \"Token.Update\",\n\t\t\t\"error\": err,\n\t\t}).Debug(\"mongo request failed\")\n\t}\n\n\treturn err\n}", "func (f *vaultTokenAuthHandler) SetToken(token string) {\n\tf.client.SetToken(token)\n}", "func (us *UserService) UserSetToken(id int, sessionToken string) (*railway.User, error) {\n\tdetails := &MethodInfo{\n\t\tName: \"UserSetToken\",\n\t\tDescription: \"UserSetToken is the DB method used to UserSetToken\",\n\t}\n\ttx, err := us.db.Begin()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, details.Name)\n\t}\n\n\tupdatedUser := &railway.User{}\n\tquery := fmt.Sprintf(`\n\tUPDATE users\n\tSET session_token=$1 \n\tWHERE id=$2\n\tRETURNING %s\n`, userAllColumns)\n\terr = tx.QueryRow(query, sessionToken, id).Scan(updatedUser.Scan()...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, details.Name)\n\t}\n\n\ttx.Commit()\n\treturn updatedUser, nil\n}", "func (m *AndroidEnrollmentCompanyCode) SetEnrollmentToken(value *string)() {\n err := m.GetBackingStore().Set(\"enrollmentToken\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *SlackConfig) SetToken(t string) {\n\ts.Token = t\n}", "func (t *Tik) SetToken(s string) {\n\tt.token = s\n\tt.logger.Println(\"GCP token is overwritten by environment variable.\")\n}", "func (client *Client) SetToken(token string) {\n\tclient.Token = token\n}", "func (c *APIClient) SetToken(token string) {\n\tc.token = token\n}", "func (c *MqClient) SetToken(token string) {\n\tc.token = token\n}", "func (f *FileStorage) SetToken(t *oauth2.Token) error {\n\tif t == nil || !t.Valid() {\n\t\treturn errors.New(\"bad token\")\n\t}\n\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tout, err := os.OpenFile(f.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tdata, err := json.Marshal(&t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = out.Write(data)\n\treturn err\n}", "func UpdateAccessToken(t *AccessToken) error {\n\t_, err := x.ID(t.ID).AllCols().Update(t)\n\treturn err\n}", "func (cli *Client) SetToken(token string) {\n\tcli.token = token\n}", "func (d *Dao) UpdateSnsToken(c context.Context, a *model.SnsToken) (affected int64, err error) {\n\tvar res sql.Result\n\tif res, err = d.snsDB.Exec(c, _updateSnsTokenSQL, a.Token, a.Expires, a.Mid, a.Platform); err != nil {\n\t\tlog.Error(\"UpdateSnsToken(%+v) tx.Exec() error(%+v)\", a, err)\n\t\treturn\n\t}\n\treturn res.RowsAffected()\n}", "func SetToken(ctx context.Context, token string) context.Context {\n\treturn context.WithValue(ctx, tokenKey, token)\n}", "func (us *UserService) UserSetResetToken(id int) (string, error) {\n\tdetails := &MethodInfo{\n\t\tName: \"UserSetResetToken\",\n\t\tDescription: \"UserSetResetToken is the DB method used to UserSetResetToken\",\n\t}\n\ttoken := uuid.NewV4().String()\n\ttx, err := us.db.Begin()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, details.Name)\n\t}\n\n\tquery := `\n\tUPDATE users\n\tSET password_reset_token=$1\n\tWHERE id=$2\n`\n\n\ttx.QueryRow(query, token, id).Scan()\n\ttx.Commit()\n\treturn token, nil\n}", "func UpdateAccessToken(mongo *mongo.Client, login, accessToken string, validUntil time.Time) error {\n\tfieldsToUpdate := primitive.D{\n\t\t{\"auth.accessToken\", accessToken},\n\t\t{\"auth.validUntil\", validUntil},\n\t}\n\n\treturn updateUser(mongo, login, fieldsToUpdate)\n}", "func (r provisionTokenClient) Update(ctx context.Context, token types.ProvisionToken) error {\n\tteleportClient, err := r.TeleportClientAccessor(ctx)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn trace.Wrap(teleportClient.UpsertToken(ctx, token))\n}", "func SetToken(Username interface{}, Signingkey []byte) string {\n\texpireToken := time.Now().Add(time.Hour * 1).Unix()\n\tjwtData := database.JwtData{\n\t\tUsername: Username,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: expireToken,\n\t\t},\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtData)\n\n\tsignedToken, _ := token.SignedString(Signingkey)\n\n\treturn signedToken\n}", "func UpdateUserToken(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tuserId := vars[\"user_id\"]\n\treq := &models.User{}\n\tif err := DecodeRequestBody(r, req); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error while decoding the request body\" + err.Error()))\n\t}\n\tif err := dal.UpdateUser(req.RegistrationToken, userId); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t}\n}", "func (u *User) SetToken(token, refreshToken string) {\n\tu.Token = token\n\tu.RefreshToken = refreshToken\n}", "func (conf *OnboardingConfig) SetToken(token string) {\n\tconf.TokenValue = token\n}", "func (v *VersionHistory) SetBranchToken(\n\tinputToken []byte,\n) error {\n\n\ttoken := make([]byte, len(inputToken))\n\tcopy(token, inputToken)\n\tv.BranchToken = token\n\treturn nil\n}", "func (transaction *TokenUpdateTransaction) SetTokenID(tokenID TokenID) *TokenUpdateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.tokenID = &tokenID\n\treturn transaction\n}", "func (as *AuthService) UserSetToken(id int, sessionToken string) (*railway.User, error) {\n\tdetails := &MethodInfo{\n\t\tName: \"UserSetToken\",\n\t\tDescription: \"UserSetToken is the DB method used to UserSetToken\",\n\t}\n\tupdatedUser := &railway.User{}\n\tquery := `\n\tUPDATE users SET session_token=$1 WHERE id=$2 \n\tRETURNING\n\t\tid,\n\t\tfirst_name,\n\t\tlast_name,\n\t\temail,\n\t\tpassword,\n\t\trole,\n\t\tsession_token,\n\t\tdata,\n\t\tclient_id,\n\t\tdisabled,\n\t\tdisabled_on,\n\t\tarchived,\n\t\tarchived_on,\n\t\tcreated_at,\n\t\tpassword_reset_token\n\t`\n\terr := as.db.QueryRow(query, sessionToken, id).Scan(updatedUser.Scan()...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, details.Name)\n\t}\n\n\treturn updatedUser, nil\n}", "func (me *TAttlistGrantListCompleteYN) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func SetAuthToken() error {\n\t// Noop if token is already set\n\tif token != \"\" {\n\t\treturn nil\n\t}\n\n\t// token is only set once, no need to mutex protect\n\tvar err error\n\ttoken, err = security.FetchAuthToken()\n\treturn err\n}", "func (m *TokenBase) SetToken(token *token32) {\n\tm.token = token\n}", "func (m *Manager) SetPasswordTokenCfg(cfg *Config) {\n\tm.gtcfg[oauth2.PasswordCredentials] = cfg\n}", "func (d *TokenStore) UpdateTokenAuth(userGUID string, tokenRecord interfaces.TokenRecord, encryptionKey []byte) error {\n\t// if isLocalCloudFoundry(tokenRecord.TokenGUID) {\n\t// \tupdates := make(map[string]string)\n\t// \tupdates[\"AccessToken\"] = fmt.Sprintf(\"bearer %s\", tokenRecord.AuthToken)\n\t// \tupdates[\"RefreshToken\"] = tokenRecord.RefreshToken\n\t// \treturn updateCFFIle(updates)\n\t// }\n\treturn d.store.UpdateTokenAuth(userGUID, tokenRecord, encryptionKey)\n}", "func (m *TokenManager) Set(ctx context.Context, subject, value string) error {\n\t_, err := sqlContext.GetQueryer(ctx, m.db).ExecContext(ctx, persistToken, subject, value)\n\treturn err\n}", "func (c *CSRFStore) setToken(token CSRFToken) {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.token = &token\n}", "func (me *TAttlistUrlType) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func (m *SessionMutation) SetToken(s string) {\n\tm.token = &s\n}", "func SetRefreshAuthTokenCallback(f func() string) func(*AviSession) error {\n\treturn func(sess *AviSession) error {\n\t\treturn sess.setRefreshAuthTokenCallback(f)\n\t}\n}", "func (c *Client) SetToken(authToken string) {\n\tc.authToken = authToken\n}", "func (c *Client) SetToken(req *http.Request) {\n\treq.Header.Set(\"X-Vault-Token\", c.token)\n}", "func (model *StormDB) UpdateTokenNodes(token common.Address, nodes []common.Address) error {\n\terr := model.db.Set(models.BucketTokenNodes, token[:], nodes)\n\treturn models.GeneratDBError(err)\n}", "func (o *SettingsObjectUpdate) HasUpdateToken() bool {\n\tif o != nil && o.UpdateToken != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Manager) SetRefreshTokenCfg(cfg *Config) {\n\tm.gtcfg[oauth2.Refreshing] = cfg\n}", "func SetToken(token string) {\n\tDefaultClient.SetToken(token)\n}", "func (m *TokenMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase token.FieldCreatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreatedAt(v)\n\t\treturn nil\n\tcase token.FieldUpdatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdatedAt(v)\n\t\treturn nil\n\tcase token.FieldValue:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetValue(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Token field %s\", name)\n}", "func UpsertToken(ctx context.Context, exec boil.ContextExecutor, tt *models.TwitchToken) error {\n\treturn tt.Upsert(ctx, exec, true, []string{models.TwitchTokenColumns.TwitchID}, tokenUpdate, boil.Infer())\n}", "func (s *MTLSAuthService) Update(ctx context.Context,\n\tconsumerUsernameOrID *string, mtlsAuth *MTLSAuth) (*MTLSAuth, error) {\n\n\tcred, err := s.client.credentials.Update(ctx, \"mtls-auth\",\n\t\tconsumerUsernameOrID, mtlsAuth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar updatedMTLS MTLSAuth\n\terr = json.Unmarshal(cred, &updatedMTLS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &updatedMTLS, nil\n}", "func (_ISettableTokenURI *ISettableTokenURITransactor) SetTokenURI(opts *bind.TransactOpts, tokenId *big.Int, uri string) (*types.Transaction, error) {\n\treturn _ISettableTokenURI.contract.Transact(opts, \"setTokenURI\", tokenId, uri)\n}", "func (s *Session) SetToken(token oauth2.Token) {\n\ts.tokenChan <- token\n}", "func (me *TAttlistELocationIDValidYN) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func setToken(u *models.User) (string, error) {\n\tt := time.Now()\n\tclaims := customClaims{\n\t\tRole: u.Role,\n\t\tActive: u.Active,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tSubject: strconv.Itoa(u.ID),\n\t\t\tExpiresAt: t.Add(expireDelay).Unix(),\n\t\t\tIssuedAt: t.Unix(),\n\t\t\tIssuer: iss}}\n\treturn getTokenString(&claims)\n}", "func SetToken(request *http.Request) error {\n\n\tif len(os.Getenv(\"LOCAL_ENVIRONMENT\")) == 0 {\n\n\t\tlog.Printf(\"[passwords] setting bearer token...\")\n\n\t\ttoken, err := bearertoken.GetToken()\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"cannot get bearer token: %s\", err.Error())\n\t\t\tlog.Printf(\"%s\", color.HiRedString(\"[passwords] %s\", msg))\n\t\t\treturn errors.New(msg)\n\t\t}\n\n\t\trequest.Header.Set(\"Authorization\", \"Bearer \"+token.Token)\n\t}\n\n\treturn nil\n}", "func (st *Store) setCtxToken(r *http.Request, t *Token) *http.Request {\n\tif nil == r || nil == t {\n\t\treturn r\n\t}\n\n\treturn r.WithContext(context.WithValue(r.Context(), st.ctxKey, t))\n}", "func (l *qpsLimiter) updateToken() {\n\tif atomic.LoadInt32(&l.limit) < atomic.LoadInt32(&l.tokens) {\n\t\treturn\n\t}\n\n\tonce := atomic.LoadInt32(&l.once)\n\n\tdelta := atomic.LoadInt32(&l.limit) - atomic.LoadInt32(&l.tokens)\n\n\tif delta > once || delta < 0 {\n\t\tdelta = once\n\t}\n\n\tnewTokens := atomic.AddInt32(&l.tokens, delta)\n\tif newTokens < once {\n\t\tatomic.StoreInt32(&l.tokens, once)\n\t}\n}", "func (a *Client) UpdateAgentToken(params *UpdateAgentTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateAgentTokenOK, *UpdateAgentTokenNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewUpdateAgentTokenParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"UpdateAgentToken\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/api/v1/orgs/{owner}/agents/{entity}/token\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &UpdateAgentTokenReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *UpdateAgentTokenOK:\n\t\treturn value, nil, nil\n\tcase *UpdateAgentTokenNoContent:\n\t\treturn nil, value, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*UpdateAgentTokenDefault)\n\treturn nil, nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (me *TAttlistDataBankListCompleteYN) Set(s string) { (*xsdt.Token)(me).Set(s) }", "func (m *MemoryTokenManager) Set(ctx context.Context, subject, token string) error {\n\tm.cache.Store(subject, token)\n\treturn nil\n}" ]
[ "0.67424035", "0.6318639", "0.6259154", "0.6147144", "0.6010651", "0.5914078", "0.58685935", "0.5868187", "0.577681", "0.566868", "0.5507102", "0.5506833", "0.5504006", "0.55024403", "0.5489404", "0.5430087", "0.53739274", "0.5315903", "0.5315727", "0.52970797", "0.5290442", "0.5286895", "0.5243094", "0.52422357", "0.52332807", "0.5218426", "0.5203493", "0.5196031", "0.51662385", "0.514928", "0.5141449", "0.51321524", "0.51210696", "0.5105874", "0.50897354", "0.50768304", "0.50768304", "0.5071886", "0.5069885", "0.50364053", "0.5000363", "0.49957642", "0.4988255", "0.49864775", "0.49848938", "0.49834165", "0.4976828", "0.4969407", "0.4952621", "0.4943254", "0.49171904", "0.49088582", "0.4894985", "0.4836705", "0.48361817", "0.48352873", "0.48318368", "0.48270324", "0.4824238", "0.48099005", "0.4794794", "0.47935572", "0.4787811", "0.47812143", "0.47693685", "0.47597882", "0.47570497", "0.47565565", "0.47298366", "0.4725619", "0.47220197", "0.47214466", "0.46781436", "0.46761551", "0.46618932", "0.46482515", "0.4629708", "0.4628551", "0.46156803", "0.45914677", "0.4584274", "0.45778444", "0.45255768", "0.45188925", "0.45159245", "0.45146203", "0.4493232", "0.44851726", "0.44664997", "0.44573748", "0.44317162", "0.44252816", "0.44222987", "0.44191697", "0.4409261", "0.4408332", "0.44033659", "0.44013286", "0.43966925", "0.4393603" ]
0.7368886
0
GetValue returns the Value field value
func (o *SettingsObjectUpdate) GetValue() map[string]interface{} { if o == nil { var ret map[string]interface{} return ret } return o.Value }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (self *FieldValue) GetValue() (interface{}, bool) {\n\tif self.StringValue != nil {\n\t\treturn *self.StringValue, true\n\t}\n\n\tif self.DoubleValue != nil {\n\t\tfv := *self.DoubleValue\n\t\tif math.IsNaN(fv) || math.IsInf(fv, 0) {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn fv, true\n\t}\n\n\tif self.Int64Value != nil {\n\t\treturn *self.Int64Value, true\n\t}\n\n\tif self.BoolValue != nil {\n\t\treturn *self.BoolValue, true\n\t}\n\n\t// TODO: should we do something here ?\n\treturn nil, true\n}", "func (f *Field) Value() interface{} {\n\treturn f.value.Interface()\n}", "func (f *Fieldx) Value() interface{} {\n\treturn f.value.Interface()\n}", "func (m *KeyValue) GetValue()(*string) {\n return m.value\n}", "func (jo *Object) GetValue(field string) (Value, bool) {\n\tjp, ok := jo.GetProperty(field)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn jp.Value, true\n}", "func (f *TagField) Value() string {\n\treturn f.value\n}", "func (f *field) Val() interface{} {\n\treturn f.v\n}", "func (options *Options) Value(name string) interface{} {\n\tvalue := options.eval.evalField(options.eval.curCtx(), name, false)\n\tif !value.IsValid() {\n\t\treturn nil\n\t}\n\n\treturn value.Interface()\n}", "func (rw *ReadWrite) GetVal() Value {\n\tpacked := rw.GetStr_()\n\tval := Unpack(packed)\n\tif trace.ClientServer.On() {\n\t\tif len(packed) < traceLimit {\n\t\t\ttrace.ClientServer.Println(\" ->\", val)\n\t\t} else {\n\t\t\ttrace.ClientServer.Println(\" ->\", val.Type())\n\t\t}\n\t}\n\treturn val\n}", "func (value *Value) Value() interface{} {\n\treturn value.value\n}", "func (node *GoValueNode) GetValue() (reflect.Value, error) {\n\n\treturn node.thisValue, nil\n}", "func (o *OutputField) GetValue() SqlExpression {\n\tif o == nil || IsNil(o.Value) {\n\t\tvar ret SqlExpression\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (o unicodeVersion) GetValue() interface{} {\n\treturn string(o)\n}", "func (n ValueReference[T]) GetValue() T {\n\treturn n.Value\n}", "func (fm *FieldModelOrder) GetValue(fbeValue *Order) error {\n fbeBegin, err := fm.GetBegin()\n if fbeBegin == 0 {\n return err\n }\n\n fbeStructSize := int(fbe.ReadUInt32(fm.buffer.Data(), fm.buffer.Offset()))\n fm.GetFields(fbeValue, fbeStructSize)\n fm.GetEnd(fbeBegin)\n return nil\n}", "func (o *AllocationVersion) GetValue() string {\n\tif o == nil || IsNil(o.Value) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (t *DataToken) GetValue() string {\n\treturn t.value\n}", "func (f *FieldHandler) Value(initZero bool) reflect.Value {\n\treturn f.field.reflectValueGetter(f.expr.ptr, initZero)\n}", "func (b *BaseElement) GetValue() string {\n\treturn b.Value\n}", "func GetValue(tv *gpb.TypedValue) (interface{}, error) {\n\tvar (\n\t\tjsondata []byte\n\t\tvalue interface{}\n\t\terr error\n\t)\n\n\tswitch tv.Value.(type) {\n\tcase *gpb.TypedValue_AsciiVal:\n\t\tvalue = tv.GetAsciiVal()\n\tcase *gpb.TypedValue_BoolVal:\n\t\tvalue = tv.GetBoolVal()\n\tcase *gpb.TypedValue_BytesVal:\n\t\tvalue = tv.GetBytesVal()\n\tcase *gpb.TypedValue_DecimalVal:\n\t\tvalue = float64(tv.GetDecimalVal().Digits) / math.Pow(10, float64(tv.GetDecimalVal().Precision))\n\tcase *gpb.TypedValue_FloatVal:\n\t\tvalue = tv.GetFloatVal()\n\tcase *gpb.TypedValue_IntVal:\n\t\tvalue = tv.GetIntVal()\n\tcase *gpb.TypedValue_StringVal:\n\t\tvalue = tv.GetStringVal()\n\tcase *gpb.TypedValue_UintVal:\n\t\tvalue = tv.GetUintVal()\n\tcase *gpb.TypedValue_JsonIetfVal:\n\t\tjsondata = tv.GetJsonIetfVal()\n\tcase *gpb.TypedValue_JsonVal:\n\t\tjsondata = tv.GetJsonVal()\n\tcase *gpb.TypedValue_LeaflistVal:\n\t\telems := tv.GetLeaflistVal().GetElement()\n\t\tvalue, err = getLeafList(elems)\n\tdefault:\n\t\terr = fmt.Errorf(\"unknown value type %+v\", tv.Value)\n\t}\n\n\tif jsondata != nil {\n\t\terr = json.Unmarshal(jsondata, &value)\n\t}\n\n\treturn value, err\n}", "func (s *String) GetValue() string {\n\treturn s.value\n}", "func (x *Update) GetValue() *Value {\n\tif x != nil {\n\t\treturn x.Value\n\t}\n\treturn nil\n}", "func (s *SequenceItemValue) GetValue() interface{} { return s.elements }", "func (e *KvOrResolved) GetValue() interface{} {\n\tif e.KV != nil {\n\t\treturn e.KV\n\t} else if e.Resolved != nil {\n\t\treturn e.Resolved\n\t} else {\n\t\treturn nil\n\t}\n}", "func (f DefaultField) Value() interface{} {\n\treturn f.V\n}", "func (c CachedObject) GetValue() interface{} {\r\n\r\n\treturn c.Value\r\n}", "func (rule *GameRule) GetValue() interface{} {\n\treturn rule.value\n}", "func GetValue(db storage.Store, cmd *fsm.Command, dataType byte) (*Value, error) {\n\tk := KeyFromCommand(cmd)\n\tb, err := db.Get(k.ToBytes())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar val *Value\n\tif b == nil {\n\t\tval = WrapValue(nil, dataType)\n\t} else {\n\t\tval, err = ParseValue(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif dataType == TypeNone || val.DataType != dataType {\n\t\treturn val, ErrWrongType\n\t}\n\n\tif val.Expired() {\n\t\treturn WrapValue(nil, dataType), nil\n\t}\n\n\treturn val, nil\n}", "func (b Bitfield) GetValue(field Bitfield) uint8 {\n\tif b.Get(field) {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (m *QueryParameterMatcher) GetValue() string {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn \"\"\n}", "func (o *Domain) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (n *Node) GetValue() string {\n\treturn n.value\n}", "func (this JsonDecode) GetValue() interface{} {\n\tvar result interface{}\n\tjsonParsed, err := this.parseJson()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Iterate through all sequential fields to get value\n\tfor i := 0; i < this.fieldLen-1; i++ {\n\t\tif jsonParsed[this.fields[i]] == nil {\n\t\t\treturn nil\n\t\t}\n\t\tjsonParsed = jsonParsed[this.fields[i]].(map[string]interface{})\n\t}\n\tresult = jsonParsed[this.fields[this.fieldLen-1]]\n\treturn result\n}", "func (o *CreateRiskRulesData) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (flag *flag) GetValue() string {\n\treturn flag.FlagValue.String()\n}", "func (o *FeatureFlag) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (stringEntry *String) GetValue() interface{} {\n\treturn stringEntry.trueValue\n}", "func (d Document) Value(field string) (interface{}, bool) {\n\tif i, ok := d.data.index[field]; ok {\n\t\tvar (\n\t\t\tvalue interface{}\n\t\t\tfv = d.rv.Field(i)\n\t\t\tft = fv.Type()\n\t\t)\n\n\t\tif ft.Kind() == reflect.Ptr {\n\t\t\tif !fv.IsNil() {\n\t\t\t\tvalue = fv.Elem().Interface()\n\t\t\t}\n\t\t} else {\n\t\t\tvalue = fv.Interface()\n\t\t}\n\n\t\treturn value, true\n\t}\n\n\treturn nil, false\n}", "func (obj *BlobAttribute) GetValue() interface{} {\n\treturn obj.getValue()\n}", "func (r Record) Value(key string) interface{} {\n\tval, ok := r.values[key]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn val\n}", "func (reference *Reference) GetValue() interface{} {\n\treturn reference.resolve().GetValue()\n}", "func (o *VerifiableAddress) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (c LessThanEqual) GetValue() interface{} {\n\treturn c.Value\n}", "func (p *Pet) GetFieldValue(field *mapping.StructField) (interface{}, error) {\n\tswitch field.Index[0] {\n\tcase 0: // ID\n\t\treturn p.ID, nil\n\tcase 1: // Name\n\t\treturn p.Name, nil\n\tcase 3: // OwnerID\n\t\treturn p.OwnerID, nil\n\t}\n\treturn nil, errors.Wrapf(mapping.ErrInvalidModelField, \"provided invalid field: '%s' for given model: Pet'\", field.Name())\n}", "func Get_Value(value *vector_tile.Tile_Value) interface{} {\n\tif value.StringValue != nil {\n\t\treturn *value.StringValue\n\t} else if value.FloatValue != nil {\n\t\treturn *value.FloatValue\n\t} else if value.DoubleValue != nil {\n\t\treturn *value.DoubleValue\n\t} else if value.IntValue != nil {\n\t\treturn *value.IntValue\n\t} else if value.UintValue != nil {\n\t\treturn *value.UintValue\n\t} else if value.SintValue != nil {\n\t\treturn *value.SintValue\n\t} else if value.BoolValue != nil {\n\t\treturn *value.BoolValue\n\t} else {\n\t\treturn \"\"\n\t}\n\treturn \"\"\n}", "func (t *DefaultResolver) GetValue(id string, tag string) string {\n\treturn utils.GetTagValue(tag, t.Resolve(id))\n}", "func (f *Value) Get() interface{} {\n\t<-f.ready\n\treturn f.value\n}", "func (o *RiskRulesListAllOfData) GetValue() string {\n\tif o == nil || IsNil(o.Value) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (s DnaString) GetValue() string {\n\treturn s.Value\n}", "func (s *GoObject) Value() interface{} {\n\treturn s.data\n}", "func (o *ResourceDefinitionFilter) GetValue() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (s *section) GetValue(key interface{}) interface{} {\n\tv := s.tm.get(key, s.sec)\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.value\n}", "func (self *attain_obj_t) GetVal() float64 {\n\treturn self.Val\n}", "func (o *LabelProperties) GetValue() *string {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn o.Value\n\n}", "func GetFieldValue(v interface{}, field string) (r string) {\n\tvar immutable reflect.Value\n\timmutable = GetReflectValue(v)\n\tval := immutable.FieldByName(field)\n\tswitch val.Kind() {\n\tcase reflect.Int64, reflect.Int32, reflect.Int:\n\t\tr = fmt.Sprintf(\"%d\", val.Int())\n\tcase reflect.Float64, reflect.Float32:\n\t\tr = fmt.Sprintf(\"%.2f\", val.Float())\n\tdefault:\n\t\t// process time\n\t\tvi := val.Interface()\n\t\tif vc, ok := vi.(time.Time); ok {\n\t\t\tr = FormatTime(vc)\n\t\t\tbreak\n\t\t}\n\t\tr = fmt.Sprintf(\"%v\", val)\n\t}\n\treturn\n}", "func (fm *FinalModelStructOptional) GetValue(fbeValue *StructOptional) (int, error) {\n fm.buffer.Shift(fm.FBEOffset())\n fbeSize, err := fm.GetFields(fbeValue)\n fm.buffer.Unshift(fm.FBEOffset())\n return fbeSize, err\n}", "func (s *StructField) Value() interface{} {\n\tif s.Kind() == reflect.Ptr && s.IsZero() {\n\t\te := s.value.Type().Elem()\n\t\tif e.Kind() == reflect.Ptr {\n\t\t\treturn nil\n\t\t}\n\n\t\tz := reflect.New(e)\n\t\ts.value.Set(z)\n\t}\n\n\tif s.Kind() == reflect.Struct {\n\t\ts.value = reflect.ValueOf(s.value.Addr().Interface())\n\t}\n\n\treturn s.value.Interface()\n}", "func (u *User) GetFieldValue(field *mapping.StructField) (interface{}, error) {\n\tswitch field.Index[0] {\n\tcase 0: // ID\n\t\treturn u.ID, nil\n\tcase 1: // Name\n\t\treturn u.Name, nil\n\tcase 2: // CreatedAt\n\t\treturn u.CreatedAt, nil\n\tcase 3: // CreatedAtIso\n\t\treturn u.CreatedAtIso, nil\n\tcase 5: // MotherID\n\t\treturn u.MotherID, nil\n\tcase 7: // FatherID\n\t\treturn u.FatherID, nil\n\t}\n\treturn nil, errors.Wrapf(mapping.ErrInvalidModelField, \"provided invalid field: '%s' for given model: User'\", field.Name())\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (m *Payment) GetValue() int64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (c *IssueLabel) Value() interface{} {\n\tswitch c.oneOfField {\n\tcase \"asString\":\n\t\treturn c.asString\n\tcase \"issueLabelAsObject\":\n\t\treturn c.issueLabelAsObject\n\t}\n\treturn nil\n}", "func (fm *FieldModelFlagsSimple) GetValue(value *FlagsSimple) error {\n return fm.GetValueDefault(value, FlagsSimple(0))\n}", "func (o *Output) GetValue() string {\n\tif !o.ShowValue || o.Value == nil {\n\t\treturn \"\"\n\t}\n\tmarshaled, err := json.MarshalIndent(o.Value, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvalue := string(marshaled)\n\tif value == `null` {\n\t\treturn \"\" // types.Nil\n\t}\n\treturn value // everything else\n}", "func (o *EquipmentBaseSensor) GetValue() string {\n\tif o == nil || o.Value == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (m *Refund_TransactionInfo) GetValue() uint64 {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn 0\n}", "func (o *ViewCustomFieldTask) GetValue() map[string]interface{} {\n\tif o == nil || o.Value == nil {\n\t\tvar ret map[string]interface{}\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (m *Property) GetValue() (val interface{}, set bool) {\n\tif m.Value == nil {\n\t\treturn\n\t}\n\n\treturn *m.Value, true\n}", "func (fm *FinalModelStructBytes) GetValue(fbeValue *StructBytes) (int, error) {\n fm.buffer.Shift(fm.FBEOffset())\n fbeSize, err := fm.GetFields(fbeValue)\n fm.buffer.Unshift(fm.FBEOffset())\n return fbeSize, err\n}", "func (this *record) Value() interface{} {\n\tswitch this._Type {\n\tcase sensors.OT_DATATYPE_UDEC_0:\n\t\tif value, err := this.UintValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_UDEC_4, sensors.OT_DATATYPE_UDEC_8, sensors.OT_DATATYPE_UDEC_12, sensors.OT_DATATYPE_UDEC_16, sensors.OT_DATATYPE_UDEC_20, sensors.OT_DATATYPE_UDEC_24:\n\t\tif value, err := this.FloatValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_STRING:\n\t\tif value, err := this.StringValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_DEC_0:\n\t\tif value, err := this.IntValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tcase sensors.OT_DATATYPE_DEC_8, sensors.OT_DATATYPE_DEC_16, sensors.OT_DATATYPE_DEC_24:\n\t\tif value, err := this.FloatValue(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\tdefault:\n\t\tif value, err := this.Data(); err != nil {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn value\n\t\t}\n\t}\n}", "func (po *Post) Value(name string) (ent.Value, error) {\n\treturn po.selectValues.Get(name)\n}", "func (s *Identity) GetValue(name string) *Identity {\n\tfor _, v := range s.Values {\n\t\tif v.Name == name {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func (b *box) getFieldValue(x, y int) int {\n\treturn b.values[x+y*3]\n}", "func (self Param) Value() string { return self.value }", "func (s SortEnum) GetValue() string {\n\treturn s.value\n}", "func (t *TimeValue) GetValue() (val time.Time, ok bool) {\n\tif t == nil || t.Value == nil {\n\t\treturn time.Time{}, false\n\t}\n\treturn *t.Value, true\n}", "func (f *ExtensionField) Value() protoreflect.Value {\n\tif f.lazy != nil {\n\t\tif atomic.LoadUint32(&f.lazy.atomicOnce) == 0 {\n\t\t\tf.lazyInit()\n\t\t}\n\t\treturn f.lazy.value\n\t}\n\treturn f.value\n}", "func getValue(tv *task.Value) (types.Value, error) {\n\tvType := tv.ValType\n\tvalBytes := tv.Val\n\tval := types.ValueForType(types.TypeID(vType))\n\tif val == nil {\n\t\treturn nil, x.Errorf(\"Invalid type: %v\", vType)\n\t}\n\tif err := val.UnmarshalBinary(valBytes); err != nil {\n\t\treturn nil, err\n\t}\n\treturn val, nil\n}", "func (o *MetricsDataValue) GetValue() string {\n\tif o == nil || o.Value == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (i *Item) GetValue(field string) string {\n\tif i == nil || len(i.Fields) == 0 {\n\t\treturn \"\"\n\t}\n\n\tsectionFilter := false\n\tsectionLabel := \"\"\n\tfieldLabel := field\n\tif strings.Contains(field, \".\") {\n\t\tparts := strings.Split(field, \".\")\n\n\t\t// Test to make sure the . isn't the last character\n\t\tif len(parts) == 2 {\n\t\t\tsectionFilter = true\n\t\t\tsectionLabel = parts[0]\n\t\t\tfieldLabel = parts[1]\n\t\t}\n\t}\n\n\tfor _, f := range i.Fields {\n\t\tif sectionFilter {\n\t\t\tif f.Section != nil {\n\t\t\t\tif sectionLabel != i.SectionLabelForID(f.Section.ID) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif fieldLabel == f.Label {\n\t\t\treturn f.Value\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func (o *SmppTlv) GetValue() string {\n\tif o == nil || o.Value == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Value\n}", "func (v Value10) Get() any { return int(v) }", "func (s *Smpval) Value() reflect.Value {\n\treturn s.val\n}", "func (i *CollectionIterator) GetValue(dest interface{}) {\n\ti.get(dest)\n}", "func (e *Element) Value() interface{} {\n\treturn e.value\n}", "func (e *Element) Value() interface{} {\n\treturn e.value\n}", "func (s *solrDocument) getRawValue(field string) interface{} {\n\treturn (*s)[field]\n}", "func (this *ValueTransaction) GetValue() (result int64) {\n\tthis.valueMutex.RLock()\n\tif this.value == nil {\n\t\tthis.valueMutex.RUnlock()\n\t\tthis.valueMutex.Lock()\n\t\tdefer this.valueMutex.Unlock()\n\t\tif this.value == nil {\n\t\t\tvalue := trinary.TritsToInt(this.trits[VALUE_OFFSET:VALUE_END])\n\n\t\t\tthis.value = &value\n\t\t}\n\t} else {\n\t\tdefer this.valueMutex.RUnlock()\n\t}\n\n\tresult = *this.value\n\n\treturn\n}", "func (v *tagValuer) Value(name string) (interface{}, bool) {\n\tif value, ok := v.tags[name]; ok {\n\t\tif value == nil {\n\t\t\treturn nil, true\n\t\t}\n\t\treturn *value, true\n\t}\n\treturn nil, false\n}", "func (sv *SyncVal) Get() interface{} {\n\tsv.lock.RLock()\n\tval := sv.val\n\tsv.lock.RUnlock()\n\treturn val\n}", "func (r *Record) Value() []byte {\n\treturn r.rd.Value\n}", "func (client *Client) Value(key string) interface{} {\n\tclient.mutex.RLock()\n\tdefer client.mutex.RUnlock()\n\n\treturn client.values[key]\n}", "func (m *PublishRequest) GetValue() []byte {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn nil\n}", "func (t *TimeSeries) GetValue() interface{} {\n\treturn t.time\n}", "func (t TimeValue) Value() interface{} {\n\treturn t.value\n}" ]
[ "0.76636225", "0.75976247", "0.7425814", "0.72290695", "0.7208232", "0.7202034", "0.71837157", "0.7172454", "0.703129", "0.7008563", "0.6988478", "0.6988324", "0.69858205", "0.6977245", "0.69616526", "0.6958008", "0.69548863", "0.6954811", "0.69493246", "0.69451064", "0.69360185", "0.69310814", "0.6913948", "0.6905784", "0.690072", "0.6890453", "0.68867016", "0.68841684", "0.6882508", "0.68668014", "0.68599755", "0.68499684", "0.6838136", "0.68205446", "0.6815251", "0.68055916", "0.679749", "0.67927647", "0.6782663", "0.677924", "0.6774096", "0.67682594", "0.672081", "0.6712693", "0.67052776", "0.66819113", "0.66791093", "0.66770136", "0.6675461", "0.66717315", "0.66650105", "0.66639507", "0.6661802", "0.66584903", "0.66575426", "0.66545534", "0.6642021", "0.66411036", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.6627112", "0.66248035", "0.6606656", "0.66050243", "0.6604632", "0.6603729", "0.65904194", "0.6589896", "0.6583731", "0.6582453", "0.65743023", "0.65599525", "0.65573704", "0.6546578", "0.6530191", "0.65298057", "0.6528928", "0.6527317", "0.6527009", "0.6519836", "0.65182704", "0.65129036", "0.6512682", "0.65084916", "0.6497678", "0.6497678", "0.6492826", "0.6491075", "0.64902836", "0.6489766", "0.64890397", "0.64839476", "0.6480859", "0.64777285", "0.64720047" ]
0.0
-1
GetValueOk returns a tuple with the Value field value and a boolean to check if the value has been set.
func (o *SettingsObjectUpdate) GetValueOk() (*map[string]interface{}, bool) { if o == nil { return nil, false } return &o.Value, true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *NewData) GetValueOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *RuleActionStore) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value.Get(), o.Value.IsSet()\n}", "func (o *EnvironmentVariablePair1) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *ViewCustomFieldTask) GetValueOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *ProjectApiKey) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *DeviceParameterValue) GetValueOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *OutputField) GetValueOk() (*SqlExpression, bool) {\n\tif o == nil || IsNil(o.Value) {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *Domain) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *WidgetMarker) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *VerifiableAddress) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *CreateRiskRulesData) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *AllocationVersion) GetValueOk() (*string, bool) {\n\tif o == nil || IsNil(o.Value) {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *UploadResponse) GetValueOk() (*NFT, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *SmppTlv) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *LabelProperties) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\n\treturn o.Value, true\n}", "func (o *ResourceDefinitionFilter) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *MetricsDataValue) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *EquipmentBaseSensor) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *UiNodeInputAttributes) GetValueOk() (*interface{}, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *TeamPermissionSettingAttributes) GetValueOk() (*TeamPermissionSettingValue, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *IncomeSummaryFieldNumber) GetValueOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *InlineObject901) GetValueIfTrueOk() (AnyOfobject, bool) {\n\tif o == nil || o.ValueIfTrue == nil {\n\t\tvar ret AnyOfobject\n\t\treturn ret, false\n\t}\n\treturn *o.ValueIfTrue, true\n}", "func (o *RiskRulesListAllOfData) GetValueOk() (*string, bool) {\n\tif o == nil || IsNil(o.Value) {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *KubernetesEthernetMatcher) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *Sensorefficiency) GetValueOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *CustomVendaResultado) GetValueOk() (*CustomVenda, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *WebhooksIntegrationCustomVariableResponse) GetValueOk() (*string, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *LongProperty) GetValueOk() (*int64, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *VulnUpdateNotification) GetRecordStateValOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.RecordStateVal.Get(), o.RecordStateVal.IsSet()\n}", "func (v *Values) GetOk(key Key) (value interface{}, ok bool) {\n\tv.lock.RLock()\n\tdefer v.lock.RUnlock()\n\n\t_, found, _ := v.root.findDescendent(nil, key, false, false)\n\tif found == nil {\n\t\treturn nil, false\n\t}\n\tif found.isSet() {\n\t\treturn found.value, true\n\t}\n\treturn newValues(found.clone()), true\n}", "func (o *AssetConcentrationRisk) GetValueOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *InlineObject901) GetValueIfFalseOk() (AnyOfobject, bool) {\n\tif o == nil || o.ValueIfFalse == nil {\n\t\tvar ret AnyOfobject\n\t\treturn ret, false\n\t}\n\treturn *o.ValueIfFalse, true\n}", "func (o *CollectionOfUser) GetValueOk() ([]User, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (o *HttpDeliveryOptions) GetValueOk() (*DeliveryOverrideType, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Value, true\n}", "func (o *MicrosoftGraphModifiedProperty) GetNewValueOk() (string, bool) {\n\tif o == nil || o.NewValue == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.NewValue, true\n}", "func (b Bitfield) GetValue(field Bitfield) uint8 {\n\tif b.Get(field) {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (o *InlineObject985) GetValuesOk() (AnyOfobject, bool) {\n\tif o == nil || o.Values == nil {\n\t\tvar ret AnyOfobject\n\t\treturn ret, false\n\t}\n\treturn *o.Values, true\n}", "func (o *PayloadNullableInt64Slice) GetValueOk() (*[]int32, bool) {\n\tif o == nil || o.Value == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Value, true\n}", "func (self *FieldValue) GetValue() (interface{}, bool) {\n\tif self.StringValue != nil {\n\t\treturn *self.StringValue, true\n\t}\n\n\tif self.DoubleValue != nil {\n\t\tfv := *self.DoubleValue\n\t\tif math.IsNaN(fv) || math.IsInf(fv, 0) {\n\t\t\treturn 0, false\n\t\t}\n\t\treturn fv, true\n\t}\n\n\tif self.Int64Value != nil {\n\t\treturn *self.Int64Value, true\n\t}\n\n\tif self.BoolValue != nil {\n\t\treturn *self.BoolValue, true\n\t}\n\n\t// TODO: should we do something here ?\n\treturn nil, true\n}", "func (o *InlineObject794) GetValuesOk() (AnyOfobject, bool) {\n\tif o == nil || o.Values == nil {\n\t\tvar ret AnyOfobject\n\t\treturn ret, false\n\t}\n\treturn *o.Values, true\n}", "func (v *OrderedValues) GetOk(key []byte) ([]byte, bool) {\n\tfor _, j := range *v {\n\t\tif len(j) > 0 && bytes.Equal(j[0], key) {\n\t\t\tif len(j) > 1 {\n\t\t\t\treturn j[1], true\n\t\t\t}\n\t\t\treturn nil, true\n\t\t}\n\t}\n\treturn nil, false\n}", "func (o *SearchTagItem) GetValuesOk() ([]string, bool) {\n\tif o == nil || o.Values == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Values, true\n}", "func (o loadFromOnline) GetValue() interface{} {\n\treturn bool(o)\n}", "func (o *DnsViewparamDataData) GetViewparamValueOk() (*string, bool) {\n\tif o == nil || o.ViewparamValue == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ViewparamValue, true\n}", "func (t *TimeValue) GetValue() (val time.Time, ok bool) {\n\tif t == nil || t.Value == nil {\n\t\treturn time.Time{}, false\n\t}\n\treturn *t.Value, true\n}", "func (v Value) TryBool() (b bool, ok bool) {\n\tb, ok = v.iface.(bool)\n\treturn\n}", "func (rw *ReadWrite) ValueResult() Value {\n\tif rw.GetBool() {\n\t\treturn rw.GetVal()\n\t}\n\treturn nil\n}", "func (o *OutputField) HasValue() bool {\n\tif o != nil && !IsNil(o.Value) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (v *ValueGetter) HasValue() bool {\n\treturn v.Value != nil\n}", "func (m Maybe[T]) HasValue() bool {\n\treturn m.hasValue\n}", "func (o *StatusDescriptorDTO) GetFieldOk() (*string, bool) {\n\tif o == nil || o.Field == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Field, true\n}", "func (v *missingValue) GetBool() (bool, bool) {\n\treturn false, false\n}", "func (o *Ga4ghContinuous) GetValuesOk() ([]float64, bool) {\n\tif o == nil || o.Values == nil {\n\t\tvar ret []float64\n\t\treturn ret, false\n\t}\n\treturn *o.Values, true\n}", "func (o *EndsWithCompareOperation) GetValuesOk() (*[]string, bool) {\n\tif o == nil || o.Values == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Values, true\n}", "func (v Bool) Value() (driver.Value, error) {\n\tif !v.present {\n\t\treturn nil, nil\n\t}\n\treturn v.v, nil\n}", "func (o *DeferredResultVoid) GetSetOrExpiredOk() (*bool, bool) {\n\tif o == nil || o.SetOrExpired == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SetOrExpired, true\n}", "func (o *FiltersNet) GetTagValuesOk() ([]string, bool) {\n\tif o == nil || o.TagValues == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.TagValues, true\n}", "func (val Value) IsKnown() bool {\n\treturn val.value != UnknownValue\n}", "func (o offlineFallback) GetValue() interface{} {\n\treturn bool(o)\n}", "func GetBoolVal(val *bool) (bool, bool) {\n\tif val != nil {\n\t\treturn *val, true\n\t}\n\n\treturn false, false\n}", "func (o *InlineObject901) GetValueIfTrue() AnyOfobject {\n\tif o == nil || o.ValueIfTrue == nil {\n\t\tvar ret AnyOfobject\n\t\treturn ret\n\t}\n\treturn *o.ValueIfTrue\n}", "func (nb NullBool) Value() (driver.Value, error) {\n\tif nb.Valid == false || nb.isSet == false {\n\t\treturn nil, nil\n\t}\n\treturn nb.Bool, nil\n}", "func (value *Value) BoolValue() bool {\n\tif value.valueType == Bool {\n\t\treturn value.value.(bool)\n\t}\n\n\tpanic(fmt.Sprintf(\"requested bool value but found %T type\", value.value))\n}", "func (b *Bool) Value() bool {\n\t// generate nil checks and faults early.\n\tref := &b.i\n\treturn atomic.LoadUint64(ref) == 1\n}", "func (o *FiltersVirtualGateway) GetTagValuesOk() ([]string, bool) {\n\tif o == nil || o.TagValues == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.TagValues, true\n}", "func (n BoolWrapper) Value() (Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn n.Bool, nil\n}", "func (o *FiltersVmGroup) GetTagValuesOk() (*[]string, bool) {\n\tif o == nil || o.TagValues == nil {\n\t\treturn nil, false\n\t}\n\treturn o.TagValues, true\n}", "func (o *ServerName) GetValueOverrideOk() (*string, bool) {\n\tif o == nil || o.ValueOverride == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ValueOverride, true\n}", "func (v *Value) Bool() bool {\n return Util.ToBool(v.data)\n}", "func (o *SyntheticsGlobalVariableParseTestOptions) GetFieldOk() (*string, bool) {\n\tif o == nil || o.Field == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Field, true\n}", "func (o *NewData) HasValue() bool {\n\tif o != nil && o.Value != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *CustomVendaResultado) GetOk() bool {\n\tif o == nil || o.Ok == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Ok\n}", "func getBoolValue(val *bool) bool {\n\tif val == nil {\n\t\treturn false\n\t}\n\n\treturn *val\n}", "func boolValue(thing interface{}) (value, isBool bool) {\n\tfield := reflect.ValueOf(thing)\n\n\tswitch field.Kind() {\n\tcase reflect.Bool:\n\t\tvalue = field.Bool()\n\t\tisBool = true\n\tdefault:\n\t\tvalue = false\n\t\tisBool = false\n\t}\n\n\treturn\n}", "func BoolValue(t bool) Value {\n\tif t {\n\t\treturn Value{Typ: ':', IntegerV: 1}\n\t}\n\treturn Value{Typ: ':', IntegerV: 0}\n}", "func (a AttributeValue) BoolVal() bool {\n\treturn a.orig.GetBoolValue()\n}", "func (fm *FieldModelFlagsSimple) GetValue(value *FlagsSimple) error {\n return fm.GetValueDefault(value, FlagsSimple(0))\n}", "func (v *Value) Valid() bool {\n return v.data != nil\n}", "func Value(c cell.I) bool {\n\tb, ok := c.(I)\n\tif !ok {\n\t\treturn c != pair.Null\n\t}\n\n\treturn b.Bool()\n}", "func (p *Property) ValueBool() bool {\n\treturn p.vbool\n}", "func (v Value) Bool() bool {\n\treturn v.Integer() != 0\n}", "func (o *TeamPermissionSettingAttributes) HasValue() bool {\n\treturn o != nil && o.Value != nil\n}", "func (o *FiltersNatService) GetTagValuesOk() ([]string, bool) {\n\tif o == nil || o.TagValues == nil {\n\t\tvar ret []string\n\t\treturn ret, false\n\t}\n\treturn *o.TagValues, true\n}", "func (v Value) Bool() bool {\n\treturn v.v.Bool()\n}", "func (o *SecretValue) GetTypeOk() (*string, bool) {\n\tif o == nil || o.Type == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Type, true\n}", "func (v *Value) Bool() bool {\n\treturn (bool)(C.value_get_bool(v.value))\n}", "func ValGetBool(model ModelT, yval *YvalT, val *int32) int32 {\n\treturn int32(C.yices_val_get_bool(ymodel(model), (*C.yval_t)(yval), (*C.int32_t)(val)))\n}", "func (m *Option) GetValue() (val string, set bool) {\n\tif m.Value == nil {\n\t\treturn\n\t}\n\n\treturn *m.Value, true\n}", "func (o *OptionalVal[T]) Get() (v T, present bool) {\n\treturn o.v, o.present\n}", "func (o *SmppTlv) HasValue() bool {\n\tif o != nil && o.Value != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func BoolValue(v Value) (bool, bool) {\n\tif v.Type() != BoolType {\n\t\treturn false, false\n\t}\n\tval, ok := (v.Value()).(bool)\n\treturn val, ok\n}", "func (s *StringValue) GetValue() (val string, ok bool) {\n\tif s == nil || s.Value == nil {\n\t\treturn \"\", false\n\t}\n\treturn *s.Value, true\n}", "func GetBoolValue(model ModelT, t TermT, val *int32) int32 {\n\treturn int32(C.yices_get_bool_value(ymodel(model), C.term_t(t), (*C.int32_t)(val)))\n}", "func hasValue(fl FieldLevel) bool {\n\tfield := fl.Field()\n\tswitch field.Kind() {\n\tcase reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:\n\t\treturn !field.IsNil()\n\tdefault:\n\t\tif fl.(*validate).fldIsPointer && field.Interface() != nil {\n\t\t\treturn true\n\t\t}\n\t\treturn field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface()\n\t}\n}", "func (o *FiltersSecurityGroup) GetTagValuesOk() (*[]string, bool) {\n\tif o == nil || o.TagValues == nil {\n\t\treturn nil, false\n\t}\n\treturn o.TagValues, true\n}", "func (f *Field) FieldOk(name string) (*Field, bool) {\n\tvalue := &f.value\n\t// value must be settable so we need to make sure it holds the address of the\n\t// variable and not a copy, so we can pass the pointer to strctVal instead of a\n\t// copy (which is not assigned to any variable, hence not settable).\n\t// see \"https://blog.golang.org/laws-of-reflection#TOC_8.\"\n\tif f.value.Kind() != reflect.Ptr {\n\t\ta := f.value.Addr()\n\t\tvalue = &a\n\t}\n\tv := strctVal(value.Interface())\n\tt := v.Type()\n\n\tfield, ok := t.FieldByName(name)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\treturn &Field{\n\t\tfield: field,\n\t\tvalue: v.FieldByName(name),\n\t}, true\n}", "func (o *CustomVendaResultado) HasValue() bool {\n\tif o != nil && o.Value != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *DeviceParameterValue) HasValue() bool {\n\tif o != nil && o.Value != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (b Bool) Value() (driver.Value, error) {\n\tif !b.Valid {\n\t\treturn nil, nil\n\t}\n\treturn b.Bool, nil\n\n}", "func (*InstBitCast) isValue() {}" ]
[ "0.79439557", "0.7658591", "0.76296705", "0.75834614", "0.7571527", "0.7557479", "0.7489606", "0.7477852", "0.74479353", "0.7412575", "0.7374969", "0.7360294", "0.731511", "0.72939545", "0.72445446", "0.7218862", "0.71982825", "0.7129213", "0.7062646", "0.70069796", "0.6923643", "0.6889253", "0.68649167", "0.6854203", "0.6839635", "0.683666", "0.68246347", "0.68239367", "0.677302", "0.67470187", "0.6600252", "0.6475496", "0.646853", "0.642605", "0.6403909", "0.63772815", "0.6310984", "0.62596613", "0.6244303", "0.62359697", "0.62342536", "0.61473495", "0.61020344", "0.60582626", "0.6055354", "0.60458624", "0.6006764", "0.5965063", "0.5957326", "0.5950721", "0.5937234", "0.59337974", "0.5905508", "0.58892506", "0.5887647", "0.5872327", "0.58673906", "0.5853634", "0.58501816", "0.5820814", "0.58075416", "0.58041793", "0.5800523", "0.5793059", "0.5773374", "0.5771109", "0.57661515", "0.5763644", "0.5761619", "0.57587093", "0.57509166", "0.57373744", "0.5726358", "0.57219553", "0.5720583", "0.5718407", "0.5703339", "0.5697513", "0.56974226", "0.5696219", "0.5693386", "0.56833875", "0.56721336", "0.56579524", "0.56571704", "0.56539905", "0.5652541", "0.5644178", "0.56418264", "0.560582", "0.5603712", "0.5600179", "0.560008", "0.5599055", "0.5595499", "0.5594492", "0.5586676", "0.5574575", "0.5561489", "0.5555474" ]
0.7664978
1
SetValue sets field value
func (o *SettingsObjectUpdate) SetValue(v map[string]interface{}) { o.Value = v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Field) SetValue(newValue interface{}) {\n\tf.Call(\"setValue\", newValue)\n}", "func (field *Field) SetValue(parser *ArgParse, args ...string) (size int, err error) {\n\tsize = 1\n\t// the basic setter\n\tif size, err = field.setValue(field.Value, args...); err != nil {\n\t\treturn\n\t}\n\n\tif fn := GetCallback(parser.Value, field.Callback); fn != nil {\n\t\tlog.Debug(\"try execute %v\", field.Callback)\n\t\t// trigger the callback, exit when callback return true\n\t\tif fn(parser) && ExitWhenCallback {\n\t\t\tlog.Info(\"execute callback %v, and exit 0\", field.Callback)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfield.BeenSet = true\n\tif field.Value.Kind() == reflect.Ptr && field.Value.Elem().Kind() == reflect.Slice {\n\t\t// can set repeat\n\t\tfield.BeenSet = false\n\t}\n\tlog.Info(\"set %v as %v (%d)\", field.Name, field.Value, size)\n\treturn\n}", "func (o *Wfmagent) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Wfmbushorttermforecastimportcompletetopicbuforecastmodification) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Integrationtype) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Workitemwrapup) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (m *ModelStructRecord) SetField(name string, value reflect.Value) {\n\tif name == \"\" {\n\t\treturn\n\t}\n\tfieldValue := m.FieldValues[name]\n\t//if value.Kind() == reflect.Ptr {\n\t//\tpanic(\"RecordFieldSetError: value cannot be a ptr\")\n\t//}\n\tif fieldValue.IsValid() == false {\n\t\tm.VirtualFieldValues[name] = reflect.New(m.model.GetFieldWithName(name).StructField().Type).Elem()\n\t\tfieldValue = m.VirtualFieldValues[name]\n\t}\n\t//fieldValue = LoopIndirectAndNew(fieldValue)\n\tsafeSet(fieldValue, value)\n}", "func (field *Field) Set(value interface{}) (err error) {\n if !field.Field.IsValid() {\n return errors.New(\"field value not valid\")\n }\n\n if !field.Field.CanAddr() {\n return ErrUnaddressable\n }\n\n reflectValue, ok := value.(reflect.Value)\n if !ok {\n reflectValue = reflect.ValueOf(value)\n }\n\n fieldValue := field.Field\n if reflectValue.IsValid() {\n if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n fieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n } else {\n if fieldValue.Kind() == reflect.Ptr {\n if fieldValue.IsNil() {\n fieldValue.Set(reflect.New(field.Struct.Type.Elem()))\n }\n fieldValue = fieldValue.Elem()\n }\n\n if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n fieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n } else if scanner, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {\n v := reflectValue.Interface()\n if valuer, ok := v.(driver.Valuer); ok {\n if v, err = valuer.Value(); err == nil {\n err = scanner.Scan(v)\n }\n } else {\n err = scanner.Scan(v)\n }\n } else {\n err = fmt.Errorf(\"could not convert argument of field %s from %s to %s\", field.Name, reflectValue.Type(), fieldValue.Type())\n }\n }\n } else {\n field.Field.Set(reflect.Zero(field.Field.Type()))\n }\n\n field.IsBlank = isBlank(field.Field)\n return err\n}", "func (o *Contentmanagementworkspacedocumentstopicdocumentdatav2) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (r *Record) SetValue(fid int, val *Value) {\n\tif len(r.Fields) == 0 {\n\t\tr.Fields = make(map[int]*Value)\n\t}\n\tr.Fields[fid] = val\n}", "func (f *TagField) SetValue(v string) {\n\tf.value = v\n}", "func (o *Wfmintradaydataupdatetopicintradayhistoricalqueuedata) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (f *Field) Set(val interface{}) error {\n\t// we can't set unexported fields, so be sure this field is exported\n\tif !f.IsExported() {\n\t\treturn errNotExported\n\t}\n\n\t// do we get here? not sure...\n\tif !f.value.CanSet() {\n\t\treturn errNotSettable\n\t}\n\n\tgiven := reflect.ValueOf(val)\n\n\tif f.value.Kind() != given.Kind() {\n\t\treturn fmt.Errorf(\"wrong kind. got: %s want: %s\", given.Kind(), f.value.Kind())\n\t}\n\n\tf.value.Set(given)\n\treturn nil\n}", "func (o *Createshareresponse) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Directrouting) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (field *Field) Set(value interface{}) (err error) {\n\tif !field.Field.IsValid() {\n\t\treturn errors.New(\"field value not valid\")\n\t}\n\n\tif !field.Field.CanAddr() {\n\t\treturn ErrUnaddressable\n\t}\n\n\treflectValue, ok := value.(reflect.Value)\n\tif !ok {\n\t\treflectValue = reflect.ValueOf(value)\n\t}\n\n\tfieldValue := field.Field\n\tif reflectValue.IsValid() {\n\t\tif reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n\t\t\tfieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n\t\t} else {\n\t\t\tif fieldValue.Kind() == reflect.Ptr {\n\t\t\t\tif fieldValue.IsNil() {\n\t\t\t\t\tfieldValue.Set(reflect.New(field.Struct.Type.Elem()))\n\t\t\t\t}\n\t\t\t\tfieldValue = fieldValue.Elem()\n\t\t\t}\n\n\t\t\tif reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n\t\t\t\tfieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"could not convert argument of field %s from %s to %s\", field.Name, reflectValue.Type(), fieldValue.Type())\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfield.Field.Set(reflect.Zero(field.Field.Type()))\n\t}\n\n\treturn err\n}", "func (o *Appevent) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Webchatmemberinfo) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Oauthclientrequest) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Actionmap) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (s *LoadSaver) SetValue(id ident.Id, value interface{}) (err error) {\n\tif field, ok := s.data[id]; ok {\n\t\tfield.Value = value\n\t\ts.data[id] = field // record value back; it's not a pointer.\n\t\ts.changed = true\n\t} else if prop, ok := s.GetProperty(id); !ok {\n\t\terr = fmt.Errorf(\"couldnt find property %s.%s\", s, id)\n\t} else {\n\t\ts.data[id] = FieldValue{prop.GetType(), value}\n\t\ts.changed = true\n\t}\n\treturn\n}", "func (o *Initialconfiguration) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (f *FieldNames) SetValue(val interface{}) {\n\t*f = val.(FieldNames)\n}", "func (s *StructField) Set(v interface{}) error {\n\tif s.field.PkgPath != \"\" {\n\t\treturn errors.New(\"Field is not exported\")\n\t}\n\n\tif !s.CanSet() {\n\t\treturn errors.New(\"Field cannot be set\")\n\t}\n\n\tgiven := reflect.ValueOf(v)\n\n\tif s.value.Kind() != given.Kind() {\n\t\treturn errors.New(\"Field and value kind don't match\")\n\t}\n\n\ts.value.Set(given)\n\treturn nil\n}", "func (o *Dialercampaignconfigchangecampaign) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func SetFieldValue(i interface{}, field string, value interface{}) {\n\tv := reflect.ValueOf(i)\n\n\tif v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {\n\t\tpanic(\"input must be a pointer to a struct\")\n\t}\n\n\tfieldVal := v.Elem().FieldByName(field)\n\n\tswitch fieldVal.Kind() {\n\tcase reflect.Bool:\n\t\tfieldVal.SetBool(value.(bool))\n\tcase reflect.Int:\n\tcase reflect.Int8:\n\tcase reflect.Int16:\n\tcase reflect.Int32:\n\tcase reflect.Int64:\n\t\tfieldVal.SetInt(value.(int64))\n\tcase reflect.Uint:\n\tcase reflect.Uint8:\n\tcase reflect.Uint16:\n\tcase reflect.Uint32:\n\tcase reflect.Uint64:\n\t\tfieldVal.SetUint(value.(uint64))\n\tcase reflect.Float32:\n\tcase reflect.Float64:\n\t\tfieldVal.SetFloat(value.(float64))\n\tcase reflect.Complex64:\n\tcase reflect.Complex128:\n\t\tfieldVal.SetComplex(value.(complex128))\n\tcase reflect.String:\n\t\tfieldVal.SetString(value.(string))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unsupported type [%s]\", fieldVal.Kind().String()))\n\t}\n}", "func (o *Compliance) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (u ConstraintUpdater) SetValue(value string) ConstraintUpdater {\n\tu.fields[string(ConstraintDBSchema.Value)] = value\n\treturn u\n}", "func setValueByName(target interface{}, fieldName string, fieldValue interface{}) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = exception.Newf(\"Error setting field: %v\", r)\n\t\t}\n\t}()\n\ttypeCheck := reflect.TypeOf(target)\n\tif typeCheck.Kind() != reflect.Ptr {\n\t\treturn exception.New(\"Cannot modify non-pointer target\")\n\t}\n\n\ttargetValue := reflectValue(target)\n\ttargetType := reflectType(target)\n\trelevantField, hasField := targetType.FieldByName(fieldName)\n\n\tif !hasField {\n\t\treturn exception.Newf(\"Field not found %s.%s\", targetType.Name(), fieldName)\n\t}\n\n\tfield := targetValue.FieldByName(relevantField.Name)\n\tfieldType := field.Type()\n\tif !field.CanSet() {\n\t\treturn exception.Newf(\"Cannot set field %s\", fieldName)\n\t}\n\n\tvalueReflected := reflectValue(fieldValue)\n\tif !valueReflected.IsValid() {\n\t\treturn exception.New(\"Reflected value is invalid, cannot continue.\")\n\t}\n\n\tif valueReflected.Type().AssignableTo(fieldType) {\n\t\tfield.Set(valueReflected)\n\t\treturn nil\n\t}\n\n\tif field.Kind() == reflect.Ptr {\n\t\tif valueReflected.CanAddr() {\n\t\t\tconvertedValue := valueReflected.Convert(fieldType.Elem())\n\t\t\tif convertedValue.CanAddr() {\n\t\t\t\tfield.Set(convertedValue.Addr())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn exception.New(\"Cannot take address of value for assignment to field pointer\")\n\t}\n\n\tif fieldAsString, isString := valueReflected.Interface().(string); isString {\n\t\tvar parsedValue reflect.Value\n\t\thandledType := true\n\t\tswitch fieldType.Kind() {\n\t\tcase reflect.Int:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(intValue)\n\t\tcase reflect.Int64:\n\t\t\tint64Value, err := strconv.ParseInt(fieldAsString, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(int64Value)\n\t\tcase reflect.Uint16:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint16(intValue))\n\t\tcase reflect.Uint: //a.k.a. uint32\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint(intValue))\n\t\tcase reflect.Uint32:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint32(intValue))\n\t\tcase reflect.Uint64:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint64(intValue))\n\t\tcase reflect.Float32:\n\t\t\tfloatValue, err := strconv.ParseFloat(fieldAsString, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(floatValue)\n\t\tcase reflect.Float64:\n\t\t\tfloatValue, err := strconv.ParseFloat(fieldAsString, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(floatValue)\n\t\tdefault:\n\t\t\thandledType = false\n\t\t}\n\t\tif handledType {\n\t\t\tfield.Set(parsedValue)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tconvertedValue := valueReflected.Convert(fieldType)\n\tif convertedValue.IsValid() && convertedValue.Type().AssignableTo(fieldType) {\n\t\tfield.Set(convertedValue)\n\t\treturn nil\n\t}\n\n\treturn exception.New(\"Couldnt set field %s.%s\", targetType.Name(), fieldName)\n}", "func (r *Record) SetValue(value string) {\n\tr.Value = value\n}", "func (d Document) SetValue(field string, value interface{}) bool {\n\tif i, ok := d.data.index[field]; ok {\n\t\tvar (\n\t\t\trv reflect.Value\n\t\t\trt reflect.Type\n\t\t\tfv = d.rv.Field(i)\n\t\t\tft = fv.Type()\n\t\t)\n\n\t\tswitch v := value.(type) {\n\t\tcase nil:\n\t\t\trv = reflect.Zero(ft)\n\t\tcase reflect.Value:\n\t\t\trv = reflect.Indirect(v)\n\t\tdefault:\n\t\t\trv = reflect.Indirect(reflect.ValueOf(value))\n\t\t}\n\n\t\trt = rv.Type()\n\n\t\tif fv.Type() == rt || rt.AssignableTo(ft) {\n\t\t\tfv.Set(rv)\n\t\t\treturn true\n\t\t}\n\n\t\tif rt.ConvertibleTo(ft) {\n\t\t\treturn setConvertValue(ft, fv, rt, rv)\n\t\t}\n\n\t\tif ft.Kind() == reflect.Ptr {\n\t\t\treturn setPointerValue(ft, fv, rt, rv)\n\t\t}\n\t}\n\n\treturn false\n}", "func (r *Wrapper) Set(name string, val any) error {\n\tfv := r.rv.FieldByName(name)\n\tif !fv.IsValid() {\n\t\treturn errors.New(\"field not found\")\n\t}\n\n\tif !fv.CanSet() {\n\t\treturn errors.New(\"field can not set value\")\n\t}\n\n\tfv.Set(reflect.ValueOf(val))\n\treturn nil\n}", "func setFieldValue(field *reflect.Value, value reflect.Value) {\n\tswitch field.Type().Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tfield.SetInt(int64(value.Float()))\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tfield.SetUint(uint64(value.Float()))\n\tdefault:\n\t\tfield.Set(value)\n\t}\n}", "func setField(obj interface{}, name string, value interface{}) error {\n\tstructValue := reflect.ValueOf(obj).Elem()\n\tstructFieldValue := structValue.FieldByName(name)\n\n\tif !structFieldValue.IsValid() {\n\t\treturn fmt.Errorf(\"No such field: %s in obj\", name)\n\t}\n\n\tif !structFieldValue.CanSet() {\n\t\treturn fmt.Errorf(\"Cannot set %s field value\", name)\n\t}\n\n\tstructFieldType := structFieldValue.Type()\n\n\tvar val reflect.Value\n\tswitch structFieldType.String() {\n\tcase \"int\":\n\t\ti, _ := strconv.Atoi(value.(js.Value).String())\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"float64\":\n\t\ti, _ := strconv.ParseFloat(value.(js.Value).String(), 64)\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"bool\":\n\t\ti, _ := strconv.ParseBool(value.(js.Value).String())\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"string\":\n\t\tval = reflect.ValueOf(value.(js.Value).String())\n\t\tbreak\n\tdefault:\n\t\tval = reflect.ValueOf(value)\n\t\tbreak\n\t}\n\n\tstructFieldValue.Set(val)\n\treturn nil\n}", "func (o *Posttextresponse) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func SetField(obj interface{}, name string, value interface{}) error {\n\tstructValue := reflect.ValueOf(obj).Elem()\n\tstructFieldValue := structValue.FieldByName(name)\n\n\tif !structFieldValue.IsValid() {\n\t\treturn fmt.Errorf(\"No such field: %s in obj\", name)\n\t}\n\n\tif !structFieldValue.CanSet() {\n\t\treturn fmt.Errorf(\"Cannot set %s field value\", name)\n\t}\n\n\tstructFieldType := structFieldValue.Type()\n\tval := reflect.ValueOf(value)\n\tif structFieldType != val.Type() {\n\t\treturn errors.New(\"Provided value type didn't match obj field type\")\n\t}\n\n\tstructFieldValue.Set(val)\n\treturn nil\n}", "func (f *Field) Set(l *Location, val string, seps *Delimeters) error {\n\tloc := l.Comp\n\tif loc < 0 {\n\t\tloc = 0\n\t}\n\tif x := loc - len(f.Components) + 1; x > 0 {\n\t\tf.Components = append(f.Components, make([]Component, x)...)\n\t}\n\terr := f.Components[loc].Set(l, val, seps)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.Value = f.encode(seps)\n\treturn nil\n}", "func Set(target, source interface{}) error {\n\tconverter := &Converter{\n\t\tTagName: \"field\",\n\t}\n\n\treturn converter.Convert(source, target)\n}", "func (o *Voicemailmessagestopicvoicemailmessage) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (o *Digitalcondition) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (i *Info) SetField(column string, value interface{}) error {\n\tfieldName, ok := i.Metadata.Fields[column]\n\tif !ok {\n\t\treturn fmt.Errorf(\"SetField: column %s not found in orm info\", column)\n\t}\n\tfieldValue := reflect.ValueOf(i.Obj).Elem().FieldByName(fieldName)\n\n\tif !fieldValue.Type().AssignableTo(reflect.TypeOf(value)) {\n\t\treturn fmt.Errorf(\"column %s: native value %v (%s) is not assignable to field %s (%s)\",\n\t\t\tcolumn, value, reflect.TypeOf(value), fieldName, fieldValue.Type())\n\t}\n\tfieldValue.Set(reflect.ValueOf(value))\n\treturn nil\n}", "func (b *box) setFieldValue(x, y, v int) {\n\t// Matrix conversion, see: https://stackoverflow.com/a/14015582\n\tb.values[x+y*3] = v\n}", "func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {\n\tfieldType := fi.fieldType\n\tisNative := !fi.isFielder\n\nsetValue:\n\tswitch {\n\tcase fieldType == TypeBooleanField:\n\t\tif isNative {\n\t\t\tif nb, ok := field.Interface().(sql.NullBool); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tnb.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tnb.Bool = value.(bool)\n\t\t\t\t\tnb.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(nb))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(bool)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = false\n\t\t\t\t}\n\t\t\t\tfield.SetBool(value.(bool))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField:\n\t\tif isNative {\n\t\t\tif ns, ok := field.Interface().(sql.NullString); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tns.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tns.String = value.(string)\n\t\t\t\t\tns.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(ns))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(string)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = \"\"\n\t\t\t\t}\n\t\t\t\tfield.SetString(value.(string))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField:\n\t\tif isNative {\n\t\t\tif value == nil {\n\t\t\t\tvalue = time.Time{}\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(time.Time)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfield.Set(reflect.ValueOf(value))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypePositiveBitField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := uint8(value.(uint64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypePositiveSmallIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := uint16(value.(uint64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypePositiveIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tif field.Type() == reflect.TypeOf(new(uint)) {\n\t\t\t\tv := uint(value.(uint64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t} else {\n\t\t\t\tv := uint32(value.(uint64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypePositiveBigIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := value.(uint64)\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeBitField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := int8(value.(int64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeSmallIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := int16(value.(int64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tif field.Type() == reflect.TypeOf(new(int)) {\n\t\t\t\tv := int(value.(int64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t} else {\n\t\t\t\tv := int32(value.(int64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeBigIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := value.(int64)\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType&IsIntegerField > 0:\n\t\tif fieldType&IsPositiveIntegerField > 0 {\n\t\t\tif isNative {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = uint64(0)\n\t\t\t\t}\n\t\t\t\tfield.SetUint(value.(uint64))\n\t\t\t}\n\t\t} else {\n\t\t\tif isNative {\n\t\t\t\tif ni, ok := field.Interface().(sql.NullInt64); ok {\n\t\t\t\t\tif value == nil {\n\t\t\t\t\t\tni.Valid = false\n\t\t\t\t\t} else {\n\t\t\t\t\t\tni.Int64 = value.(int64)\n\t\t\t\t\t\tni.Valid = true\n\t\t\t\t\t}\n\t\t\t\t\tfield.Set(reflect.ValueOf(ni))\n\t\t\t\t} else {\n\t\t\t\t\tif value == nil {\n\t\t\t\t\t\tvalue = int64(0)\n\t\t\t\t\t}\n\t\t\t\t\tfield.SetInt(value.(int64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeFloatField || fieldType == TypeDecimalField:\n\t\tif isNative {\n\t\t\tif nf, ok := field.Interface().(sql.NullFloat64); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tnf.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tnf.Float64 = value.(float64)\n\t\t\t\t\tnf.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(nf))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tif field.Type() == reflect.TypeOf(new(float32)) {\n\t\t\t\t\t\tv := float32(value.(float64))\n\t\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tv := value.(float64)\n\t\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = float64(0)\n\t\t\t\t}\n\t\t\t\tfield.SetFloat(value.(float64))\n\t\t\t}\n\t\t}\n\tcase fieldType&IsRelField > 0:\n\t\tif value != nil {\n\t\t\tfieldType = fi.relModelInfo.fields.pk.fieldType\n\t\t\tmf := reflect.New(fi.relModelInfo.addrField.Elem().Type())\n\t\t\tfield.Set(mf)\n\t\t\tf := mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex)\n\t\t\tfield = f\n\t\t\tgoto setValue\n\t\t}\n\t}\n\n\tif !isNative {\n\t\tfd := field.Addr().Interface().(Fielder)\n\t\terr := fd.SetRaw(value)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"converted value `%v` set to Fielder `%s` failed, err: %s\", value, fi.fullName, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn value, nil\n}", "func (f *FieldHeaderNames) SetValue(val interface{}) {\n\t*f = val.(FieldHeaderNames)\n}", "func SetValue(r interface{}, val string) error {\n\tiVal, err := ValueFromString(val, reflect.TypeOf(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecv := reflect.ValueOf(r)\n\tif recv.Type().Kind() == reflect.Ptr {\n\t\trecv = recv.Elem()\n\t}\n\n\tv := reflect.ValueOf(iVal)\n\tif v.Type().Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\trecv.Set(v)\n\treturn nil\n}", "func (o *Outcomequantilecondition) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (f *Fieldx) Set(v interface{}) error {\n\tif !f.IsExport() {\n\t\treturn ErrNotExported\n\t}\n\n\tif !f.value.CanSet() {\n\t\treturn errNotSettable\n\t}\n\n\tvv := reflect.ValueOf(v)\n\tif f.Kind() != vv.Kind() {\n\t\treturn fmt.Errorf(\"xstruct: value kind not match, want: %s but got %s\", f.Kind(), vv.Kind())\n\t}\n\n\tf.value.Set(vv)\n\n\treturn nil\n}", "func (o *Edge) SetField(field string, fieldValue interface{}) {\n\t// Get Value object for field\n\ttarget := reflect.ValueOf(o)\n\ttargetField := reflect.Indirect(target).FieldByName(field)\n\n\t// Set value\n\tif fieldValue != nil {\n\t\ttargetField.Set(reflect.ValueOf(fieldValue))\n\t} else {\n\t\t// Must create a new Value (creates **type) then get its element (*type), which will be nil pointer of the appropriate type\n\t\tx := reflect.Indirect(reflect.New(targetField.Type()))\n\t\ttargetField.Set(x)\n\t}\n\n\t// Add field to set field names list\n\tif o.SetFieldNames == nil {\n\t\to.SetFieldNames = make(map[string]bool)\n\t}\n\to.SetFieldNames[field] = true\n}", "func (v *ClassValue) setField(s *scope, name string, val Value) Value {\n\tout := v.Clone().(*ClassValue)\n\tout.Fields[name] = val\n\treturn out\n}", "func (o *ObjectRef) SetField(env *Env, fieldName string, value interface{}) error {\n\tclass, err := o.getClass(env)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvType, vClassName, err := typeOfValue(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar fieldSig string\n\tif env.preCalcSig != \"\" {\n\t\tfieldSig = env.preCalcSig\n\t\tenv.preCalcSig = \"\"\n\t} else {\n\t\tfieldSig = typeSignature(vType, vClassName)\n\t}\n\n\tfid, err := env.callGetFieldID(false, class, fieldName, fieldSig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v := value.(type) {\n\tcase bool:\n\t\tsetBooleanField(env.jniEnv, o.jobject, fid, fromBool(v))\n\tcase byte:\n\t\tsetByteField(env.jniEnv, o.jobject, fid, jbyte(v))\n\tcase uint16:\n\t\tsetCharField(env.jniEnv, o.jobject, fid, jchar(v))\n\tcase int16:\n\t\tsetShortField(env.jniEnv, o.jobject, fid, jshort(v))\n\tcase int32:\n\t\tsetIntField(env.jniEnv, o.jobject, fid, jint(v))\n\tcase int:\n\t\tsetIntField(env.jniEnv, o.jobject, fid, jint(int32(v)))\n\tcase int64:\n\t\tsetLongField(env.jniEnv, o.jobject, fid, jlong(v))\n\tcase float32:\n\t\tsetFloatField(env.jniEnv, o.jobject, fid, jfloat(v))\n\tcase float64:\n\t\tsetDoubleField(env.jniEnv, o.jobject, fid, jdouble(v))\n\tcase jobj:\n\t\tsetObjectField(env.jniEnv, o.jobject, fid, v.jobj())\n\tcase []bool, []byte, []int16, []uint16, []int32, []int, []int64, []float32, []float64:\n\t\tarray, err := env.toJavaArray(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer deleteLocalRef(env.jniEnv, array)\n\t\tsetObjectField(env.jniEnv, o.jobject, fid, jobject(array))\n\tdefault:\n\t\treturn errors.New(\"JNIGI unknown field value\")\n\t}\n\n\tif env.exceptionCheck() {\n\t\treturn env.handleException()\n\t}\n\n\treturn nil\n}", "func SetValue(v reflect.Value, value string) error {\n\tswitch indirectType(v.Type()) {\n\tcase timeType:\n\t\treturn setTime(&v, value)\n\tcase durationType:\n\t\treturn setDuration(&v, value)\n\tcase durationCustomType:\n\t\treturn setDurationCustom(&v, value)\n\t}\n\n\tswitch v.Kind() {\n\tcase reflect.String:\n\t\tv.SetString(value)\n\tcase reflect.Slice:\n\t\tsetSlice(&v, value)\n\tcase reflect.Int, reflect.Int32, reflect.Int64:\n\t\treturn setInt(&v, value)\n\tcase reflect.Uint, reflect.Uint32, reflect.Uint64:\n\t\treturn setUint(&v, value)\n\tcase reflect.Bool:\n\t\tsetBool(&v, value)\n\t}\n\n\treturn nil\n}", "func (f *ExtensionField) Set(t protoreflect.ExtensionType, v protoreflect.Value) {\n\tf.typ = t\n\tf.value = v\n\tf.lazy = nil\n}", "func setValue(fieldType reflect.Type, fieldValue reflect.Value, v string) error {\n\tif len(v) == 0 {\n\t\treturn nil\n\t}\n\tvar err error\n\tswitch k := fieldValue.Kind(); k {\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64:\n\t\tvar i int64\n\t\ti, err = strconv.ParseInt(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetInt(i)\n\tcase reflect.String:\n\t\tfieldValue.SetString(v)\n\tcase reflect.Bool:\n\t\tvar b bool\n\t\tb, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetBool(b)\n\tcase reflect.Float32, reflect.Float64:\n\t\tvar f float64\n\t\tf, err = strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetFloat(f)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tvar u uint64\n\t\tu, err = strconv.ParseUint(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetUint(u)\n\tcase reflect.Slice:\n\t\terr = setSliceValue(fieldType, fieldValue, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"turbo: not supported kind[\" + k.String() + \"]\")\n\t}\n\treturn nil\n}", "func (s *Struct) SetField(key string, to Item) (err error) {\n\treqType, ok := s.ty.Fields[key]\n\tif !ok {\n\t\treturn newError(ErrIndex, \"cannot retrieve undefined field %s\")\n\t}\n\tif !to.Type().Equals(reqType) {\n\t\treturn newError(\n\t\t\tErrType,\n\t\t\t\"field %s of type %s cannot be assigned to a %s\",\n\t\t\tkey,\n\t\t\treqType,\n\t\t\tto.Type(),\n\t\t)\n\t}\n\n\ts.value[key] = to\n\n\treturn nil\n}", "func setField(obj interface{}, name string, value interface{}) error {\n\tstructValue := reflect.ValueOf(obj).Elem()\n\tstructType := reflect.TypeOf(obj).Elem()\n\tstructFieldValue := structValue.FieldByName(name)\n\n\tfor i := 0; i < structType.NumField(); i++ {\n\t\tfield := structType.Field(i)\n\t\ttag := field.Tag.Get(\"query\")\n\n\t\tif tag == name {\n\t\t\tstructFieldValue = structValue.Field(i)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !structFieldValue.IsValid() || !structFieldValue.CanSet() {\n\t\treturn errors.New(fmt.Sprintf(\"%s is not allowed\", name))\n\t}\n\n\tstructFieldType := structFieldValue.Type()\n\tval := reflect.ValueOf(value)\n\n\tif structFieldType.Kind() == reflect.Bool {\n\t\tswitch val.String() {\n\t\tcase \"false\":\n\t\t\tstructFieldValue.SetBool(false)\n\t\t\treturn nil\n\t\tcase \"true\":\n\t\t\tstructFieldValue.SetBool(true)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn errors.New(fmt.Sprintf(\"%s must be a boolean\", name))\n\t\t}\n\t} else {\n\t\tstructFieldValue.Set(val)\n\t\treturn nil\n\t}\n}", "func (c Connector) SetValue(key string, value interface{}) {\n\terr := c.Client.Set(key, value, 0).Err()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (field *Field) setValue(value reflect.Value, args ...string) (size int, err error) {\n\tlog.Debug(\"try set value %[1]T (%#v)\", value.Interface(), args)\n\n\tswitch value.Interface().(type) {\n\tcase bool:\n\t\t// toggle the boolean\n\t\tvalue.SetBool(!value.Interface().(bool))\n\tcase int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:\n\t\t// override the integer\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass %v\", TYPE_INT)\n\t\t\treturn\n\t\t}\n\n\t\tvar val int\n\t\tif val, err = strconv.Atoi(args[0]); err != nil {\n\t\t\terr = fmt.Errorf(\"should pass %v: %v\", TYPE_INT, args[0])\n\t\t\treturn\n\t\t}\n\n\t\tif len(field.Choices) > 0 {\n\t\t\tidx := sort.SearchStrings(field.Choices, args[0])\n\t\t\tif idx == len(field.Choices) || field.Choices[idx] != args[0] {\n\t\t\t\terr = fmt.Errorf(\"%v should choice from %v\", args[0], field.Choices)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tswitch field.Value.Kind() {\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tvalue.SetInt(int64(val))\n\t\tdefault:\n\t\t\tvalue.SetUint(uint64(val))\n\t\t}\n\n\t\tsize++\n\tcase string:\n\t\t// override the string\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass %v\", TYPE_STRING)\n\t\t\treturn\n\t\t}\n\n\t\tif len(field.Choices) > 0 {\n\t\t\tidx := sort.SearchStrings(field.Choices, args[0])\n\t\t\tif idx == len(field.Choices) || field.Choices[idx] != args[0] {\n\t\t\t\terr = fmt.Errorf(\"%v should choice from %v\", args[0], field.Choices)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvalue.SetString(args[0])\n\t\tsize++\n\tcase *os.File:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass filename\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"open file %#v\", args[0])\n\n\t\tvar f *os.File\n\t\tif f, err = os.Open(args[0]); err == nil {\n\t\t\tvalue.Set(reflect.ValueOf(f))\n\t\t\tsize++\n\t\t}\n\t\treturn\n\tcase os.FileMode:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass file perm\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"set os.FileMode as %v\", args[0])\n\t\tvar perm int\n\t\tif perm, err = strconv.Atoi(args[0]); err != nil || uint64(perm)&uint64(0xFFFFFFFF00000000) != 0 {\n\t\t\tlog.Info(\"cannot set os.FileMode %#v: %v\", args[0], err)\n\t\t\terr = fmt.Errorf(\"cannot set os.FileMode %#v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(os.FileMode(uint32(perm))))\n\t\tsize++\n\tcase time.Time:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass TIME: RFC-3339 (2006-01-02T15:04:05+07:00)\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"set time.Time as %v\", args[0])\n\t\tvar timestamp time.Time\n\n\t\tif timestamp, err = time.Parse(time.RFC3339, args[0]); err != nil {\n\t\t\tlog.Info(\"should pass RFC-3339 (2006-01-02T15:04:05+07:00): %v: %v\", args[0], err)\n\t\t\terr = fmt.Errorf(\"should pass RFC-3339 (2006-01-02T15:04:05+07:00): %v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\t\tvalue.Set(reflect.ValueOf(timestamp))\n\t\tsize++\n\tcase net.Interface:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass IFACE\")\n\t\t\treturn\n\t\t}\n\n\t\tvar iface *net.Interface\n\n\t\tif iface, err = net.InterfaceByName(args[0]); err != nil {\n\t\t\terr = fmt.Errorf(\"invalid IFACE %#v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(*iface))\n\t\tsize++\n\tcase net.IP:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass IP\")\n\t\t\treturn\n\t\t}\n\n\t\tip := field.getIP(args[0])\n\t\tif ip == nil {\n\t\t\terr = fmt.Errorf(\"invalid IP: %#v\", args[0])\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(ip))\n\t\tsize++\n\tcase net.IPNet:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass CIDR\")\n\t\t\treturn\n\t\t}\n\n\t\tinet := field.getCIRD(args[0])\n\t\tif inet == nil {\n\t\t\terr = fmt.Errorf(\"invalid CIDR: %#v\", args[0])\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(*inet))\n\t\tsize++\n\tdefault:\n\t\tswitch value.Kind() {\n\t\tcase reflect.Struct:\n\t\t\t// execute sub-command\n\t\t\tif err = field.Subcommand.Parse(args...); err != nil {\n\t\t\t\t// only show the help message on the sub-command\n\t\t\t\tfield.Subcommand.HelpMessage(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tlog.Debug(\"set pointer %v: %v\", field.Name, value)\n\n\t\t\tif value.IsNil() {\n\t\t\t\tif field.Subcommand != nil {\n\t\t\t\t\tlog.Info(\"nil pointer, assign as sub-command\")\n\n\t\t\t\t\tvalue.Set(field.Subcommand.Value)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Info(\"nil pointer, new instance: %v\", value.Type())\n\n\t\t\t\t\tobj := reflect.New(value.Type().Elem())\n\t\t\t\t\tvalue.Set(obj)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif size, err = field.setValue(value.Elem(), args...); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase reflect.Slice:\n\t\t\telem := reflect.New(value.Type().Elem()).Elem()\n\t\t\tif size, err = field.setValue(elem, args...); err != nil {\n\t\t\t\terr = fmt.Errorf(\"cannot set %#v: %v\", value.Type(), err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// append to the slice\n\t\t\tvalue.Set(reflect.Append(value, elem))\n\t\tdefault:\n\t\t\tlog.Warn(\"not implemented set value: %[1]v (%[1]T)\", value.Interface())\n\t\t\terr = fmt.Errorf(\"not implemented set value: %[1]v (%[1]T)\", value.Interface())\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Debug(\"success set %v (%d)\", value, size)\n\treturn\n}", "func SetFieldValue(v interface{}, field string, newValue interface{}) interface{} {\n\tvar immutable reflect.Value\n\timmutable = GetReflectValue(v)\n\tf := immutable.FieldByName(field)\n\tif f.IsValid() && f.CanSet() {\n\t\tif f.Kind() == reflect.Int {\n\t\t\tf.SetInt(newValue.(int64))\n\t\t} else {\n\t\t\tf.Set(reflect.ValueOf(newValue))\n\t\t}\n\t}\n\treturn v\n}", "func (suo *SettingUpdateOne) SetValue(s string) *SettingUpdateOne {\n\tsuo.mutation.SetValue(s)\n\treturn suo\n}", "func setValue(fv *reflect.Value, c *Config, key string) error {\n\t// Update the value with the correct type\n\tswitch fv.Kind() {\n\tcase reflect.Int:\n\t\tval, err := c.GetInt(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetInt(int64(val))\n\tcase reflect.Float64:\n\t\tval, err := c.GetFloat(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetFloat(val)\n\tcase reflect.Bool:\n\t\tval, err := c.GetBool(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetBool(val)\n\tcase reflect.String:\n\t\tval, err := c.GetString(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetString(val)\n\t}\n\n\treturn nil\n}", "func (f *Fields) Set(s []*Field)", "func (o *Domain) SetValue(v string) {\n\to.Value = v\n}", "func (e *Element) SetValue(val interface{}) {\n\te.value = val\n}", "func (field *Field) SetField() {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t}\n\t}()\n\n\tfield.SetDefault()\n\tfield.SetName()\n\tfield.SetIgnore()\n\tfield.SetDoc()\n\t//\tfield.SetShort()\n\tfield.SetOmit()\n\tfield.SetRequired()\n\tfield.SetKeyName()\n\tfield.SetFlagName()\n\tfield.SetValueFromEnv()\n\tfield.SetType()\n\t// Must run last if referencing any info from field settings\n\tif field.UseFlags {\n\t\tfield.AddFlag()\n\t}\n}", "func (this *TriggerAction) Set(field string, value interface{}) {\n switch field {\n case \"id\":\n this.SetId(value.(int64))\n break\n case \"agentName\":\n this.agentName = value.(string)\n break\n case \"propertyName\":\n this.propertyName = value.(string)\n break\n case \"propertyValue\":\n this.propertyValue = value.(string)\n break\n }\n}", "func (df *DataFrame) SetField(name string, val starlark.Value) error {\n\tif df.frozen {\n\t\treturn fmt.Errorf(\"cannot set, DataFrame is frozen\")\n\t}\n\n\tif name == \"columns\" {\n\t\tidx, ok := val.(*Index)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"cannot assign to 'columns', wrong type\")\n\t\t}\n\t\tdf.columns = idx\n\t\treturn nil\n\t}\n\treturn starlark.NoSuchAttrError(name)\n}", "func (tuo *TagUpdateOne) SetValue(s string) *TagUpdateOne {\n\ttuo.mutation.SetValue(s)\n\treturn tuo\n}", "func (u *User) SetFieldValue(field *mapping.StructField, value interface{}) (err error) {\n\tswitch field.Index[0] {\n\tcase 0: // ID\n\t\tif v, ok := value.(int); ok {\n\t\t\tu.ID = v\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase int8:\n\t\t\tu.ID = int(v)\n\t\tcase int16:\n\t\t\tu.ID = int(v)\n\t\tcase int32:\n\t\t\tu.ID = int(v)\n\t\tcase int64:\n\t\t\tu.ID = int(v)\n\t\tcase uint:\n\t\t\tu.ID = int(v)\n\t\tcase uint8:\n\t\t\tu.ID = int(v)\n\t\tcase uint16:\n\t\t\tu.ID = int(v)\n\t\tcase uint32:\n\t\t\tu.ID = int(v)\n\t\tcase uint64:\n\t\t\tu.ID = int(v)\n\t\tcase float32:\n\t\t\tu.ID = int(v)\n\t\tcase float64:\n\t\t\tu.ID = int(v)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\t\t}\n\t\treturn nil\n\tcase 1: // Name\n\t\tif v, ok := value.(string); ok {\n\t\t\tu.Name = v\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check alternate types for the Name.\n\t\tif v, ok := value.([]byte); ok {\n\t\t\tu.Name = string(v)\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\tcase 2: // CreatedAt\n\t\tif v, ok := value.(time.Time); ok {\n\t\t\tu.CreatedAt = v\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\tcase 3: // CreatedAtIso\n\t\tif v, ok := value.(time.Time); ok {\n\t\t\tu.CreatedAtIso = v\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\tcase 5: // MotherID\n\t\tif v, ok := value.(int); ok {\n\t\t\tu.MotherID = v\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase int8:\n\t\t\tu.MotherID = int(v)\n\t\tcase int16:\n\t\t\tu.MotherID = int(v)\n\t\tcase int32:\n\t\t\tu.MotherID = int(v)\n\t\tcase int64:\n\t\t\tu.MotherID = int(v)\n\t\tcase uint:\n\t\t\tu.MotherID = int(v)\n\t\tcase uint8:\n\t\t\tu.MotherID = int(v)\n\t\tcase uint16:\n\t\t\tu.MotherID = int(v)\n\t\tcase uint32:\n\t\t\tu.MotherID = int(v)\n\t\tcase uint64:\n\t\t\tu.MotherID = int(v)\n\t\tcase float32:\n\t\t\tu.MotherID = int(v)\n\t\tcase float64:\n\t\t\tu.MotherID = int(v)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\t\t}\n\t\treturn nil\n\tcase 7: // FatherID\n\t\tif v, ok := value.(int); ok {\n\t\t\tu.FatherID = v\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase int8:\n\t\t\tu.FatherID = int(v)\n\t\tcase int16:\n\t\t\tu.FatherID = int(v)\n\t\tcase int32:\n\t\t\tu.FatherID = int(v)\n\t\tcase int64:\n\t\t\tu.FatherID = int(v)\n\t\tcase uint:\n\t\t\tu.FatherID = int(v)\n\t\tcase uint8:\n\t\t\tu.FatherID = int(v)\n\t\tcase uint16:\n\t\t\tu.FatherID = int(v)\n\t\tcase uint32:\n\t\t\tu.FatherID = int(v)\n\t\tcase uint64:\n\t\t\tu.FatherID = int(v)\n\t\tcase float32:\n\t\t\tu.FatherID = int(v)\n\t\tcase float64:\n\t\t\tu.FatherID = int(v)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.Wrapf(mapping.ErrInvalidModelField, \"provided invalid field: '%s' for the model: 'User'\", field.Name())\n\t}\n}", "func (p *Property) SetValue(v int) {\n\t// change the member value of property\n\tp.value = v\n}", "func (d Document) SetField(field string, value interface{}) error {\n\tif d.m != nil {\n\t\td.m[field] = value\n\t\treturn nil\n\t}\n\tpanic(\"unimplemented\")\n}", "func (s *Structx) Set(name string, value interface{}) error {\n\tf, ok := s.Field(name)\n\tif !ok {\n\t\treturn ErrNotField\n\t}\n\n\treturn f.Set(value)\n}", "func (d *Descriptor) SetValue(b []byte) {\n\tif d.rhandler != nil {\n\t\tpanic(\"descriptor has been configured with a read handler\")\n\t}\n\td.props |= CharRead\n\t// d.secure |= CharRead\n\td.value = make([]byte, len(b))\n\tcopy(d.value, b)\n}", "func (n *Node) SetField(field string, val interface{}) bool {\n\tfv := kit.FlatFieldValueByName(n.This, field)\n\tif !fv.IsValid() {\n\t\tlog.Printf(\"ki.SetField, could not find field %v on node %v\\n\", field, n.PathUnique())\n\t\treturn false\n\t}\n\tupdt := n.UpdateStart()\n\tok := kit.SetRobust(kit.PtrValue(fv).Interface(), val)\n\tif ok {\n\t\tbitflag.Set(n.Flags(), int(FieldUpdated))\n\t}\n\tn.UpdateEnd(updt)\n\treturn ok\n}", "func (fm *FinalModelStructOptional) Set(fbeValue *StructOptional) (int, error) {\n fm.buffer.Shift(fm.FBEOffset())\n fbeResult, err := fm.SetFields(fbeValue)\n fm.buffer.Unshift(fm.FBEOffset())\n return fbeResult, err\n}", "func (m *SettlementMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase settlement.FieldX:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetX(v)\n\t\treturn nil\n\tcase settlement.FieldY:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetY(v)\n\t\treturn nil\n\tcase settlement.FieldIsCity:\n\t\tv, ok := value.(bool)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetIsCity(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Settlement field %s\", name)\n}", "func setField(name string, field reflect.Value, usage string) {\n\tswitch field.Kind() {\n\tcase reflect.Bool:\n\t\tpflag.Bool(name, false, usage)\n\tcase reflect.Float64:\n\t\tpflag.Float64(name, 0, usage)\n\tcase reflect.Uint:\n\t\tpflag.Uint(name, 0, usage)\n\tcase reflect.String:\n\t\tpflag.String(name, \"\", usage)\n\tcase reflect.Slice:\n\t\tslice := field.Interface()\n\t\tif _, ok := slice.([]string); ok {\n\t\t\tpflag.StringSlice(name, []string{}, usage)\n\t\t} else if _, ok := slice.([]float64); ok {\n\t\t\tpflag.Float64Slice(name, []float64{}, usage)\n\t\t} else if _, ok := slice.([]uint); ok {\n\t\t\tpflag.UintSlice(name, []uint{}, usage)\n\t\t}\n\t\tpanic(\"unsupported slice type\")\n\tdefault:\n\t\tpanic(\"unsupported type\")\n\t}\n\tviper.BindPFlag(strings.ReplaceAll(name, \"-\", \".\"), pflag.Lookup(name))\n}", "func (p *Pet) SetFieldValue(field *mapping.StructField, value interface{}) (err error) {\n\tswitch field.Index[0] {\n\tcase 0: // ID\n\t\tif v, ok := value.(int); ok {\n\t\t\tp.ID = v\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase int8:\n\t\t\tp.ID = int(v)\n\t\tcase int16:\n\t\t\tp.ID = int(v)\n\t\tcase int32:\n\t\t\tp.ID = int(v)\n\t\tcase int64:\n\t\t\tp.ID = int(v)\n\t\tcase uint:\n\t\t\tp.ID = int(v)\n\t\tcase uint8:\n\t\t\tp.ID = int(v)\n\t\tcase uint16:\n\t\t\tp.ID = int(v)\n\t\tcase uint32:\n\t\t\tp.ID = int(v)\n\t\tcase uint64:\n\t\t\tp.ID = int(v)\n\t\tcase float32:\n\t\t\tp.ID = int(v)\n\t\tcase float64:\n\t\t\tp.ID = int(v)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\t\t}\n\t\treturn nil\n\tcase 1: // Name\n\t\tif v, ok := value.(string); ok {\n\t\t\tp.Name = v\n\t\t\treturn nil\n\t\t}\n\n\t\t// Check alternate types for the Name.\n\t\tif v, ok := value.([]byte); ok {\n\t\t\tp.Name = string(v)\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\tcase 3: // OwnerID\n\t\tif v, ok := value.(int); ok {\n\t\t\tp.OwnerID = v\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase int8:\n\t\t\tp.OwnerID = int(v)\n\t\tcase int16:\n\t\t\tp.OwnerID = int(v)\n\t\tcase int32:\n\t\t\tp.OwnerID = int(v)\n\t\tcase int64:\n\t\t\tp.OwnerID = int(v)\n\t\tcase uint:\n\t\t\tp.OwnerID = int(v)\n\t\tcase uint8:\n\t\t\tp.OwnerID = int(v)\n\t\tcase uint16:\n\t\t\tp.OwnerID = int(v)\n\t\tcase uint32:\n\t\t\tp.OwnerID = int(v)\n\t\tcase uint64:\n\t\t\tp.OwnerID = int(v)\n\t\tcase float32:\n\t\t\tp.OwnerID = int(v)\n\t\tcase float64:\n\t\t\tp.OwnerID = int(v)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(mapping.ErrFieldValue, \"provided invalid field type: '%T' for the field: %s\", value, field.Name())\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.Wrapf(mapping.ErrInvalidModelField, \"provided invalid field: '%s' for the model: 'Pet'\", field.Name())\n\t}\n}", "func (o *VerifiableAddress) SetValue(v string) {\n\to.Value = v\n}", "func (f Field) Set(x, y int, b bool) {\n\tf.s[y][x] = b\n}", "func (b *Bitfield) Set(field Bitfield, value bool) {\n\tif value {\n\t\t*b |= field\n\t} else {\n\t\t*b &= Bitfield(^uint8(field))\n\t}\n}", "func (k Keeper) SetValue(ctx sdk.Context, accessPath *vm_grpc.VMAccessPath, value []byte) {\n\tk.modulePerms.AutoCheck(types.PermStorageWrite)\n\n\tk.setValue(ctx, accessPath, value)\n}", "func (m *FeedMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase feed.FieldFeedID:\n\t\tv, ok := value.(uuid.UUID)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetFeedID(v)\n\t\treturn nil\n\tcase feed.FieldAudioURL:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetAudioURL(v)\n\t\treturn nil\n\tcase feed.FieldCaption:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCaption(v)\n\t\treturn nil\n\tcase feed.FieldTranscript:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetTranscript(v)\n\t\treturn nil\n\tcase feed.FieldPrivacy:\n\t\tv, ok := value.(feed.Privacy)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetPrivacy(v)\n\t\treturn nil\n\tcase feed.FieldOwnerID:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetOwnerID(v)\n\t\treturn nil\n\tcase feed.FieldCreatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreatedAt(v)\n\t\treturn nil\n\tcase feed.FieldUpdatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdatedAt(v)\n\t\treturn nil\n\tcase feed.FieldDeletedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDeletedAt(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Feed field %s\", name)\n}", "func (o *CreateRiskRulesData) SetValue(v string) {\n\to.Value = v\n}", "func (o *OutputField) SetValue(v SqlExpression) {\n\to.Value = &v\n}", "func (fm *FieldModelFlagsSimple) Set(value *FlagsSimple) error {\n return fm.SetValue(*value)\n}", "func (b *BaseElement) SetValue(value string) error {\n\tb.Value = value\n\treturn nil\n}", "func (m *SystemMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase system.FieldCreateByUser:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreateByUser(v)\n\t\treturn nil\n\tcase system.FieldUpdateByUser:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdateByUser(v)\n\t\treturn nil\n\tcase system.FieldCreateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreateTime(v)\n\t\treturn nil\n\tcase system.FieldUpdateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdateTime(v)\n\t\treturn nil\n\tcase system.FieldName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetName(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown System field %s\", name)\n}", "func (n *NullableGeneric) SetValue(data generic.T) {\n\tn.data = data\n\tn.notNull = true\n}", "func (n *Node) SetValue(value string) {\n\tn.value = value\n}", "func (o *FeatureFlag) SetValue(v string) {\n\to.Value = v\n}", "func (m *EntityMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase entity.FieldActive:\n\t\tv, ok := value.(bool)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetActive(v)\n\t\treturn nil\n\tcase entity.FieldTicker:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetTicker(v)\n\t\treturn nil\n\tcase entity.FieldName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetName(v)\n\t\treturn nil\n\tcase entity.FieldDescription:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDescription(v)\n\t\treturn nil\n\tcase entity.FieldListDate:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetListDate(v)\n\t\treturn nil\n\tcase entity.FieldDelisted:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDelisted(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Entity field %s\", name)\n}", "func (j *JetStreamRecord) SetValue(v string) *JetStreamRecord {\n\tj.value = []byte(v)\n\treturn j\n}", "func (m *BookcourseMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase bookcourse.FieldACCESS:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetACCESS(v)\n\t\treturn nil\n\tcase bookcourse.FieldPHONE:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetPHONE(v)\n\t\treturn nil\n\tcase bookcourse.FieldDETAIL:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDETAIL(v)\n\t\treturn nil\n\tcase bookcourse.FieldBOOKTIME:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetBOOKTIME(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Bookcourse field %s\", name)\n}", "func (m *AuthorizeMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase authorize.FieldProvider:\n\t\tv, ok := value.(authorize.Provider)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetProvider(v)\n\t\treturn nil\n\tcase authorize.FieldServiceID:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetServiceID(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Authorize field %s\", name)\n}", "func (o *AllocationVersion) SetValue(v string) {\n\to.Value = &v\n}", "func (m *UserMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase user.FieldCreateByUser:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreateByUser(v)\n\t\treturn nil\n\tcase user.FieldUpdateByUser:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdateByUser(v)\n\t\treturn nil\n\tcase user.FieldCreateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreateTime(v)\n\t\treturn nil\n\tcase user.FieldUpdateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdateTime(v)\n\t\treturn nil\n\tcase user.FieldAccountName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetAccountName(v)\n\t\treturn nil\n\tcase user.FieldStaffType:\n\t\tv, ok := value.(user.StaffType)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetStaffType(v)\n\t\treturn nil\n\tcase user.FieldIsOnJob:\n\t\tv, ok := value.(bool)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetIsOnJob(v)\n\t\treturn nil\n\tcase user.FieldFamilyName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetFamilyName(v)\n\t\treturn nil\n\tcase user.FieldGivenName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetGivenName(v)\n\t\treturn nil\n\tcase user.FieldDisplayName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDisplayName(v)\n\t\treturn nil\n\tcase user.FieldBirthday:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetBirthday(v)\n\t\treturn nil\n\tcase user.FieldIDNumber:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetIDNumber(v)\n\t\treturn nil\n\tcase user.FieldSex:\n\t\tv, ok := value.(user.Sex)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetSex(v)\n\t\treturn nil\n\tcase user.FieldPhoneNumber:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetPhoneNumber(v)\n\t\treturn nil\n\tcase user.FieldAddress:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetAddress(v)\n\t\treturn nil\n\tcase user.FieldStaffID:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetStaffID(v)\n\t\treturn nil\n\tcase user.FieldPersonalEmail:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetPersonalEmail(v)\n\t\treturn nil\n\tcase user.FieldIntranetWorkEmail:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetIntranetWorkEmail(v)\n\t\treturn nil\n\tcase user.FieldExtranetWorkEmail:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetExtranetWorkEmail(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown User field %s\", name)\n}", "func (m *CardMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase card.FieldCreateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreateTime(v)\n\t\treturn nil\n\tcase card.FieldUpdateTime:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdateTime(v)\n\t\treturn nil\n\tcase card.FieldSuit:\n\t\tv, ok := value.(card.Suit)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetSuit(v)\n\t\treturn nil\n\tcase card.FieldValue:\n\t\tv, ok := value.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetValue(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Card field %s\", name)\n}", "func (m *TenantMutation) SetField(name string, value ent.Value) error {\n\tswitch name {\n\tcase tenant.FieldCreatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetCreatedAt(v)\n\t\treturn nil\n\tcase tenant.FieldUpdatedAt:\n\t\tv, ok := value.(time.Time)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetUpdatedAt(v)\n\t\treturn nil\n\tcase tenant.FieldName:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetName(v)\n\t\treturn nil\n\tcase tenant.FieldDomains:\n\t\tv, ok := value.([]string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetDomains(v)\n\t\treturn nil\n\tcase tenant.FieldNetworks:\n\t\tv, ok := value.([]string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetNetworks(v)\n\t\treturn nil\n\tcase tenant.FieldTabs:\n\t\tv, ok := value.([]string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetTabs(v)\n\t\treturn nil\n\tcase tenant.FieldSSOCert:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetSSOCert(v)\n\t\treturn nil\n\tcase tenant.FieldSSOEntryPoint:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetSSOEntryPoint(v)\n\t\treturn nil\n\tcase tenant.FieldSSOIssuer:\n\t\tv, ok := value.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for field %s\", value, name)\n\t\t}\n\t\tm.SetSSOIssuer(v)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown Tenant field %s\", name)\n}", "func (tu *TagUpdate) SetValue(s string) *TagUpdate {\n\ttu.mutation.SetValue(s)\n\treturn tu\n}", "func (o *LabelProperties) SetValue(v string) {\n\n\to.Value = &v\n\n}" ]
[ "0.75090915", "0.7286455", "0.72005755", "0.7193745", "0.7144577", "0.7124791", "0.7084981", "0.70568204", "0.70139426", "0.6986351", "0.69855297", "0.6973494", "0.6951845", "0.6949988", "0.69424045", "0.6936594", "0.691344", "0.6882407", "0.68719107", "0.6864278", "0.6852965", "0.6850117", "0.68248546", "0.68217134", "0.68198216", "0.67949146", "0.6778408", "0.6765892", "0.67624825", "0.6757928", "0.67415535", "0.6731238", "0.6728946", "0.6724571", "0.67067397", "0.66735506", "0.6672639", "0.6652934", "0.66500133", "0.66253316", "0.66033804", "0.65919566", "0.65679157", "0.6566278", "0.65655696", "0.6556392", "0.6541288", "0.6518485", "0.65047324", "0.6472553", "0.6448866", "0.644674", "0.64356303", "0.64285135", "0.6389074", "0.63788307", "0.6358778", "0.63298523", "0.63172984", "0.63152254", "0.6299379", "0.62864155", "0.6274745", "0.6274663", "0.62655556", "0.62532324", "0.62434053", "0.6240733", "0.6226231", "0.62256736", "0.62089235", "0.6205093", "0.6200505", "0.61712945", "0.6170392", "0.6170015", "0.6168667", "0.615979", "0.6144432", "0.6142381", "0.61407757", "0.61357445", "0.61282885", "0.61225444", "0.61199284", "0.6113653", "0.6106403", "0.6105622", "0.6094871", "0.609078", "0.60892004", "0.60842836", "0.60753345", "0.60697883", "0.6061266", "0.6055869", "0.60546786", "0.60470533", "0.6044247", "0.6041193" ]
0.61596495
78
add1 incrementa di uno il valore passato
func add1(n int) int { return n + 1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AddOne(value int) int {\n\treturn value + 1\n}", "func AddOne(n *int32) {\n\t*n = *n + 1\n}", "func (c *Int) PlusOne() (v int) {\n\tc.mu.Lock()\n\tc.v++\n\tv = c.v\n\tc.mu.Unlock()\n\treturn\n}", "func (c *Int64) PlusOne() (v int64) {\n\tc.mu.Lock()\n\tc.v++\n\tv = c.v\n\tc.mu.Unlock()\n\treturn\n}", "func add1(x, y int64) int64", "func (c *counter) AddOne() int {\n\tc.count++\n\treturn c.count\n}", "func addOnePointer(value *int) {\n\t*value = *value + 1\n}", "func PlusOne(digits []int) []int {\n\n\treturn 0\n}", "func (s *lock) AddOne() int {\n\tvar l sync.Mutex\n\tl.Lock()\n\tdefer l.Unlock()\n\ts.value += 1\n\treturn s.value\n}", "func (r *Register) Increment() {\n\tr.Reg = (r.Reg + 1) & r.mask\n\tr.changed = true\n}", "func (sw *Statistics) PlusOne() {\n\tsw.statistics <- uint8(1)\n}", "func inc(a interface{}) (interface{}, error) {\n\treturn add(a, 1)\n}", "func Plus1(in chan int,\n\tout chan int) {\n\tfor {\n\t\tout <- (<-in) + 1\n\t}\n}", "func increment() int {\n\tx++\n\treturn x\n}", "func increment(inc *int) {\n\t*inc++\n}", "func (i *Number) Increment() {\n\ti.value++\n}", "func incFn(args []reflect.Value) []reflect.Value {\n\treturn []reflect.Value{reflect.ValueOf(args[0].Interface().(int) + 1)}\n}", "func (nuo *NodeUpdateOne) AddValue(i int) *NodeUpdateOne {\n\tif nuo.addvalue == nil {\n\t\tnuo.addvalue = &i\n\t} else {\n\t\t*nuo.addvalue += i\n\t}\n\treturn nuo\n}", "func (c *Stats) Increment(name string, tags []string) {\n\tc.Count(name, 1, tags)\n}", "func PlusOne(digits []int) []int {\n\tdigits[len(digits)-1] += 1\n\tvar proto = 0\n\tfor i := len(digits) -1; i >= 0; i-- {\n\t\tdigits[i] += proto\n\t\tif digits[i] >= 10 {\n\t\t\tdigits[i] -= 10\n\t\t\tproto = 1\n\t\t} else {\n\t\t\tproto = 0\n\t\t}\n\t}\n\tif proto > 0 {\n\t\tdigits = append([]int{1}, digits...)\n\t}\n\treturn digits\n}", "func Increment(path string, val float32) {\n\tmetrics.IncrCounter(strings.Split(path, \".\"), val)\n}", "func PlusOne(digits []int) []int {\n\tif len(digits) == 0 {\n\t\treturn digits\n\t}\n\n\tfor i := len(digits) - 1; i >= 0; i-- {\n\t\tif digits[i] != 9 {\n\t\t\tdigits[i]++\n\t\t\treturn digits\n\t\t}\n\t\tdigits[i] = 0\n\t}\n\n\treturn append([]int{1}, digits...)\n}", "func inc(n int) int {\n\tn++\n\tif Repeat > 0 {\n\t\tn %= Repeat\n\t}\n\treturn n\n}", "func inc(n int) int {\n\treturn n + 1\n}", "func (u *UserProfile) Increment(key string) int64 {\n\n\tval, ok := u.ints[key]\n\tif !ok {\n\t\tval = 0\n\t}\n\n\tval++\n\n\tu.ints[key] = val\n\treturn val\n}", "func (c *Counter) Increment() { c.n++ }", "func (counter *Counter) Increment() {\n\tcounter.count.Set(counter.count.Get().Int() + 1)\n}", "func Increment(name string) {\n\tmn := getWithNamespace(name)\n\tc := metrics.GetOrRegisterCounter(mn, nil)\n\tc.Inc(1)\n\tdebug(\"increment \" + name + \" 1\")\n}", "func (s *singleton) AddOne() int {\n\ts.count++\n\treturn s.count\n}", "func (c *Counter) Increment(addend int64) {\n\tatomic.AddInt64(&c.value, addend)\n}", "func (r *Range) Increment(args *IncrementRequest, reply *IncrementResponse) {\n\treply.NewValue, reply.Error = increment(r.engine, args.Key, args.Increment, args.Timestamp)\n}", "func (k *keeper) IncreaseCachedValueByOne(key string) error {\n\tif k.disableCaching {\n\t\treturn nil\n\t}\n\n\tclient := k.connPool.Get()\n\tdefer client.Close()\n\n\t_, err := client.Do(\"INCR\", key)\n\treturn err\n}", "func plusOne(digits []int) []int {\n\tif len(digits) == 0 {\n\t\treturn []int{1}\n\t}\n\tvar tmp []int\n\tvar ret []int\n\ti := len(digits) - 1\n\tpre := 1\n\tfor ; i >= 0; i-- {\n\t\tvalue := digits[i] + pre\n\t\tif value < 10 {\n\t\t\ttmp = append(tmp, value)\n\t\t\tbreak\n\t\t}\n\t\ttmp = append(tmp, 0)\n\t\tif i == 0 {\n\t\t\ttmp = append(tmp, 1)\n\t\t}\n\t}\n\tif i > 0 {\n\t\tfor _, d := range digits[:i] {\n\t\t\tret = append(ret, d)\n\t\t}\n\t}\n\tfor j := len(tmp) - 1; j >= 0; j-- {\n\t\tret = append(ret, tmp[j])\n\t}\n\treturn ret\n}", "func _cgoexp_e93fccc2f088_add(a *struct {\n\t\tp0 _Ctype_int\n\t\tp1 _Ctype_int\n\t\tr0 _Ctype_int\n\t}) {\n\ta.r0 = add(a.p0, a.p1)\n}", "func (ftuo *FieldTypeUpdateOne) AddInt(i int) *FieldTypeUpdateOne {\n\tif ftuo.addint == nil {\n\t\tftuo.addint = &i\n\t} else {\n\t\t*ftuo.addint += i\n\t}\n\treturn ftuo\n}", "func (c *Client) IncrementGaugeBy(stat string, value int) error {\n\treturn c.send(stat, 1, \"+%d|g\", value)\n}", "func increaseSeq(u *uint32) {\n\tif *u == math.MaxUint32 {\n\t\t*u = 1\n\t} else {\n\t\t*u++\n\t}\n}", "func PlusOneRune(r rune) rune {\n\tr += 1\n\treturn r\n}", "func increment2(inc *int) {\n\t// the * is an operator, it tells us the value of the pointer points to\n\t*inc++\n\tprintln(\"inc2:\\tValue Of[\", inc, \"]\\tAddr Of[\", &inc, \"]\\tValue Points To[\", *inc, \"]\")\n}", "func (self *IoRateValues) Increment(other IoRateValues) {\n\tself.Syscalls += other.Syscalls\n\tself.BlockBytes += other.BlockBytes\n}", "func plusOne(digits []int) []int {\n\tres := make([]int, len(digits)+1)\n\tc := 1\n\tind := len(res) - 1\n\tvar sum int\n\tfor ind >= 0 {\n\t\tif ind > 0 {\n\t\t\tsum = digits[ind-1] + c\n\t\t} else {\n\t\t\tsum = c\n\t\t}\n\n\t\tres[ind] = sum % 10\n\t\tc = sum / 10\n\t\tind--\n\t}\n\tvar start int\n\tfor ; res[start] == 0; start++ {\n\t}\n\treturn res[start:]\n\n}", "func setNextValue(d *types.Datum) {\n\tswitch d.Kind() {\n\tcase types.KindBytes, types.KindString:\n\t\td.SetBytes(kv.Key(d.GetBytes()).PrefixNext())\n\tcase types.KindInt64:\n\t\td.SetInt64(d.GetInt64() + 1)\n\tcase types.KindUint64:\n\t\td.SetUint64(d.GetUint64() + 1)\n\tcase types.KindMysqlDuration:\n\t\tduration := d.GetMysqlDuration()\n\t\tduration.Duration = duration.Duration + 1\n\t\td.SetMysqlDuration(duration)\n\tcase types.KindMysqlTime:\n\t\tt := d.GetMysqlTime()\n\t\tsc := &stmtctx.StatementContext{TimeZone: types.BoundTimezone}\n\t\tif _, err := t.Add(sc, types.Duration{Duration: 1, Fsp: 0}); err != nil {\n\t\t\tlog.Error(errors.ErrorStack(err))\n\t\t}\n\t\td.SetMysqlTime(t)\n\t}\n}", "func (s *Sparse) inc(start uint, dx int32) {\n\tfor i := start + 1; i < uint(len(s.count)); i++ {\n\t\ts.count[i] += dx\n\t}\n}", "func (self *IoValues) Increment(other IoValues) {\n\tself.Syscalls += other.Syscalls\n\tself.BlockBytes += other.BlockBytes\n}", "func add(this js.Value, args []js.Value) interface{} {\n\ta := args[0].Int()\n\tb := args[1].Int()\n\n\tthis.Set(\"result\", js.ValueOf(a+b))\n\treturn nil\n}", "func (nu *NodeUpdate) AddValue(i int) *NodeUpdate {\n\tif nu.addvalue == nil {\n\t\tnu.addvalue = &i\n\t} else {\n\t\t*nu.addvalue += i\n\t}\n\treturn nu\n}", "func (s *intSet) increment(i int) {\n\ts.members[i]++\n}", "func (lsn *LSN) inc() {\n\tlsn.Pos++\n}", "func (ic *intCounter) increment() int {\n\t*ic++\n\t// explicity type casting from intCounter to int, as Go does not perform\n\t// implicit type casting\n\treturn int(*ic)\n}", "func (obj *Object) Increment(field string) *Object {\n\treturn obj.IncrementWithAmount(field, 1)\n}", "func (self *scroll) Increment() {\n\tself.offset++\n}", "func (c *Count) Increment(by int64) {\n\tc.µ.Lock()\n\tc.val += by\n\tc.µ.Unlock()\n}", "func (m *Uint64) Increment(key interface{}) (new uint64) {\n\treturn m.Value(key).Increment()\n}", "func (f *falconGauge) Inc() {\n\tf.Add(1)\n}", "func AddOne(n *big.Int) *big.Int {\n\tresult := big.NewInt(0)\n\tresult = result.Add(n, big.NewInt(1))\n\tmax_val := ComputeMaxKey()\n\tif result.Cmp(max_val) > 0 {\n\t\treturn big.NewInt(0)\n\t}\n\treturn result\n}", "func (s *Service) Increment(path string, input map[string]interface{}) error {\n\treturn s.r.Increment(path, input)\n}", "func (d *distance) add(v int) {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\td.v += v\n}", "func Increment(y uint) uint {\n\tif y == 0 {\n\t\treturn 1\n\t}\n\tif y%2 == 1 {\n\t\treturn (2 * Increment(y/2))\n\t}\n\treturn y + 1\n}", "func (s *IPCount) Increase(ip string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif c, ok := s.value[ip]; ok {\n\t\tc++\n\t\ts.value[ip] = c\n\t\treturn\n\t}\n\n\ts.value[ip] = 1\n}", "func (c *Counter) Increase(i int64) *Counter {\n\tif c == nil {\n\t\treturn nil\n\t}\n\n\tc.val += i\n\tc.increaseBy += i\n\n\treturn c\n}", "func Add(a, operand int) int { return operand + a }", "func (v *Val) add(i Meta) {\n\tv.c++\n\tv.metadata[i.GetSeq()%len(v.metadata)] = i\n}", "func (s *Singleton) AddOne() int {\n\ts.count++\n\treturn s.count\n}", "func (g *GaugeInt64) Inc(i int64) {\n\tatomic.AddInt64(&g.val, i)\n}", "func Increment(\n\tctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,\n) (result.Result, error) {\n\targs := cArgs.Args.(*roachpb.IncrementRequest)\n\th := cArgs.Header\n\treply := resp.(*roachpb.IncrementResponse)\n\n\tnewVal, err := engine.MVCCIncrement(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, h.Txn, args.Increment)\n\treply.NewValue = newVal\n\treturn result.Result{}, err\n}", "func (c *Client) Increment(stat string, count int, rate float64) error {\n\treturn c.send(stat, rate, \"%d|c\", count)\n}", "func (b *BrainFuck) inc(v int) {\n\tb.memory.cell[b.cur()] = (b.memory.cell[b.cur()] + v) % 255\n}", "func (cc *DependenciesCallCounter) increment(name string) {\n\tif cc.Counter == nil {\n\t\tcc.Counter = make(map[string]int)\n\t}\n\tcc.Counter[name]++\n}", "func add(ctx *build.Context, x, y ir.Int, k int) ir.Int {\n\tz := ctx.Int(\"sum\", k)\n\tc := ctx.Register(\"c\")\n\tAddInto(ctx, z, x, y, c)\n\treturn z\n}", "func (u *Update) Inc(obj types.M) *Update {\n\tu.update[\"$inc\"] = obj\n\treturn u\n}", "func (be InmemBackend) Increment(key []byte, value int, create_if_not_exists bool) (int, error) {\n\treturn 0, nil\n}", "func (p *Bar) Inc(n int64) {\n\tp.Current = p.Current + n\n\tp.printBar()\n}", "func (c *Client) Increment(k uint64, v float64, t time.Duration) error {\n\treturn types.WriteMessage(c.s, types.IncrementMessage{\n\t\tKey: k,\n\t\tVal: v,\n\t\tTTE: uint32(time.Now().Add(t).Unix()),\n\t})\n}", "func (u *Update) Inc(obj utils.M) *Update {\n\tu.update[\"$inc\"] = obj\n\treturn u\n}", "func (c *counter) Inc(n uint64) {\n\tatomic.AddUint64(&c.val, n)\n}", "func Add(a, b int) (rs int) {\n\trs = a + b\n\treturn\n}", "func (m *Minutes) Increment() {\n\t*m = (*m + 1) % 60\n}", "func (ic *IntCounter) Increment() int {\n\t*ic++\n\treturn int(*ic)\n}", "func (g *PCPGauge) Inc(val float64) error {\n\tg.mutex.Lock()\n\tdefer g.mutex.Unlock()\n\n\tif val == 0 {\n\t\treturn nil\n\t}\n\n\tv := g.val.(float64)\n\treturn g.set(v + val)\n}", "func (m *Manager) incrementRef(by int64) {\n\tm.refCount.Add(by)\n}", "func (c *Client) IncrementGauge(stat string, value int, rate float64) error {\n\treturn c.send(stat, rate, \"+%d|g\", value)\n}", "func (x *intSet) add(n int) { *x |= (1 << uint(n)) }", "func (pager *pager) increment(pointer int) {\n\tpage := pager.findPage(pointer)\n\tpageAddress := pageAddress(pointer, pager.pagesize)\n\tpage[pageAddress]++\n}", "func add(x ...int) int {\n\tfmt.Println(x)\n\tfmt.Printf(\"%T\\n\", x)\n\tsum := 0\n\tfor i, v := range x {\n\t\tsum += v\n\t\tfmt.Println(\"For index pasiton \", i, \"we are adding \", v, \" and now it is \", sum)\n\n\t}\n\treturn sum\n}", "func addInc(){\r\n\tcounter++\r\n\tnewName = fileName + sepChar + fmt.Sprint(counter)\r\n\tfileName = newName\r\n}", "func (kv *fazzRedis) Increment(ctx context.Context, key string) (int64, error) {\n\treturn kv.client.Incr(ctx, key).Result()\n}", "func (c *CPU6502) inc() uint8 {\n\tc.fetch()\n\tt := uint16(c.fetched) + 1\n\tc.write(c.addrAbs, uint8(t))\n\tc.setFlagZ(uint8(t))\n\tc.setFlagN(uint8(t))\n\treturn 0\n}", "func (s *CacheServer) Increment(ctx context.Context, in *pb.CacheRequest) (*pb.CacheResponse, error) {\n\tin.Operation = pb.CacheRequest_INCREMENT\n\treturn s.Call(ctx, in)\n}", "func add(num1 int, num2 int) int {\n\treturn num1 + num2\n}", "func (w *Writer) Put1(n int) *Writer {\n\tif n < 0 || 1<<8 <= n {\n\t\tpanic(\"stor.Writer.Put1 value outside range\")\n\t}\n\tw.buf = append(w.buf,\n\t\tbyte(n))\n\treturn w\n}", "func add(a int, b int) int {\n\treturn 1\n}", "func (self *IoAmount) Increment(other *IoAmount) {\n\tself.Read.Increment(other.Read)\n\tself.Write.Increment(other.Write)\n}", "func (t *Tree) Add(i, x int) {\n\tfor i <= t.n {\n\t\tt.bit[i] += x\n\t\ti |= i + 1\n\t}\n}", "func incr_offset() {\n\toffset = offset + 1\n}", "func add(this js.Value, i []js.Value) interface{} {\n\tin1, in2 := getInputValues(i)\n\tsetValueById(i[2].String(), in1+in2)\n\treturn nil\n}", "func (c *Counter) Increment() int {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\tcurrent := c.Current\n\tc.Current = current + 1\n\n\treturn current\n}", "func Update1(fun TermT, arg1 TermT, value TermT) TermT {\n\treturn TermT(C.yices_update1(C.term_t(fun), C.term_t(arg1), C.term_t(value)))\n}", "func (c *TransactionFirestore) Increment(ctx context.Context, obj db.Object, field string, value int) error {\n\tif err := db.AssertObject(ctx, obj, true); err != nil {\n\t\treturn err\n\t}\n\tdocRef := c.client.getDocRef(obj.Collection(), obj.ID())\n\terr := c.tx.Update(docRef, []firestore.Update{\n\t\t{Path: field, Value: firestore.Increment(value)},\n\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"tx inc field \"+strconv.Itoa(value)+\" %v-%v\", obj.Collection(), obj.ID())\n\t}\n\treturn nil\n}", "func (g *PCPGaugeVector) Inc(inc float64, instance string) error {\n\tg.mutex.Lock()\n\tdefer g.mutex.Unlock()\n\n\tv, err := g.valInstance(instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn g.setInstance(v.(float64)+inc, instance)\n}", "func (c *Counter) Add(delta uint64) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ticksCurrent = atomic.LoadInt64(&ticks)\n\tc.v += delta\n\n\t// initialize previous values to current if counter\n\t// overflows or if this is our first value\n\tif c.ticksPrevious == 0 || c.p > c.v {\n\t\tc.p = c.v\n\t\tc.ticksPrevious = c.ticksCurrent\n\t}\n}" ]
[ "0.7419214", "0.699861", "0.6886042", "0.6848004", "0.68199235", "0.6738782", "0.6724739", "0.6603531", "0.65043795", "0.6482164", "0.64574945", "0.6435017", "0.64228994", "0.6383429", "0.63611907", "0.6358452", "0.63515466", "0.6329373", "0.6316779", "0.6315114", "0.6277242", "0.62086546", "0.61846423", "0.61754984", "0.6137174", "0.6133826", "0.6128027", "0.61221385", "0.6093311", "0.6067342", "0.60642016", "0.605659", "0.604866", "0.6048226", "0.604401", "0.60407484", "0.6039394", "0.6028324", "0.6012015", "0.5988438", "0.59854496", "0.5984239", "0.59732354", "0.597258", "0.5953197", "0.5945049", "0.594103", "0.5940601", "0.5936823", "0.5934871", "0.59161246", "0.5905671", "0.58973974", "0.5895078", "0.5879482", "0.5868619", "0.586816", "0.58569324", "0.5842926", "0.5839306", "0.58369327", "0.58365995", "0.5824945", "0.58159184", "0.581449", "0.57974774", "0.57928306", "0.5787247", "0.5780248", "0.57664806", "0.5752116", "0.5750063", "0.5741522", "0.57409656", "0.5733681", "0.5732445", "0.57303333", "0.57249546", "0.57244146", "0.5722855", "0.57200766", "0.5718792", "0.5717645", "0.57074225", "0.5706328", "0.56971955", "0.5690814", "0.5689395", "0.56892824", "0.56864667", "0.56839883", "0.5681444", "0.567614", "0.5675235", "0.56708115", "0.56707805", "0.5670044", "0.5663273", "0.5662735", "0.56618065" ]
0.7685829
0
EnvConfigValidator checks if the env_config json file is present and accessible If the file is missing or unable to access, then an error will be thrown
func EnvConfigValidator() error { execName, execErr := os.Executable() cwd := filepath.Dir(execName) if execErr != nil { localLogger(execErr.Error(), global.StatusError) return execErr } fileString := cwd + "/" + global.EnvFileName _, openErr := os.Open(fileString) if openErr != nil { localLogger(openErr.Error(), global.StatusError) return openErr } else { if envContent := EnvConfigFileReader(); envContent == nil { localLogger("Unable to read env file", global.StatusError) return types.Error{Msg: "Invalid content in env_config file"} } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func loadEnvironmentConfig(env string) types.Options {\n\tconfigFile := \"config/\" + ServiceName + \"/\" + env + \".json\"\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\treturn parseConfigFile(configFile)\n}", "func validateEnv() (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_, err = utils.MultiErrorList(err)\n\t\t\terr = fmt.Errorf(\"invalid environment: %w\", err)\n\t\t}\n\t}()\n\tfor _, kv := range strings.Split(emptyStringsEnv, \"\\n\") {\n\t\tif strings.TrimSpace(kv) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.Index(kv, \"=\")\n\t\tif i == -1 {\n\t\t\treturn errors.Errorf(\"malformed .env file line: %s\", kv)\n\t\t}\n\t\tk := kv[:i]\n\t\t_, ok := os.LookupEnv(k)\n\t\tif ok {\n\t\t\terr = multierr.Append(err, fmt.Errorf(\"environment variable %s must not be set: %v\", k, v2.ErrUnsupported))\n\t\t}\n\t}\n\treturn\n}", "func TestConfigIsJSON(t *testing.T) {\n\thomedir := os.Getenv(\"HOME\")\n\tconfigpath := (homedir + \"/.stalker.json\")\n\tfile, _ := os.Open(configpath)\n\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tt.Log(\"config is valid JSON\")\n\t}\n}", "func readEnviromentFile() *ServerEnv {\n\tvar serverEnv ServerEnv\n\tjsonFile, err := os.Open(\"dist/env.json\")\n\tif err != nil {\n\t\tfmt.Printf(\":0 PANIK , enviroment json not attempting local dir found\")\n\t\tjsonFile, err = os.Open(\"env.json\")\n\t\tif err != nil {\n\t\t\tpanic(\":0 PANIK , enviroment json not found\")\n\t\t}\n\t}\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\terr = json.Unmarshal(byteValue, &serverEnv)\n\tif err != nil {\n\t\tpanic(\":0 PANIK , enviroment json could not decode\")\n\t}\n\treturn &serverEnv\n}", "func loadEnvConfig(filenames ...string) bool {\n\tfor _, filename := range filenames {\n\t\tif util.Exists(filename) {\n\t\t\terr := godotenv.Load(filename)\n\n\t\t\t// if the config file cannot be read we want to know about it\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err.Error())\n\t\t\t} else {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func validateConfig() {\n\tif viper.Get(\"project\") == \"\" {\n\t\tlog.Fatal(\"Error: --project is required\")\n\t}\n\tif viper.Get(\"region\") == \"\" {\n\t\tlog.Fatal(\"Error: --region is required, e.g. us-west1\")\n\t}\n}", "func validateConfig(args ArgCollection) error {\n\texpectedKeys := []string{}\n\tconfigFileRequired := false\n\tif args.ProviderFlag == \"custom\" {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"providers.custom.insecure\", \"providers.custom.endpoint_format\", \"providers.custom.regions\", \"providers.custom.address_style\"}...)\n\t}\n\tif args.WriteToDB {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"db.uri\"}...)\n\t}\n\tif args.UseMq {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"mq.queue_name\", \"mq.uri\"}...)\n\t}\n\t// User didn't give any arguments that require the config file\n\tif !configFileRequired {\n\t\treturn nil\n\t}\n\n\t// Try to find and read config file\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treturn errors.New(\"config file not found\")\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Verify all expected keys are in the config file\n\tfor _, k := range expectedKeys {\n\t\tif !viper.IsSet(k) {\n\t\t\treturn fmt.Errorf(\"config file missing key: %s\", k)\n\t\t}\n\t}\n\treturn nil\n}", "func TestConfigExists(t *testing.T) {\n\thomedir := os.Getenv(\"HOME\")\n\tconfigpath := (homedir + \"/.stalker.json\")\n\n\tif _, err := os.Stat(configpath); os.IsNotExist(err) {\n\t\tt.Error(configpath + \" not found!\")\n\t} else {\n\t\tt.Log(\"found config \" + configpath)\n\t}\n}", "func ValidateConfig() {\n\tconfig := GetConfig()\n\n\t// list of required keys\n\t// if these do not exist, prevent running the app\n\trequiredKeys := []string{\n\t\t\"app.core.root_directory\",\n\t\t\"app.core.log_level\",\n\t\t\"app.core.rest.url\",\n\t\t\"app.core.rest.user\",\n\t\t\"app.core.rest.xor_key\",\n\t\t\"app.core.rest.password\",\n\t\t\"app.core.rest.masked\",\n\t\t\"app.core.db.initialised\",\n\t\t\"app.core.db.path\",\n\t}\n\n\tfor _, key := range requiredKeys {\n\t\tif !config.IsSet(key) {\n\t\t\tlog.WithFields(log.Fields{\"error\": fmt.Sprintf(\"The key %s is required, but could not be found! See the sample file for reference!\", key)}).Error(\"Invalid config file detected!\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func CheckEnvVars() {\n\tenvvars := []string{\"AWS_ACCESS_KEY_ID\", \"AWS_SECRET_ACCESS_KEY\", \"AWS_STORAGE_BUCKET_NAME\", \"AWS_CONFIG_FILE\", \"FETCH_ID\", \"FETCH_OFFSET\", \"FETCH_LIMIT\"}\n\tfor _, envvar := range envvars {\n\t\tif os.Getenv(envvar) == \"\" {\n\t\t\tpanic(fmt.Errorf(\"environment variable `%s` is missing or empty,\", envvar))\n\t\t}\n\t}\n}", "func (e *Environment) Validate() error {\n\tif e.Name == \"\" {\n\t\treturn fmt.Errorf(\"'environment.name' is mandatory\")\n\t}\n\tif !isAlphaNumeric(e.Name) {\n\t\treturn fmt.Errorf(\"'environment.name' only allows alphanumeric characters\")\n\t}\n\tif e.Provider == nil {\n\t\treturn nil\n\t}\n\tif err := e.Provider.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif e.DNSProvider == nil {\n\t\tif e.Provider.HostedZone == \"\" {\n\t\t\treturn fmt.Errorf(\"'environment.provider.hosted_zone' must be defined if no dns provider is defined\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn e.DNSProvider.Validate()\n}", "func ProcessEnvConfigOrDie(env interface{}) {\n\tif env == nil {\n\t\treturn\n\t}\n\tif err := envconfig.Process(\"\", env); err != nil {\n\t\tlog.Fatal(\"Failed to process env var\", err)\n\t}\n\tlog.Printf(\"Running with env: %+v\", env)\n}", "func readFromENV() (err error) {\n\tlog.Println(\"Looking for ENV configuration\")\n\n\terr = envconfig.Process(\"PS\", &Config)\n\n\tif err == nil && Config.isMissing() {\n\t\terr = errors.New(\"Configuration is missing\")\n\t} else {\n\t\tlog.Println(\"ENV configuration has been read successfully\")\n\t}\n\n\treturn err\n}", "func initEnvironmentsFile() {\n\tabs, err := filepath.Abs(viper.GetString(\"environments-config\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tenvironmentsFile = environment.EnvironmentsFile{\n\t\tPath: abs,\n\t}\n\n\tif _, err = os.Stat(environmentsFile.Path); errors.Is(err, os.ErrNotExist) {\n\t\tenvironmentsFile.Environments = environment.Environments{}\n\t\treturn\n\t}\n\n\tif err = environmentsFile.Read(); err == nil {\n\t\treturn\n\t} else {\n\t\tlog.Fatal(\"Unable to read environments file\")\n\t}\n}", "func (config *configuration) getEnvVariables() error {\n\t// method 1: Decode json file\n\tfile, err := os.Open(confFile)\n\tif err != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Open config file error.\", err)\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoderErr := decoder.Decode(&config)\n\tif decoderErr != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Decode config file error.\", decoderErr)\n\t\treturn decoderErr\n\t}\n\n\t// method 2: Unmarshal json file\n\t// jsonData, err := ioutil.ReadFile(confFile)\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// unmarshalErr := json.Unmarshal(jsonData, &config)\n\t// if unmarshalErr != nil {\n\t// \treturn unmarshalErr\n\t// }\n\treturn nil\n}", "func (l Logging) validate() error {\n\tif l.IsEmpty() {\n\t\treturn nil\n\t}\n\tif l.EnvFile != nil {\n\t\tenvFile := aws.StringValue(l.EnvFile)\n\t\tif filepath.Ext(envFile) != envFileExt {\n\t\t\treturn fmt.Errorf(\"environment file %s must have a %s file extension\", envFile, envFileExt)\n\t\t}\n\t}\n\treturn nil\n}", "func EnvConfigFileReader() *EnvConfig {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn nil\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\tenvFile, err := os.Open(fileString)\n\n\tvar envConfig *EnvConfig\n\n\tif err != nil {\n\t\tlocalLogger(err.Error(), global.StatusError)\n\t\treturn nil\n\t} else {\n\t\tif fileContent, openErr := ioutil.ReadAll(envFile); openErr == nil {\n\t\t\tunMarshallErr := json.Unmarshal(fileContent, &envConfig)\n\t\t\tif unMarshallErr == nil {\n\t\t\t\treturn envConfig\n\t\t\t} else {\n\t\t\t\tlocalLogger(unMarshallErr.Error(), global.StatusError)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (cfg *Config) FromEnv() error {\n\n\t//Init\n\tif cfg.VirtualCenter == nil {\n\t\tcfg.VirtualCenter = make(map[string]*VirtualCenterConfig)\n\t}\n\n\t//Globals\n\tif v := os.Getenv(\"VSPHERE_VCENTER\"); v != \"\" {\n\t\tcfg.Global.VCenterIP = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_VCENTER_PORT\"); v != \"\" {\n\t\tcfg.Global.VCenterPort = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_USER\"); v != \"\" {\n\t\tcfg.Global.User = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_PASSWORD\"); v != \"\" {\n\t\tcfg.Global.Password = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_DATACENTER\"); v != \"\" {\n\t\tcfg.Global.Datacenters = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAME\"); v != \"\" {\n\t\tcfg.Global.SecretName = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAMESPACE\"); v != \"\" {\n\t\tcfg.Global.SecretNamespace = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_ROUNDTRIP_COUNT\"); v != \"\" {\n\t\ttmp, err := strconv.ParseUint(v, 10, 32)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_ROUNDTRIP_COUNT: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.RoundTripperCount = uint(tmp)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_INSECURE\"); v != \"\" {\n\t\tInsecureFlag, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_INSECURE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.InsecureFlag = InsecureFlag\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_DISABLE\"); v != \"\" {\n\t\tAPIDisable, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_API_DISABLE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.APIDisable = APIDisable\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_BINDING\"); v != \"\" {\n\t\tcfg.Global.APIBinding = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_SECRETS_DIRECTORY\"); v != \"\" {\n\t\tcfg.Global.SecretsDirectory = v\n\t}\n\tif cfg.Global.SecretsDirectory == \"\" {\n\t\tcfg.Global.SecretsDirectory = DefaultSecretDirectory\n\t}\n\tif _, err := os.Stat(cfg.Global.SecretsDirectory); os.IsNotExist(err) {\n\t\tcfg.Global.SecretsDirectory = \"\" //Dir does not exist, set to empty string\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_CAFILE\"); v != \"\" {\n\t\tcfg.Global.CAFile = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_THUMBPRINT\"); v != \"\" {\n\t\tcfg.Global.Thumbprint = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_REGION\"); v != \"\" {\n\t\tcfg.Labels.Region = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_ZONE\"); v != \"\" {\n\t\tcfg.Labels.Zone = v\n\t}\n\n\t//Build VirtualCenter from ENVs\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\n\t\tif len(pair) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := pair[0]\n\t\tvalue := pair[1]\n\n\t\tif strings.HasPrefix(key, \"VSPHERE_VCENTER_\") && len(value) > 0 {\n\t\t\tid := strings.TrimPrefix(key, \"VSPHERE_VCENTER_\")\n\t\t\tvcenter := value\n\n\t\t\t_, username, errUsername := getEnvKeyValue(\"VCENTER_\"+id+\"_USERNAME\", false)\n\t\t\tif errUsername != nil {\n\t\t\t\tusername = cfg.Global.User\n\t\t\t}\n\t\t\t_, password, errPassword := getEnvKeyValue(\"VCENTER_\"+id+\"_PASSWORD\", false)\n\t\t\tif errPassword != nil {\n\t\t\t\tpassword = cfg.Global.Password\n\t\t\t}\n\t\t\t_, server, errServer := getEnvKeyValue(\"VCENTER_\"+id+\"_SERVER\", false)\n\t\t\tif errServer != nil {\n\t\t\t\tserver = \"\"\n\t\t\t}\n\t\t\t_, port, errPort := getEnvKeyValue(\"VCENTER_\"+id+\"_PORT\", false)\n\t\t\tif errPort != nil {\n\t\t\t\tport = cfg.Global.VCenterPort\n\t\t\t}\n\t\t\tinsecureFlag := false\n\t\t\t_, insecureTmp, errInsecure := getEnvKeyValue(\"VCENTER_\"+id+\"_INSECURE\", false)\n\t\t\tif errInsecure != nil {\n\t\t\t\tinsecureFlagTmp, errTmp := strconv.ParseBool(insecureTmp)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\tinsecureFlag = insecureFlagTmp\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, datacenters, errDatacenters := getEnvKeyValue(\"VCENTER_\"+id+\"_DATACENTERS\", false)\n\t\t\tif errDatacenters != nil {\n\t\t\t\tdatacenters = cfg.Global.Datacenters\n\t\t\t}\n\t\t\troundtrip := DefaultRoundTripperCount\n\t\t\t_, roundtripTmp, errRoundtrip := getEnvKeyValue(\"VCENTER_\"+id+\"_ROUNDTRIP\", false)\n\t\t\tif errRoundtrip != nil {\n\t\t\t\troundtripFlagTmp, errTmp := strconv.ParseUint(roundtripTmp, 10, 32)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\troundtrip = uint(roundtripFlagTmp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, caFile, errCaFile := getEnvKeyValue(\"VCENTER_\"+id+\"_CAFILE\", false)\n\t\t\tif errCaFile != nil {\n\t\t\t\tcaFile = cfg.Global.CAFile\n\t\t\t}\n\t\t\t_, thumbprint, errThumbprint := getEnvKeyValue(\"VCENTER_\"+id+\"_THUMBPRINT\", false)\n\t\t\tif errThumbprint != nil {\n\t\t\t\tthumbprint = cfg.Global.Thumbprint\n\t\t\t}\n\n\t\t\t_, secretName, secretNameErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAME\", false)\n\t\t\t_, secretNamespace, secretNamespaceErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAMESPACE\", false)\n\n\t\t\tif secretNameErr != nil || secretNamespaceErr != nil {\n\t\t\t\tsecretName = \"\"\n\t\t\t\tsecretNamespace = \"\"\n\t\t\t}\n\t\t\tsecretRef := DefaultCredentialManager\n\t\t\tif secretName != \"\" && secretNamespace != \"\" {\n\t\t\t\tsecretRef = vcenter\n\t\t\t}\n\n\t\t\tiPFamilyPriority := []string{DefaultIPFamily}\n\t\t\t_, ipFamily, errIPFamily := getEnvKeyValue(\"VCENTER_\"+id+\"_IP_FAMILY\", false)\n\t\t\tif errIPFamily != nil {\n\t\t\t\tiPFamilyPriority = []string{ipFamily}\n\t\t\t}\n\n\t\t\t// If server is explicitly set, that means the vcenter value above is the TenantRef\n\t\t\tvcenterIP := vcenter\n\t\t\ttenantRef := vcenter\n\t\t\tif server != \"\" {\n\t\t\t\tvcenterIP = server\n\t\t\t\ttenantRef = vcenter\n\t\t\t}\n\n\t\t\tvar vcc *VirtualCenterConfig\n\t\t\tif cfg.VirtualCenter[tenantRef] != nil {\n\t\t\t\tvcc = cfg.VirtualCenter[tenantRef]\n\t\t\t} else {\n\t\t\t\tvcc = &VirtualCenterConfig{}\n\t\t\t\tcfg.VirtualCenter[tenantRef] = vcc\n\t\t\t}\n\n\t\t\tvcc.User = username\n\t\t\tvcc.Password = password\n\t\t\tvcc.TenantRef = tenantRef\n\t\t\tvcc.VCenterIP = vcenterIP\n\t\t\tvcc.VCenterPort = port\n\t\t\tvcc.InsecureFlag = insecureFlag\n\t\t\tvcc.Datacenters = datacenters\n\t\t\tvcc.RoundTripperCount = roundtrip\n\t\t\tvcc.CAFile = caFile\n\t\t\tvcc.Thumbprint = thumbprint\n\t\t\tvcc.SecretRef = secretRef\n\t\t\tvcc.SecretName = secretName\n\t\t\tvcc.SecretNamespace = secretNamespace\n\t\t\tvcc.IPFamilyPriority = iPFamilyPriority\n\t\t}\n\t}\n\n\treturn nil\n}", "func validateEnv(vars []corev1.EnvVar, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, ev := range vars {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(ev.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsEnvVarName(ev.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), ev.Name, msg))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child(\"valueFrom\"))...)\n\t}\n\treturn allErrs\n}", "func (e CliEnv) Validate() error {\n\tif e.AWSProfile == \"\" {\n\t\treturn ErrMissingAWSProfile\n\t}\n\n\tif e.AWSRegion == \"\" {\n\t\treturn ErrMissingAWSRegion\n\t}\n\n\tif e.StackName == \"\" {\n\t\treturn ErrMissingStackName\n\t}\n\n\treturn nil\n}", "func mustGetEnv(name string) string {\n\tenv, ok := os.LookupEnv(name)\n\tif !ok {\n\t\tlog.WithField(\"env\", name).Fatalf(\"missing required environment variable for configuration\")\n\t}\n\tlog.WithField(name, env).Info(\"using env variable\")\n\treturn env\n}", "func ValidateEnv(val string) (string, error) {\n\tarr := strings.Split(val, \"=\")\n\tif arr[0] == \"\" {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"invalid environment variable: %s\", val))\n\t}\n\tif len(arr) > 1 {\n\t\treturn val, nil\n\t}\n\tif !doesEnvExist(val) {\n\t\treturn val, nil\n\t}\n\treturn fmt.Sprintf(\"%s=%s\", val, os.Getenv(val)), nil\n}", "func envConfig(c *cli.Context) error {\n\tvar err error\n\n\terr = setEnvOptStr(\"DOCKER_HOST\", c.GlobalString(\"host\"))\n\terr = setEnvOptBool(\"DOCKER_TLS_VERIFY\", c.GlobalBool(\"tlsverify\"))\n\terr = setEnvOptStr(\"DOCKER_API_VERSION\", DockerAPIMinVersion)\n\n\treturn err\n}", "func validateExportConfig() {\n\trequiredConfig := []string{\"ident\",\n\t\t\"channel\",\n\t}\n\tfor _, req := range requiredConfig {\n\t\tif !viper.IsSet(req) {\n\t\t\tlog.Fatalln(\"Missing required config value for: \", req)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func CheckEnvVars(t *testing.T, envVars ...string) {\n\tvar missing []string\n\n\tfor _, envVar := range envVars {\n\t\tif os.Getenv(envVar) == \"\" {\n\t\t\tmissing = append(missing, envVar)\n\t\t}\n\t}\n\n\tif len(missing) > 0 {\n\t\trequire.FailNow(t, fmt.Sprintf(\"missing required AWS environment variables: %s\", missing))\n\t}\n}", "func (util *Utils) CheckEnvironment(path string) string {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn \"\"\n\t}\n\treturn path\n}", "func Check() {\n\tvar missing []string\n\tfor _, key := range viper.GetStringSlice(\"env_var_names\") {\n\t\tif _, ok := os.LookupEnv(key); !ok {\n\t\t\tmissing = append(missing, key)\n\t\t}\n\t}\n\tif len(missing) > 0 {\n\t\tlog.Fatalf(\"CheckEnv(): missing the following environmental variables: \\n\\t%s\", strings.Join(missing, \"\\n\\t\"))\n\t}\n}", "func validateConfig(cfg YamlConfig) error {\n\n\t// If Directory is nil, try to retrieve from env var, if not then error\n\tif cfg.Directory == \"\" {\n\t\treturn errors.New(\"Did not find logs directory in YAML configuration\")\n\t}\n\n\t// If Directory resolved, check if directory exists, if not then error\n\tif _, err := os.Stat(cfg.Directory); os.IsNotExist(err) {\n\t\treturn errors.New(fmt.Sprintf(\"Resolved logs directory %s does not exist, exiting\", cfg.Directory))\n\t}\n\n\t// If Name or LogPattern missing, error\n\tif cfg.ConfigName == \"\" {\n\t\treturn errors.New(\"YAML configuration missing required 'ConfigName' key, exiting\")\n\t} else if cfg.LogPattern == \"\" {\n\t\treturn errors.New(\"YAML configuration missing required 'LogPattern' key, exiting\")\n\t}\n\n\tconnectorsConfigs := getConnectorsConfigs(cfg)\n\n\tfor _, connCfg := range connectorsConfigs {\n\t\t// Assert connectors have valid common fields values\n\t\terr := validateConnectorsCommonFields(connCfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Assert connectors have valid S3 connector fields\n\t\terr = connCfg.validate()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func CheckDotEnv() {\n\terr := godotenv.Load()\n\tif err != nil && os.Getenv(env) == local {\n\t\tlog.Println(\"Error loading .env file\")\n\t}\n}", "func init() {\n\tWorkEnv = os.Getenv(\"WorkEnv\")\n\tjsonFile, err := os.Open(\"./config/config.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar environments Environments\n\tjson.Unmarshal(byteValue, &environments)\n\tvar checkWorkEnv = 0\n\tfor i := 0; i < len(environments.Environments); i++ {\n\t\tif WorkEnv == environments.Environments[i].Env || (WorkEnv == \"\" && environments.Environments[i].Env == \"dev\") {\n\t\t\tAddress = environments.Environments[i].Database.Address\n\t\t\tDbName = environments.Environments[i].Database.DBName\n\t\t\tDbUsername = environments.Environments[i].Database.DBUsername\n\t\t\tDbPassword = environments.Environments[i].Database.DBPassword\n\t\t\tPort = environments.Environments[i].API.Port\n\t\t\tcheckWorkEnv = 1\n\t\t}\n\t}\n\tif checkWorkEnv == 0 {\n\t}\n}", "func validateConfig(appConfig AppConfig) error {\n\n\treturn nil\n}", "func FromEnv() (*Configuration, error) {\n\treturn &Configuration{\n\t\tEndpoint: Endpoint(os.Getenv(\"OVH_ENDPOINT\")),\n\t\tApplicationKey: os.Getenv(\"OVH_APPLICATION_KEY\"),\n\t\tApplicationSecret: os.Getenv(\"OVH_APPLICATION_SECRET\"),\n\t\tConsumerKey: os.Getenv(\"OVH_CONSUMER_KEY\"),\n\t}, nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.Key == \"\" {\n\t\treturn errors.New(\"missing DigitalOcean access key\")\n\t}\n\n\treturn nil\n}", "func (config *Config) Validate() error {\n\n\tif _, err := os.Stat(filepath.Join(config.KirdPath, config.KernelFile)); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"kernel '%s' not found\", filepath.Join(config.KirdPath, config.KernelFile))\n\t}\n\tif _, err := os.Stat(filepath.Join(config.KirdPath, config.InitrdFile)); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"initrd '%s' not found\", filepath.Join(config.KirdPath, config.InitrdFile))\n\t}\n\n\t// Ensure all the MappedVirtualDisks exist on the host\n\tfor _, mvd := range config.MappedVirtualDisks {\n\t\tif _, err := os.Stat(mvd.HostPath); err != nil {\n\t\t\treturn fmt.Errorf(\"mapped virtual disk '%s' not found\", mvd.HostPath)\n\t\t}\n\t\tif mvd.ContainerPath == \"\" {\n\t\t\treturn fmt.Errorf(\"mapped virtual disk '%s' requested without a container path\", mvd.HostPath)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *Reader) getProvidersFromEnv(filePath string) (\n\tproviders []provider.Provider, warnings []string, err error) {\n\ts := os.Getenv(\"CONFIG\")\n\tif s == \"\" {\n\t\treturn nil, nil, nil\n\t}\n\tr.logger.Info(\"reading JSON config from environment variable CONFIG\")\n\tr.logger.Debug(\"config read: \" + s)\n\n\tb := []byte(s)\n\n\tproviders, warnings, err = extractAllSettings(b)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"configuration given: %w\", err)\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\terr = json.Indent(buffer, b, \"\", \" \")\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\tconst mode = fs.FileMode(0600)\n\terr = r.writeFile(filePath, buffer.Bytes(), mode)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\n\treturn providers, warnings, nil\n}", "func (opts *InitEnvOpts) Validate() error {\n\tif opts.EnvName != \"\" {\n\t\tif err := validateEnvironmentName(opts.EnvName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif viper.GetString(projectFlag) == \"\" {\n\t\treturn errors.New(\"no project found, run `project init` first\")\n\t}\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tif c.ServerConf.RestAPIPort < 0 || c.ServerConf.RestAPIPort > 65535 {\n\t\treturn errors.New(\"invalid restful port: \" + strconv.Itoa(c.ServerConf.RestAPIPort))\n\t}\n\n\t// remove \"/\"\n\tc.ZeekConf.LogDir = processDirName(c.ZeekConf.LogDir)\n\tc.ZeekConf.PcapDir = processDirName(c.ZeekConf.PcapDir)\n\tc.ZeekConf.ExtractedFileDir = processDirName(c.ZeekConf.ExtractedFileDir)\n\tc.SeaweedfsConf.ExtractedFileDir = processDirName(c.SeaweedfsConf.ExtractedFileDir)\n\n\tif c.SeaweedfsConf.Retries < 1 {\n\t\treturn errors.New(\"seaweedfs post retry times < 1\")\n\t}\n\treturn nil\n}", "func (o *initEnvOpts) Validate() error {\n\tif o.name != \"\" {\n\t\tif err := validateEnvironmentName(o.name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := o.validateCustomizedResources(); err != nil {\n\t\treturn err\n\t}\n\treturn o.validateCredentials()\n}", "func CheckEnv(lookupFunc func(key string) (string, bool)) (err error) {\n\tif lookupFunc == nil {\n\t\tlookupFunc = os.LookupEnv\n\t}\n\n\tenvVars := [4]string{\n\t\tEnvHueBridgeAddress,\n\t\tEnvHueBridgeUsername,\n\t\tEnvHueRemoteToken,\n\t\tEnvRedisURL,\n\t}\n\n\tfor _, v := range envVars {\n\t\tif _, ok := lookupFunc(v); !ok {\n\t\t\treturn models.NewMissingEnvError(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CheckEnvironment(env string) {\n\t// Compare and validate environments\n\tif !IsValid(env) {\n\t\tpanic(\"JUS_ENVIRONMENT not setted!\\n\" +\n\t\t\t\"To correct this, run this command in your terminal: export JUS_ENVIRONMENT=developer\\n\" +\n\t\t\t\"Available environments: developer, sandbox, production, test\")\n\t}\n}", "func ReadFromFileAndEnv(settings interface{}) error {\n\tfile, err := os.Open(\"appsettings.json\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\tdata, err := ioutil.ReadAll(file)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to read appsettings\")\n\t}\n\n\terr = json.Unmarshal(data, settings)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to unmarshal appsettings\")\n\t}\n\n\terr = envconfig.Init(settings)\n\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"Failed to update with env vars\")\n\t}\n\treturn err\n}", "func (c *Config) Validate() error {\n\t// we'll first validate the structure and values of the config file\n\tfile := c.viper.GetString(configFile)\n\tvar out interface{}\n\tb, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch filepath.Ext(file) {\n\tcase \".yaml\", \".yml\":\n\t\terr = yaml.Unmarshal(b, &out)\n\tcase \".json\":\n\t\terr = json.Unmarshal(b, &out)\n\tdefault:\n\t\treturn fmt.Errorf(\"%s is not a supported config file extension\", filepath.Ext(file))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't read the config file: %v\", err)\n\t}\n\t// validate config file content\n\tvalid, errs := validate(interpolateSchema(), out)\n\tif !valid || len(errs) > 0 {\n\t\treturn fmt.Errorf(\"invalid config: %v\", multierror.Wrap(errs...))\n\t}\n\t// now validate the Viper config flags\n\tvalid, errs = validate(interpolateSchema(), c.viper.AllSettings())\n\tif !valid || len(errs) > 0 {\n\t\treturn fmt.Errorf(\"invalid config: %v\", multierror.Wrap(errs...))\n\t}\n\treturn nil\n}", "func (c *Config) validateIniConfig() bool {\n\t// livery directory\n\tif c.Ini.Section(\"paths\").Key(\"liveryDir\").String() == \"\" {\n\t\treturn false\n\t}\n\tisDir, err := util.IsDir(c.Ini.Section(\"paths\").Key(\"liveryDir\").String())\n\tif err != nil || !isDir {\n\t\treturn false\n\t}\n\t// output file\n\tif c.Ini.Section(\"paths\").Key(\"outputFile\").String() == \"\" {\n\t\treturn false\n\t}\n\tisDir, err = util.IsDir(c.Ini.Section(\"paths\").Key(\"outputFile\").String())\n\tif err != nil || isDir { // file does not exist or path exists but is directory\n\t\treturn false\n\t}\n\treturn true\n}", "func ReadConfig() *error {\n\tvar env = os.Getenv(\"ENV\")\n\n\tgame.Appartement.Bots = Config.Bots\n\tfile, err := os.Open(\"/env/config.\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Println(prefixWarn, \"ENV must be of: 'localhost', 'dev' or 'prod'. starting with default configuration\")\n\t\treturn &err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn &err\n\t}\n\n\treturn nil\n}", "func configFromFile(env string) (Config, error) {\n\tenv = strings.ToLower(env)\n\t// attempt to read config from {{environment}}.yml (defaults to development.yml)\n\tvar fname string\n\tvar conf Config\n\tif _, err := os.Stat(fmt.Sprintf(\"config/%s.yml\", env)); err == nil {\n\t\tfname = fmt.Sprintf(\"config/%s.yml\", env)\n\t} else {\n\t\tfname = fmt.Sprintf(\"config/development.yml\")\n\t}\n\n\tymlFile, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\terr = yaml.Unmarshal(ymlFile, &conf)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n\n}", "func InitEnv() error {\n\tfile, err := ioutil.ReadFile(envPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif errMarsh := codec.DecJson(file, &env); errMarsh != nil {\n\t\treturn fmt.Errorf(\"failed to parse %s. decode error: %v\", string(file), err)\n\t}\n\n\treturn nil\n}", "func setupEnvConfigViper(environmentFlag string) *viper.Viper {\n\tconfig := viper.New()\n\tconfig.SetConfigName(environmentFlag)\n\tconfig.AddConfigPath(\"./.argo/environments\")\n\tif err := config.ReadInConfig(); err != nil {\n\t\tcolor.Red(\"%s\",err)\n\t\tcolor.Red(\"Error locating or parsing %s env's helm value file (should be ./argo/environments/%s.yaml!\", environmentFlag)\n\t\tos.Exit(1)\n\t}\n\treturn config\n}", "func configExistsInPath(path string) bool {\n\t// Needed for testing\n\tif config != nil {\n\t\treturn true\n\t}\n\n\t// Check devspace.yaml\n\t_, err := os.Stat(filepath.Join(path, constants.DefaultConfigPath))\n\tif err == nil {\n\t\treturn true\n\t}\n\n\t// Check devspace-configs.yaml\n\t_, err = os.Stat(filepath.Join(path, constants.DefaultConfigsPath))\n\tif err == nil {\n\t\treturn true\n\t}\n\n\treturn false // Normal config file found\n}", "func ValidateConfig(c Config) error {\n\tif !ConfigOK(c) {\n\t\treturn fmt.Errorf(\"Must provide %s, %s, %s: (%s, %s, '*')\", LocationEnv, UserEnv, PasswordEnv, c.Location, c.User)\n\t}\n\n\treturn nil\n}", "func (c *Config) ValidateConfig() error {\n\tif c.FileName == \"\" {\n\t\treturn errors.New(\"Puppetfile not provided\")\n\t}\n\tif c.Module == \"\" {\n\t\treturn errors.New(\"Module not provided\")\n\t}\n\tif c.Key == \"\" {\n\t\treturn errors.New(\"Key not provided\")\n\t}\n\treturn nil\n}", "func ValidateGlobalConfig() error {\n\tif viper.GetString(\"username\") == \"\" {\n\t\treturn fmt.Errorf(\"username is not set\")\n\t}\n\tif viper.GetString(\"api-key\") == \"\" {\n\t\treturn fmt.Errorf(\"API key is not set\")\n\t}\n\treturn nil\n}", "func TestValidGetEnvValueForField3(t *testing.T) {\n\tosGetenv = mockInvalidOsGetenv\n\n\tif _, err := getEnvValueForField(\"$ENV_VAR\"); err == nil {\n\t\tt.Errorf(\"Invalid Hostname Returned No Error\")\n\t}\n}", "func getenvRequired(key string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\tPtEnvError(fmt.Sprintf(\"no %s environment variable\", key))\n\t}\n\treturn value\n}", "func checkConfigValidity() {\n\tnerrs := 0\n\tif config.Google.ClientId == \"\" ||\n\t\tconfig.Google.ClientId == \"YOUR_GOOGLE_APP_CLIENT_ID\" {\n\t\tfmt.Fprintf(os.Stderr, \"skicka: missing [google]/clientid in \"+\n\t\t\t\"configuration file.\\n\")\n\t\tnerrs++\n\t}\n\tif config.Google.ClientSecret == \"\" ||\n\t\tconfig.Google.ClientSecret == \"YOUR_GOOGLE_APP_SECRET\" {\n\t\tfmt.Fprintf(os.Stderr, \"skicka: missing [google]/clientsecret in \"+\n\t\t\t\"configuration file.\\n\")\n\t\tnerrs++\n\t}\n\n\t// It's ok if the encryption stuff isn't present (if encryption\n\t// isn't being used), but if it is present, it must be valid...\n\tnerrs += checkEncryptionConfig(config.Encryption.Salt, \"salt\", 32)\n\tnerrs += checkEncryptionConfig(config.Encryption.Passphrase_hash,\n\t\t\"passphrase-hash\", 32)\n\tnerrs += checkEncryptionConfig(config.Encryption.Encrypted_key,\n\t\t\"encrypted-key\", 32)\n\tnerrs += checkEncryptionConfig(config.Encryption.Encrypted_key_iv,\n\t\t\"encrypted-key-iv\", 16)\n\n\tif nerrs > 0 {\n\t\tos.Exit(1)\n\t}\n}", "func (c Config) Validate() (err error) {\n\tvar fi os.FileInfo\n\n\t// validate key fingerprint\n\t_, err = HexStringToFingerprint(c.MasterKeyFingerprint)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// validate TLSCert\n\tif len(c.TLSCert) == 0 {\n\t\treturn errors.New(\"Missing config param: TLSCert\")\n\t}\n\tfi, err = os.Stat(c.TLSCert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in TLSCert '%s': %s\", c.TLSCert, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in TLSCert '%s': expected file path, got directory\", c.TLSCert)\n\t}\n\n\t// validate TLSKey\n\tif len(c.TLSKey) == 0 {\n\t\treturn errors.New(\"Missing config param: TLSKey\")\n\t}\n\tfi, err = os.Stat(c.TLSKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in TLSKey '%s': %s\", c.TLSKey, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in TLSKey '%s': expected file path, got directory\", c.TLSKey)\n\t}\n\n\t// validate SecRing\n\tif len(c.SecRing) == 0 {\n\t\treturn errors.New(\"Missing config param: SecRing\")\n\t}\n\tfi, err = os.Stat(c.SecRing)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in SecRing '%s': %s\", c.SecRing, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in SecRing '%s': expected file path, got directory\", c.SecRing)\n\t}\n\n\t// validate ProdSupportPubRing\n\tif len(c.ProdSupportPubRing) == 0 {\n\t\treturn errors.New(\"Missing config param: ProdSupportPubRing\")\n\t}\n\tfi, err = os.Stat(c.ProdSupportPubRing)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in ProdSupportPubRing '%s': %s\", c.ProdSupportPubRing, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in ProdSupportPubRing '%s': expected file path, got directory\", c.ProdSupportPubRing)\n\t}\n\n\t// validate DataRoot\n\tif len(c.DataRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: DataRoot\")\n\t}\n\tfi, err = os.Stat(c.DataRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.DataRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in DataRoot '%s': %s\", c.DataRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in DataRoot '%s': expected directory, got file path\", c.DataRoot)\n\t\t}\n\t}\n\n\t// validate ProdSupportDir\n\tif len(c.ProdSupportDir) == 0 {\n\t\treturn errors.New(\"Missing config param: ProdSupportDir\")\n\t}\n\tfi, err = os.Stat(c.ProdSupportDir)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.ProdSupportDir, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in ProdSupportDir '%s': %s\", c.ProdSupportDir, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in ProdSupportDir '%s': expected directory, got file path\", c.ProdSupportDir)\n\t\t}\n\t}\n\n\t// validate KeyRoot\n\tif len(c.KeyRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: KeyRoot\")\n\t}\n\tfi, err = os.Stat(c.KeyRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.KeyRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in KeyRoot '%s': %s\", c.KeyRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in KeyRoot '%s': expected directory, got file path\", c.KeyRoot)\n\t\t}\n\t}\n\n\t// validate MetaRoot\n\tif len(c.MetaRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: MetaRoot\")\n\t}\n\tfi, err = os.Stat(c.MetaRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.MetaRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in MetaRoot '%s': %s\", c.MetaRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in MetaRoot '%s': expected directory, got file path\", c.MetaRoot)\n\t\t}\n\t}\n\n\t// validate HTTPLog\n\tif len(c.HTTPLog) > 0 {\n\t\tfi, err = os.Stat(filepath.Dir(c.HTTPLog))\n\t\tif err != nil {\n\t\t\t// doesn't exist... can we create it?\n\t\t\tif err = os.MkdirAll(filepath.Dir(c.HTTPLog), 0744); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Config error in HTTPLog '%s': %s\", c.HTTPLog, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// validate HtpasswdFile\n\tif len(c.HtpasswdFile) == 0 {\n\t\treturn errors.New(\"Missing config param: HtpasswdFile\")\n\t}\n\tfi, err = os.Stat(c.HtpasswdFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in HtpasswdFile '%s': %s\", c.HtpasswdFile, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in HtpasswdFile '%s': expected file path, got directory\", c.HtpasswdFile)\n\t}\n\n\tif len(c.MasterKeyPassphrase) == 0 {\n\t\tlog.Println(\"no passphrase specified for secure keyring\")\n\t}\n\n\treturn nil\n}", "func validateConfig(config *ProviderConfig) error {\n\t// Validate the inputs\n\tif config == nil {\n\t\treturn fmt.Errorf(\"missing config\")\n\t}\n\tif config.Service == nil {\n\t\treturn fmt.Errorf(\"missing service\")\n\t}\n\tif config.Service.Service == \"\" {\n\t\treturn fmt.Errorf(\"missing service name\")\n\t}\n\tif config.Service.ServiceVersion == \"\" {\n\t\treturn fmt.Errorf(\"missing service version\")\n\t}\n\tif config.Service.ResourceType == \"\" {\n\t\treturn fmt.Errorf(\"missing service resource type\")\n\t}\n\tif config.Handlers == nil && len(config.Service.Capabilities) != 0 {\n\t\treturn fmt.Errorf(\"missing handlers\")\n\t}\n\tfor c := range config.Service.Capabilities {\n\t\tif _, ok := config.Handlers[c]; !ok {\n\t\t\treturn fmt.Errorf(\"missing handler for '%s' capability\", c)\n\t\t}\n\t}\n\tif config.ResourceGroup == \"\" {\n\t\treturn fmt.Errorf(\"missing resource group\")\n\t}\n\tif config.Token == \"\" {\n\t\tconfig.Token = os.Getenv(\"ATLAS_TOKEN\")\n\t}\n\tif config.Token == \"\" {\n\t\treturn fmt.Errorf(\"missing token\")\n\t}\n\n\t// Default the endpoint\n\tif config.Endpoint == \"\" {\n\t\tconfig.Endpoint = DefaultEndpoint\n\t\tif end := os.Getenv(\"SCADA_ENDPOINT\"); end != \"\" {\n\t\t\tconfig.Endpoint = end\n\t\t}\n\t}\n\treturn nil\n}", "func validateAndGetEnvVars() (*environmentVariables, error) {\n\tenvVars := &environmentVariables{}\n\tuploadAPIURL := os.Getenv(\"UPLOAD_API_URL\")\n\tif len(uploadAPIURL) == 0 {\n\t\treturn nil, errors.Errorf(\"UPLOAD_API_URL environment variable is not set\")\n\t}\n\tenvVars.UploadAPIURL = uploadAPIURL\n\n\tpostAPIURL := os.Getenv(\"POST_API_URL\")\n\tif len(postAPIURL) == 0 {\n\t\treturn nil, errors.Errorf(\"POST_API_URL environment variable is not set\")\n\t}\n\tenvVars.PostAPIURL = postAPIURL\n\n\tmattermostDeployments := os.Getenv(\"MATTERMOST_DEPLOYMENTS\")\n\tif len(mattermostDeployments) == 0 {\n\t\tenvVars.MattermostDeployments = []string{}\n\t} else {\n\t\tenvVars.MattermostDeployments = strings.Split(mattermostDeployments, \",\")\n\t}\n\n\tmattermostNamespace := os.Getenv(\"MATTERMOST_NAMESPACE\")\n\tif len(mattermostNamespace) == 0 {\n\t\treturn nil, errors.Errorf(\"CHANNEL_ID environment variable is not set.\")\n\t}\n\tenvVars.MattermostNamespace = mattermostNamespace\n\n\tprofilingTime := os.Getenv(\"PROFILING_TIME\")\n\tif len(profilingTime) == 0 {\n\t\treturn nil, errors.Errorf(\"PROFILING_TIME environment variable is not set.\")\n\t}\n\tenvVars.ProfilingTime = profilingTime\n\n\tchannelID := os.Getenv(\"CHANNEL_ID\")\n\tif len(channelID) == 0 {\n\t\treturn nil, errors.Errorf(\"CHANNEL_ID environment variable is not set.\")\n\t}\n\tenvVars.ChannelID = channelID\n\n\ttoken := os.Getenv(\"TOKEN\")\n\tif len(token) == 0 {\n\t\treturn nil, errors.Errorf(\"TOKEN environment variable is not set.\")\n\t}\n\tenvVars.Token = token\n\n\tdeveloperMode := os.Getenv(\"DEVELOPER_MODE\")\n\tif len(developerMode) == 0 {\n\t\tenvVars.DevMode = \"false\"\n\t} else {\n\t\tenvVars.DevMode = developerMode\n\t}\n\n\treturn envVars, nil\n}", "func TestSystemConfigIsExisting(t *testing.T) {\n\n\tif !exists(confPath) {\n\t\tt.Fatal(confPath, \"does not exist: cannot do testing\")\n\t}\n}", "func TestGetConfigInfoWithoutIndexdOrMDSCreds(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"Expecting getConfigInfo to panic since Indexd and Metadata Service creds were not present in CONFIG_FILE\")\n\t\t}\n\t}()\n\n\tjsonConfigInfo :=\n\t\t`\n\t{}\n\t`\n\terr := os.Setenv(\"CONFIG_FILE\", jsonConfigInfo)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgetConfigInfo()\n}", "func TestEnvEmpty(t *testing.T) {\n\tenverr := pkg.LoadEnv()\n\n\tif _, err := os.Stat(\"../.env\"); os.IsNotExist(err) {\n\t\tif enverr != nil {\n\t\t\tt.Error(\"Env does not exist\")\n\t\t}\n\t}\n}", "func checkEnv(envVar string) string {\n\tv := os.Getenv(envVar)\n\tif v == \"\" {\n\t\tlog.Panicf(\"%s environment variable not set.\", envVar)\n\t}\n\treturn v\n}", "func (c *Configuration) FromEnv() {\n\tif api := getOSPrefixEnv(\"API\"); api != nil {\n\t\tc.APIListener = *api\n\t}\n\n\tif httpListener := getOSPrefixEnv(\"HTTP\"); httpListener != nil {\n\t\tc.HTTPListener = *httpListener\n\t}\n\n\tif httpsListener := getOSPrefixEnv(\"HTTPS\"); httpsListener != nil {\n\t\tc.HTTPSListener = *httpsListener\n\t}\n\n\tif dbEndpoint := getOSPrefixEnv(\"DB_ENDPOINT\"); dbEndpoint != nil {\n\t\tc.DynamoDB.Endpoint = *dbEndpoint\n\t}\n\n\tif dbRegion := getOSPrefixEnv(\"DB_REGION\"); dbRegion != nil {\n\t\tc.DynamoDB.Region = *dbRegion\n\t}\n\n\tif dbKey := getOSPrefixEnv(\"DB_KEY\"); dbKey != nil {\n\t\tif dbSecret := getOSPrefixEnv(\"DB_SECRET\"); dbSecret != nil {\n\t\t\tc.DynamoDB.Key = *dbKey\n\t\t\tc.DynamoDB.Secret = *dbSecret\n\t\t}\n\t}\n\n\tif dbBootstrap := getOSPrefixEnv(\"BOOTSTRAP\"); dbBootstrap != nil {\n\t\tc.Bootstrap = len(*dbBootstrap) > 0 && *dbBootstrap != \"0\"\n\t}\n\n\tif logLevel := getOSPrefixEnv(\"LOG_LEVEL\"); logLevel != nil {\n\t\tc.LogLevel = *logLevel\n\t}\n\n\tif logFormatter := getOSPrefixEnv(\"LOG_FORMATTER\"); logFormatter != nil {\n\t\tc.LogFormatter = *logFormatter\n\t}\n}", "func (c *Config) ReadEnvironment() error {\n\tvar envAddress string\n\tvar envAgentAddress string\n\tvar envCACert string\n\tvar envCACertBytes []byte\n\tvar envCAPath string\n\tvar envClientCert string\n\tvar envClientKey string\n\tvar envClientTimeout time.Duration\n\tvar envInsecure bool\n\tvar envTLSServerName string\n\tvar envMaxRetries *uint64\n\tvar envSRVLookup bool\n\tvar limit *rate.Limiter\n\tvar envVaultProxy string\n\tvar envVaultDisableRedirects bool\n\n\t// Parse the environment variables\n\tif v := os.Getenv(EnvVaultAddress); v != \"\" {\n\t\tenvAddress = v\n\t}\n\tif v := os.Getenv(EnvVaultAgentAddr); v != \"\" {\n\t\tenvAgentAddress = v\n\t}\n\tif v := os.Getenv(EnvVaultMaxRetries); v != \"\" {\n\t\tmaxRetries, err := strconv.ParseUint(v, 10, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tenvMaxRetries = &maxRetries\n\t}\n\tif v := os.Getenv(EnvVaultCACert); v != \"\" {\n\t\tenvCACert = v\n\t}\n\tif v := os.Getenv(EnvVaultCACertBytes); v != \"\" {\n\t\tenvCACertBytes = []byte(v)\n\t}\n\tif v := os.Getenv(EnvVaultCAPath); v != \"\" {\n\t\tenvCAPath = v\n\t}\n\tif v := os.Getenv(EnvVaultClientCert); v != \"\" {\n\t\tenvClientCert = v\n\t}\n\tif v := os.Getenv(EnvVaultClientKey); v != \"\" {\n\t\tenvClientKey = v\n\t}\n\tif v := os.Getenv(EnvRateLimit); v != \"\" {\n\t\trateLimit, burstLimit, err := parseRateLimit(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlimit = rate.NewLimiter(rate.Limit(rateLimit), burstLimit)\n\t}\n\tif t := os.Getenv(EnvVaultClientTimeout); t != \"\" {\n\t\tclientTimeout, err := parseutil.ParseDurationSecond(t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %q\", EnvVaultClientTimeout)\n\t\t}\n\t\tenvClientTimeout = clientTimeout\n\t}\n\tif v := os.Getenv(EnvVaultSkipVerify); v != \"\" {\n\t\tvar err error\n\t\tenvInsecure, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultSkipVerify)\n\t\t}\n\t}\n\tif v := os.Getenv(EnvVaultSRVLookup); v != \"\" {\n\t\tvar err error\n\t\tenvSRVLookup, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultSRVLookup)\n\t\t}\n\t}\n\n\tif v := os.Getenv(EnvVaultTLSServerName); v != \"\" {\n\t\tenvTLSServerName = v\n\t}\n\n\tif v := os.Getenv(EnvHTTPProxy); v != \"\" {\n\t\tenvVaultProxy = v\n\t}\n\n\t// VAULT_PROXY_ADDR supersedes VAULT_HTTP_PROXY\n\tif v := os.Getenv(EnvVaultProxyAddr); v != \"\" {\n\t\tenvVaultProxy = v\n\t}\n\n\tif v := os.Getenv(EnvVaultDisableRedirects); v != \"\" {\n\t\tvar err error\n\t\tenvVaultDisableRedirects, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultDisableRedirects)\n\t\t}\n\n\t\tc.DisableRedirects = envVaultDisableRedirects\n\t}\n\n\t// Configure the HTTP clients TLS configuration.\n\tt := &TLSConfig{\n\t\tCACert: envCACert,\n\t\tCACertBytes: envCACertBytes,\n\t\tCAPath: envCAPath,\n\t\tClientCert: envClientCert,\n\t\tClientKey: envClientKey,\n\t\tTLSServerName: envTLSServerName,\n\t\tInsecure: envInsecure,\n\t}\n\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\n\tc.SRVLookup = envSRVLookup\n\tc.Limiter = limit\n\n\tif err := c.configureTLS(t); err != nil {\n\t\treturn err\n\t}\n\n\tif envAddress != \"\" {\n\t\tc.Address = envAddress\n\t}\n\n\tif envAgentAddress != \"\" {\n\t\tc.AgentAddress = envAgentAddress\n\t}\n\n\tif envMaxRetries != nil {\n\t\tc.MaxRetries = int(*envMaxRetries)\n\t}\n\n\tif envClientTimeout != 0 {\n\t\tc.Timeout = envClientTimeout\n\t}\n\n\tif envVaultProxy != \"\" {\n\t\tu, err := url.Parse(envVaultProxy)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttransport := c.HttpClient.Transport.(*http.Transport)\n\t\ttransport.Proxy = http.ProxyURL(u)\n\t}\n\n\treturn nil\n}", "func (s) TestErrInFileSystemEnvVar(t *testing.T) {\n\toldObservabilityConfigFile := envconfig.ObservabilityConfigFile\n\tenvconfig.ObservabilityConfigFile = \"/this-file/does-not-exist\"\n\tdefer func() {\n\t\tenvconfig.ObservabilityConfigFile = oldObservabilityConfigFile\n\t}()\n\tif err := Start(context.Background()); err == nil {\n\t\tt.Fatalf(\"Invalid file system path not triggering error\")\n\t}\n}", "func loadConfig() {\n\terr := godotenv.Load()\n\n\tif err != nil {\n\t\tlog.Println(\"did not load any .env file\")\n\t}\n\n\terr = env.Parse(&cfg)\n\n\tif err != nil {\n\t\tlog.Fatal(\"The .env format is not valid\", err)\n\t}\n}", "func (m *EnvironmentRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCredential(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKerberosConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateKubernetesConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLdapConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocation(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProxyConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRdsConfigs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRegions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *dataConfig) Validate(args []string) error {\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"name must be specified once\")\n\t}\n\ta.Name = args[0]\n\tif len(a.EnvFileSource) == 0 && len(a.FileSources) == 0 && len(a.LiteralSources) == 0 {\n\t\treturn fmt.Errorf(\"at least from-env-file, or from-file or from-literal must be set\")\n\t}\n\tif len(a.EnvFileSource) > 0 && (len(a.FileSources) > 0 || len(a.LiteralSources) > 0) {\n\t\treturn fmt.Errorf(\"from-env-file cannot be combined with from-file or from-literal\")\n\t}\n\t// TODO: Should we check if the path exists? if it's valid, if it's within the same (sub-)directory?\n\treturn nil\n}", "func Load() error {\n\tfile, err := os.Open(\".env/config.json\")\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparser := json.NewDecoder(file)\n\terr = parser.Decode(&config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(config.Backend.MongoDB.URI) < 1 {\n\t\tconfig.Backend.MongoDB.URI = \"mongodb://127.0.0.1:27017\"\n\t}\n\n\tif len(config.Backend.MongoDB.Database) < 1 {\n\t\tconfig.Backend.MongoDB.Database = \"ikuta\"\n\t}\n\n\tif len(config.HTTP.Address) < 1 {\n\t\tconfig.HTTP.Address = \":7136\"\n\t}\n\n\treturn nil\n}", "func EnsureENVSet() (ok bool, missing string) {\n\n\t// Ports for queues and DB\n\tReportQueuePort := os.Getenv(\"REPORT_QUEUE_PORT\")\n\tNotifierQueuePort := os.Getenv(\"NOTIFIER_QUEUE_PORT\")\n\tESPort := os.Getenv(\"ES_PORT\")\n\n\t// AWS\n\tS3Region := os.Getenv(\"S3_REGION\")\n\tS3Bucket := os.Getenv(\"S3_BUCKET\")\n\tAWSAccessKeyID := os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\tAWSSecretAccessKey := os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\n\tif ReportQueuePort == \"\" {\n\t\treturn false, \"Report Queue Port\"\n\t}\n\n\tif NotifierQueuePort == \"\" {\n\t\treturn false, \"Notifier Queue Port\"\n\t}\n\n\tif ESPort == \"\" {\n\t\treturn false, \"Elasticsearch Port\"\n\t}\n\n\tif S3Region == \"\" {\n\t\treturn false, \"S3 Region\"\n\t}\n\n\tif S3Bucket == \"\" {\n\t\treturn false, \"S3 Bucket\"\n\t}\n\n\tif AWSAccessKeyID == \"\" {\n\t\treturn false, \"AWS Access Key ID\"\n\t}\n\n\tif AWSSecretAccessKey == \"\" {\n\t\treturn false, \"AWS Secret Access Key\"\n\t}\n\n\treturn true, \"\"\n}", "func (c *configuration) validateConfig() error {\n\tif c.Provider == \"\" {\n\t\treturn errors.New(msgConfigNoProvider)\n\t}\n\n\tif len(c.Servers) == 0 {\n\t\treturn errors.New(msgConfigNoServers)\n\t}\n\n\tfor i, srv := range c.Servers {\n\t\tif srv.FabricIface == \"\" {\n\t\t\treturn errors.Errorf(\n\t\t\t\tmsgConfigServerNoIface+\" for I/O service %d\", i)\n\t\t}\n\t}\n\n\treturn nil\n}", "func checkEnvVar(envVars *map[string]string) error {\n\tvar missingVars []string\n\tfor name, v := range *envVars {\n\t\tif v == \"\" {\n\t\t\tmissingVars = append(missingVars, name)\n\t\t}\n\t}\n\tif len(missingVars) > 0 {\n\t\treturn fmt.Errorf(\"Missing environment variables %v\", missingVars)\n\t}\n\treturn nil\n}", "func (clbCfg *CLBConfig) LoadFromEnv() error {\n\tvar err error\n\tclbCfg.ImplementMode = os.Getenv(ConfigBcsClbImplement)\n\tif clbCfg.ImplementMode != ConfigBcsClbImplementAPI &&\n\t\tclbCfg.ImplementMode != ConfigBcsClbImplementSDK {\n\t\tblog.Errorf(\"implement type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbImplement)\n\t\treturn fmt.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbImplement)\n\t}\n\tclbCfg.BackendMode = os.Getenv(ConfigBcsClbBackendMode)\n\tif clbCfg.BackendMode != ConfigBcsClbBackendModeENI &&\n\t\tclbCfg.BackendMode != ConfigBcsClbBackendModeCVM {\n\t\tblog.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbBackendMode)\n\t\treturn fmt.Errorf(\"backend type [%s] from env %s is invalid\", clbCfg.BackendMode, ConfigBcsClbBackendMode)\n\t}\n\tclbCfg.Region = os.Getenv(ConfigBcsClbRegion)\n\tif !CheckRegion(clbCfg.Region) {\n\t\tblog.Errorf(\"region [%s] is invalid\", clbCfg.Region)\n\t\treturn fmt.Errorf(\"region [%s] is invalid\", clbCfg.Region)\n\t}\n\tclbCfg.SecretID = os.Getenv(ConfigBcsClbSecretID)\n\tif len(clbCfg.SecretID) == 0 {\n\t\tblog.Errorf(\"secret id cannot be empty\")\n\t\treturn fmt.Errorf(\"secret id cannot be empty\")\n\t}\n\tclbCfg.SecretKey = os.Getenv(ConfigBcsClbSecretKey)\n\tif len(clbCfg.SecretKey) == 0 {\n\t\tblog.Errorf(\"secret key cannot be empty\")\n\t\treturn fmt.Errorf(\"secret key cannot be empty\")\n\t}\n\n\tprojectID := os.Getenv(ConfigBcsClbProjectID)\n\tif len(projectID) == 0 {\n\t\tblog.Errorf(\"project id cannot be empty\")\n\t\treturn fmt.Errorf(\"project id cannot be empty\")\n\t}\n\tclbCfg.ProjectID, err = strconv.Atoi(projectID)\n\tif err != nil {\n\t\tblog.Errorf(\"convert project id %s to int failed, err %s\", projectID, err.Error())\n\t\treturn fmt.Errorf(\"convert project id %s to int failed, err %s\", projectID, err.Error())\n\t}\n\tclbCfg.VpcID = os.Getenv(ConfigBcsClbVpcID)\n\tif len(clbCfg.VpcID) == 0 {\n\t\tblog.Errorf(\"vpc id cannot be empty\")\n\t\treturn fmt.Errorf(\"vpc id cannot be empty\")\n\t}\n\n\t//load expire time\n\texpireTime := os.Getenv(ConfigBcsClbExpireTime)\n\tif len(expireTime) != 0 {\n\t\teTime, err := strconv.Atoi(expireTime)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"expire time %s invalid, set default value 0\", expireTime)\n\t\t\tclbCfg.ExpireTime = 0\n\t\t} else {\n\t\t\t//expire time: range 30~3600\n\t\t\tif eTime < 30 {\n\t\t\t\tclbCfg.ExpireTime = 30\n\t\t\t} else if eTime > 3600 {\n\t\t\t\tclbCfg.ExpireTime = 3600\n\t\t\t} else {\n\t\t\t\tclbCfg.ExpireTime = eTime\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//default 0: means do not set expire time\n\t\tclbCfg.ExpireTime = 0\n\t}\n\n\tclbCfg.SubnetID = os.Getenv(ConfigBcsClbSubnet)\n\tmaxTimeout := os.Getenv(ConfigBcsClbMaxTimeout)\n\tif len(maxTimeout) != 0 {\n\t\ttimeout, err := strconv.Atoi(maxTimeout)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert max timeout %s to int error, err %s, set default value 180\", maxTimeout, err.Error())\n\t\t\tclbCfg.MaxTimeout = DefaultClbMaxTimeout\n\t\t} else {\n\t\t\tclbCfg.MaxTimeout = timeout\n\t\t}\n\t} else {\n\t\tclbCfg.MaxTimeout = DefaultClbMaxTimeout\n\t}\n\twaitPeriodExceedLimit := os.Getenv(ConfigBcsClbWaitPeriodExceedLimit)\n\tif len(waitPeriodExceedLimit) != 0 {\n\t\tperiod, err := strconv.Atoi(waitPeriodExceedLimit)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert wait period exceed limit %s to int error, err %s, set default value 10\",\n\t\t\t\twaitPeriodExceedLimit, err.Error())\n\t\t\tclbCfg.WaitPeriodExceedLimit = DefaultClbWaitPeriodExceedLimit\n\t\t} else {\n\t\t\tclbCfg.WaitPeriodExceedLimit = period\n\t\t}\n\t} else {\n\t\tclbCfg.WaitPeriodExceedLimit = DefaultClbWaitPeriodExceedLimit\n\t}\n\twaitPeriodLBDealing := os.Getenv(ConfigBcsClbWaitPeriodDealing)\n\tif len(waitPeriodLBDealing) != 0 {\n\t\tperiod, err := strconv.Atoi(waitPeriodLBDealing)\n\t\tif err != nil {\n\t\t\tblog.Errorf(\"convert wait period lb dealing limit %s to int error, err %s, set default value 3\",\n\t\t\t\twaitPeriodLBDealing, err.Error())\n\t\t\tclbCfg.WaitPeriodLBDealing = DefaultClbWaitPeriodDealing\n\t\t} else {\n\t\t\tclbCfg.WaitPeriodLBDealing = period\n\t\t}\n\t} else {\n\t\tclbCfg.WaitPeriodLBDealing = DefaultClbWaitPeriodDealing\n\t}\n\n\tblog.Infof(\"load clb config successfully\\n\")\n\treturn nil\n}", "func EnvConfigFileGenerator() error {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn types.Error{Msg: execErr.Error()}\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\n\tenvContent, _ := json.MarshalIndent(&EnvConfig{\n\t\tDataBaseFile: cwd + \"/\" + global.DatabaseFilePath,\n\t\tPort: global.DefaultPort,\n\t}, \"\", \" \")\n\n\treturn ioutil.WriteFile(fileString, envContent, 0755)\n}", "func (c *Config) Validate() error {\n\tvar errs []error\n\n\tif len(c.Hosts) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"missing hosts\"))\n\t}\n\tif c.Port == \"\" {\n\t\terrs = append(errs, fmt.Errorf(\"missing port\"))\n\t}\n\n\treturn apierrors.NewAggregate(errs)\n}", "func CheckEnvVars() error {\n\n\tenvVars := []string{\n\t\t\"HUSKYCI_CLIENT_API_ADDR\",\n\t\t\"HUSKYCI_CLIENT_REPO_URL\",\n\t\t\"HUSKYCI_CLIENT_REPO_BRANCH\",\n\t\t// \"HUSKYCI_CLIENT_TOKEN\", (optional for now)\n\t\t// \"HUSKYCI_CLIENT_API_USE_HTTPS\", (optional)\n\t\t// \"HUSKYCI_CLIENT_NPM_DEP_URL\", (optional)\n\t}\n\n\tvar envIsSet bool\n\tvar allEnvIsSet bool\n\tvar errorString string\n\n\tenv := make(map[string]string)\n\tallEnvIsSet = true\n\tfor i := 0; i < len(envVars); i++ {\n\t\tenv[envVars[i]], envIsSet = os.LookupEnv(envVars[i])\n\t\tif !envIsSet {\n\t\t\terrorString = errorString + envVars[i] + \" \"\n\t\t\tallEnvIsSet = false\n\t\t}\n\t}\n\tif !allEnvIsSet {\n\t\treturn errors.New(errorString)\n\t}\n\treturn nil\n}", "func LoadConfig() (bool, *Config) {\n\tconfig := new(Config)\n\tconfigEnvironment := os.Getenv(\"ENVIRONMENT_TYPE\")\n\t// Default to the development config since it is safer\n\tconfigFileName := \"config-dev.json\"\n\n\tif configEnvironment == \"PROD\" {\n\t\t// Development Environment\n\t\tconfigFileName = \"config-prod.json\"\n\t}\n\n\t// Open our jsonFile\n\tjsonFile, err := os.Open(configFileName)\n\t// if we os.Open returns an error then handle it and return an empty config\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false, config\n\t}\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\n\tjsonParser := json.NewDecoder(jsonFile)\n\n\tparseError := jsonParser.Decode(config)\n\tif parseError != nil {\n\t\t// Return config as is, program will end anyway as we return false here\n\t\tfmt.Println(err)\n\t\treturn false, config\n\t}\n\treturn true, config\n}", "func (c Config) Validate() error {\n\tif len(c.Project) == 0 {\n\t\treturn errors.New(\"missing project in configuration\")\n\t}\n\tif len(c.Bucket) == 0 {\n\t\treturn errors.New(\"missing bucket in configuration\")\n\t}\n\tif len(c.LastMigrationObjectName) == 0 {\n\t\treturn errors.New(\"missing state name in configuration\")\n\t}\n\treturn nil\n}", "func mustGetEnv(t *testing.T, key string) string {\n\tt.Helper()\n\tval := os.Getenv(key)\n\trequire.NotEmpty(t, val, \"%s environment variable must be set and not empty\", key)\n\treturn val\n}", "func LoadCfgFromEnv(e *Env) (*Cfg, error) {\n\tvar env Env\n\tvar err error\n\tif e == nil {\n\t\tif err = cli.SetEnvFields(&env); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\te = &env\n\t}\n\tc := &Cfg{\n\t\tSrc: \"Environment\",\n\t\tTenantID: e.TenantID,\n\t\tSubscriptionID: e.SubscriptionID,\n\t}\n\tif e.EnvName == \"\" || strings.EqualFold(e.EnvName, \"AzureCloud\") {\n\t\tc.Environment = azure.PublicCloud\n\t} else {\n\t\tc.Environment, err = azure.EnvironmentFromName(e.EnvName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif e.ClientSecret != \"\" {\n\t\terr = c.useClientSecret(e.ClientID, e.ClientSecret)\n\t} else if e.CertFile != \"\" {\n\t\terr = c.useClientCert(e.ClientID, e.CertFile, e.CertPass)\n\t} else {\n\t\terr = fmt.Errorf(\"az: client secret or cert file must be specified\")\n\t}\n\tif err != nil {\n\t\tc = nil\n\t}\n\treturn c, err\n}", "func (cfg *Config) Validate() error {\n\tif cfg.DisableValidation {\n\t\treturn nil\n\t}\n\n\tif _, err := os.Stat(cfg.KernelImagePath); err != nil {\n\t\treturn fmt.Errorf(\"failed to stat kernel image path, %q: %v\", cfg.KernelImagePath, err)\n\t}\n\n\tif cfg.InitrdPath != \"\" {\n\t\tif _, err := os.Stat(cfg.InitrdPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to stat initrd image path, %q: %v\", cfg.InitrdPath, err)\n\t\t}\n\t}\n\n\tfor _, drive := range cfg.Drives {\n\t\tif BoolValue(drive.IsRootDevice) {\n\t\t\trootPath := StringValue(drive.PathOnHost)\n\t\t\tif _, err := os.Stat(rootPath); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to stat host drive path, %q: %v\", rootPath, err)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Check the non-existence of some files:\n\tif _, err := os.Stat(cfg.SocketPath); err == nil {\n\t\treturn fmt.Errorf(\"socket %s already exists\", cfg.SocketPath)\n\t}\n\n\tif cfg.MachineCfg.VcpuCount == nil ||\n\t\tInt64Value(cfg.MachineCfg.VcpuCount) < 1 {\n\t\treturn fmt.Errorf(\"machine needs a nonzero VcpuCount\")\n\t}\n\tif cfg.MachineCfg.MemSizeMib == nil ||\n\t\tInt64Value(cfg.MachineCfg.MemSizeMib) < 1 {\n\t\treturn fmt.Errorf(\"machine needs a nonzero amount of memory\")\n\t}\n\tif cfg.MachineCfg.HtEnabled == nil {\n\t\treturn fmt.Errorf(\"machine needs a setting for ht_enabled\")\n\t}\n\treturn nil\n}", "func (e *Environment) Validate() error {\n\treturn validator.New().Struct(e)\n}", "func checkEnvVars(id string, secret string) bool {\n\tvar envVarsExist bool = true\n\tif id == \"\" || secret == \"\" {\n\t\tenvVarsExist = false\n\t}\n\treturn envVarsExist\n}", "func VerifyConfiguration() error {\n\tif _, err := readSteps(files.Root); err != nil {\n\t\treturn err\n\t}\n\n\tinfo, err := os.Stat(filepath.Join(files.Root, \".demoit\"))\n\tif os.IsNotExist(err) {\n\t\treturn errors.New(`mandatory resource folder \".demoit\" doesn't exist`)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !info.IsDir() {\n\t\treturn errors.New(`mandatory resource folder \".demoit\" is not a folder`)\n\t}\n\n\treturn nil\n}", "func (c configuration) Validate() error {\n\tvar errs error\n\n\terrs = errors.Append(errs, c.Auth.Validate())\n\terrs = errors.Append(errs, c.Config.Validate())\n\n\tif c.Environment == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"environment is required\"))\n\t}\n\n\t// TODO: this config is only used here, so the validation is here too. Either the config or the validation should be moved somewhere else.\n\tif c.Distribution.PKE.Amazon.GlobalRegion == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"pke amazon global region is required\"))\n\t}\n\n\treturn errs\n}", "func (cfg *Config) UpdateFromEnvs() (err error) {\n\tcfg.mu.Lock()\n\tdefer func() {\n\t\tcfg.unsafeSync()\n\t\tcfg.mu.Unlock()\n\t}()\n\n\tvar vv interface{}\n\tvv, err = parseEnvs(AWS_K8S_TESTER_EC2_PREFIX, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif av, ok := vv.(*Config); ok {\n\t\tcfg = av\n\t} else {\n\t\treturn fmt.Errorf(\"expected *Config, got %T\", vv)\n\t}\n\n\tif cfg.S3 == nil {\n\t\tcfg.S3 = &S3{}\n\t}\n\tvv, err = parseEnvs(AWS_K8S_TESTER_EC2_PREFIX+\"S3_\", cfg.S3)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif av, ok := vv.(*S3); ok {\n\t\tcfg.S3 = av\n\t} else {\n\t\treturn fmt.Errorf(\"expected *S3, got %T\", vv)\n\t}\n\n\tif cfg.Role == nil {\n\t\tcfg.Role = &Role{}\n\t}\n\tvv, err = parseEnvs(AWS_K8S_TESTER_EC2_PREFIX+\"ROLE_\", cfg.Role)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif av, ok := vv.(*Role); ok {\n\t\tcfg.Role = av\n\t} else {\n\t\treturn fmt.Errorf(\"expected *Role, got %T\", vv)\n\t}\n\n\tif cfg.VPC == nil {\n\t\tcfg.VPC = &VPC{}\n\t}\n\tvv, err = parseEnvs(AWS_K8S_TESTER_EC2_PREFIX+\"VPC_\", cfg.VPC)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif av, ok := vv.(*VPC); ok {\n\t\tcfg.VPC = av\n\t} else {\n\t\treturn fmt.Errorf(\"expected *VPC, got %T\", vv)\n\t}\n\n\treturn nil\n}", "func (t TaskConfig) validate() error {\n\tvar err error\n\tif err = t.Platform.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"platform\": %w`, err)\n\t}\n\tif err = t.Count.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"count\": %w`, err)\n\t}\n\tif err = t.ExecuteCommand.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"exec\": %w`, err)\n\t}\n\tif err = t.Storage.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"storage\": %w`, err)\n\t}\n\tfor n, v := range t.Variables {\n\t\tif err := v.validate(); err != nil {\n\t\t\treturn fmt.Errorf(`validate %q \"variables\": %w`, n, err)\n\t\t}\n\t}\n\tfor _, v := range t.Secrets {\n\t\tif err := v.validate(); err != nil {\n\t\t\treturn fmt.Errorf(`validate \"secret\": %w`, err)\n\t\t}\n\t}\n\tif t.EnvFile != nil {\n\t\tenvFile := aws.StringValue(t.EnvFile)\n\t\tif filepath.Ext(envFile) != envFileExt {\n\t\t\treturn fmt.Errorf(\"environment file %s must have a %s file extension\", envFile, envFileExt)\n\t\t}\n\t}\n\treturn nil\n}", "func IsValidEnv(env string) bool {\n\treturn slice.HasString(env, validEnvs)\n}", "func TestBadConfig(t *testing.T) {\n\tif os.Getenv(\"BE_CRASHER\") == \"1\" {\n\t\tconfig := config.FromFile(configFile)\n\n\t\t// Make config invalid\n\t\tconfig.TelnetAddress = \"-1\"\n\n\t\tbootstrap.NewBootstrap(config)\n\t\treturn\n\t}\n\tcmd := exec.Command(os.Args[0], \"-test.run=TestBadConfig\")\n\tcmd.Env = append(os.Environ(), \"BE_CRASHER=1\")\n\terr := cmd.Run()\n\tif e, ok := err.(*exec.ExitError); ok && !e.Success() {\n\t\treturn\n\t}\n\tt.Fatalf(\"Did not fail run with invalid config.json values, Test exited with status 0, expected 1\")\n}", "func readConfig() (*config, error) {\n\tcfgPath := *configPath\n\tuserSpecified := *configPath != \"\"\n\n\tvar homeDir string\n\tif testHomeDir != \"\" {\n\t\thomeDir = testHomeDir\n\t} else {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thomeDir = u.HomeDir\n\t}\n\n\tif !userSpecified {\n\t\tcfgPath = filepath.Join(homeDir, \"src-config.json\")\n\t} else if strings.HasPrefix(cfgPath, \"~/\") {\n\t\tcfgPath = filepath.Join(homeDir, cfgPath[2:])\n\t}\n\tdata, err := os.ReadFile(os.ExpandEnv(cfgPath))\n\tif err != nil && (!os.IsNotExist(err) || userSpecified) {\n\t\treturn nil, err\n\t}\n\tvar cfg config\n\tif err == nil {\n\t\tcfg.ConfigFilePath = cfgPath\n\t\tif err := json.Unmarshal(data, &cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tenvToken := os.Getenv(\"SRC_ACCESS_TOKEN\")\n\tenvEndpoint := os.Getenv(\"SRC_ENDPOINT\")\n\n\tif userSpecified {\n\t\t// If a config file is present, either zero or both environment variables must be present.\n\t\t// We don't want to partially apply environment variables.\n\t\tif envToken == \"\" && envEndpoint != \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t\tif envToken != \"\" && envEndpoint == \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t}\n\n\t// Apply config overrides.\n\tif envToken != \"\" {\n\t\tcfg.AccessToken = envToken\n\t}\n\tif envEndpoint != \"\" {\n\t\tcfg.Endpoint = envEndpoint\n\t}\n\tif cfg.Endpoint == \"\" {\n\t\tcfg.Endpoint = \"https://sourcegraph.com\"\n\t}\n\n\tcfg.AdditionalHeaders = parseAdditionalHeaders()\n\t// Ensure that we're not clashing additonal headers\n\t_, hasAuthorizationAdditonalHeader := cfg.AdditionalHeaders[\"authorization\"]\n\tif cfg.AccessToken != \"\" && hasAuthorizationAdditonalHeader {\n\t\treturn nil, errConfigAuthorizationConflict\n\t}\n\n\t// Lastly, apply endpoint flag if set\n\tif endpoint != nil && *endpoint != \"\" {\n\t\tcfg.Endpoint = *endpoint\n\t}\n\n\tcfg.Endpoint = cleanEndpoint(cfg.Endpoint)\n\n\treturn &cfg, nil\n}", "func setupEnv() config.Config {\n\trequiredEnvVars := []string {\n\t\tconfig.EnvURL,\n\t\tconfig.EnvPort,\n\t}\n\n\tfor _, key := range requiredEnvVars {\n\t\t_, exists := os.LookupEnv(key)\n\t\tif !exists {\n\t\t\tfmt.Printf(\"Environment mismatch. Missing required: %s\\n\", key)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tclientURL := os.Getenv(config.EnvURL)\n\tport := os.Getenv(config.EnvPort)\n\n\treturn config.Config{MemDBSchema: config.DBSchema, SSEServerUrl: clientURL, PORT: port}\n}", "func (s3ce *S3ConfigExecutor) Validate(config *gateways.ConfigContext) error {\n\tartifact, err := parseConfig(config.Data.Config)\n\tif err != nil {\n\t\treturn gateways.ErrConfigParseFailed\n\t}\n\tif artifact == nil {\n\t\treturn gateways.ErrEmptyConfig\n\t}\n\tif artifact.S3EventConfig == nil {\n\t\treturn fmt.Errorf(\"%+v, s3 bucket configuration can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.AccessKey == nil {\n\t\treturn fmt.Errorf(\"%+v, access key can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.SecretKey == nil {\n\t\treturn fmt.Errorf(\"%+v, secret key can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Endpoint == \"\" {\n\t\treturn fmt.Errorf(\"%+v, endpoint url can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Bucket == \"\" {\n\t\treturn fmt.Errorf(\"%+v, bucket name can't be empty\", gateways.ErrInvalidConfig)\n\t}\n\tif artifact.S3EventConfig.Event != \"\" && minio.NotificationEventType(artifact.S3EventConfig.Event) == \"\" {\n\t\treturn fmt.Errorf(\"%+v, unknown event %s\", gateways.ErrInvalidConfig, artifact.S3EventConfig.Event)\n\t}\n\treturn nil\n}", "func ParseConfig () error {\n\tfile := os.Getenv(\"API_CONFIG\") // try the env variable\n\tif len(file) == 0 { file = \"./config.json\" } // if there's no env variable then use the local config file\n\n\tconfigFile, err := os.Open(file) //try the file\n\tif err != nil { return errors.WithStack (err) }\n\t\n\tjsonParser := json.NewDecoder(configFile)\n\terr = jsonParser.Decode(&CFG)\n\tif err != nil { return errors.WithStack (err) }\n\n\t// validate some expected values\n\tif !CFG.ApiUrl.Url() {\n\t\treturn errors.Errorf (\"ApiUrl from config file appears invalid, this shoudl be a url that this service is listening on\")\n\t}\n\n\t// validate anything else\n\t\n\treturn nil\n}", "func (project *Project) HasDirEnv() bool {\n\t_, err := os.Stat(\".envrc\")\n\treturn !os.IsNotExist(err)\n}", "func TestGetConfigInfoWithoutIndexdCreds(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"Expecting getConfigInfo to panic since Indexd creds were not present in CONFIG_FILE\")\n\t\t}\n\t}()\n\n\tjsonConfigInfo :=\n\t\t`\n\t{\n\t\t\"metadataService\": {\n\t\t\t\"url\": \"http://revproxy-service/mds\",\n\t\t\t\"username\": \"mr friendly cat\",\n\t\t\t\"password\": \"paws\"\n\t\t}\n\t}\n\t`\n\terr := os.Setenv(\"CONFIG_FILE\", jsonConfigInfo)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgetConfigInfo()\n}", "func EnsureENVSet() (ok bool) {\n\tNotifierPort := os.Getenv(\"NOTIFIER_QUEUE_PORT\")\n\tSendGridAPIKey := os.Getenv(\"SENDGRID_API_KEY\")\n\n\tif NotifierPort == \"\" || SendGridAPIKey == \"\" {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func ConfigFromEnv(set *flag.FlagSet) error {\n\tvar errs []string\n\tset.VisitAll(func(f *flag.Flag) {\n\t\tval := os.Getenv(f.Name)\n\t\tif val == \"\" {\n\t\t\terrs = append(errs, fmt.Sprintf(\"env variable %s missing\", f.Name))\n\t\t\treturn\n\t\t}\n\t\tif err := f.Value.Set(val); err != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"failed to set flag %q with value %q - %s\\n\", f.Name, val, err))\n\n\t\t}\n\t})\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(strings.Join(errs, \", \"))\n\t}\n\treturn nil\n}", "func ValidateInputs() error {\n\tif len(os.Getenv(token)) == 0 {\n\t\treturn fmt.Errorf(\"%v is required env variable to trigger this action\", token)\n\t}\n\n\tpath := getBranchProtectionConfigPath()\n\texists, _ := utils.FileExists(path)\n\tif !exists {\n\t\treturn fmt.Errorf(\"ensure if config file %v exists\", path)\n\t}\n\n\treturn nil\n}", "func TestAWSCloudValidation(t *testing.T) {\n\tos.Setenv(\"CLOUD_NAME\", \"CLOUD_AWS\")\n\tutils.SetCloudName(\"CLOUD_AWS\")\n\tos.Setenv(\"SERVICE_TYPE\", \"NodePort\")\n\tos.Setenv(\"VIP_NETWORK_LIST\", `[]`)\n\n\taddConfigMap(t)\n\n\tif !ctrl.DisableSync {\n\t\tt.Fatalf(\"CLOUD_AWS should not be allowed if VIP_NETWORK_LIST is empty\")\n\t}\n\tDeleteConfigMap(t)\n\tos.Setenv(\"VIP_NETWORK_LIST\", `[{\"networkName\":\"net123\"}]`)\n}", "func checkUpEnvironment() {\n\tPlatform = os.Getenv(\"K8S_PLATFORM\")\n\tK8sVersion = os.Getenv(\"K8S_VERSION\")\n\n\tExpect(os.Getenv(\"MCLI_ORG_ID\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_ORG_ID environment variable\")\n\tExpect(os.Getenv(\"MCLI_PUBLIC_API_KEY\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_PUBLIC_API_KEY environment variable\")\n\tExpect(os.Getenv(\"MCLI_PRIVATE_API_KEY\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_PRIVATE_API_KEY environment variable\")\n\tExpect(os.Getenv(\"MCLI_OPS_MANAGER_URL\")).ShouldNot(BeEmpty(), \"Please, setup MCLI_OPS_MANAGER_URL environment variable\")\n\tmongocli.GetVersionOutput()\n}", "func (c *Config) IsEnv(env string) bool {\n\treturn c.Env == env\n}" ]
[ "0.6562439", "0.62982637", "0.61907583", "0.6190635", "0.61768216", "0.6167497", "0.6142193", "0.6075432", "0.59580684", "0.5939767", "0.59289217", "0.59287024", "0.5899801", "0.5876768", "0.58302706", "0.58222914", "0.5819233", "0.57605153", "0.5738932", "0.5725181", "0.56841415", "0.56823474", "0.56730175", "0.5624182", "0.5617714", "0.5599786", "0.55974054", "0.5597068", "0.55913043", "0.5591082", "0.55854976", "0.5583714", "0.55696267", "0.55672544", "0.5563583", "0.5555923", "0.55556536", "0.5554098", "0.5552738", "0.5547599", "0.55450505", "0.55443233", "0.5516922", "0.5512355", "0.5502237", "0.5500174", "0.54871476", "0.5484689", "0.5469068", "0.54626703", "0.54606956", "0.5443934", "0.54425395", "0.54398954", "0.5433705", "0.5431921", "0.5430776", "0.54304534", "0.5415836", "0.5414244", "0.5400809", "0.53982943", "0.5384131", "0.5367562", "0.5353381", "0.53520674", "0.5349077", "0.5345462", "0.53407615", "0.5334465", "0.5331836", "0.5319544", "0.5310464", "0.52980804", "0.52973235", "0.5297209", "0.52953714", "0.52944237", "0.52925503", "0.5287653", "0.5284645", "0.5279276", "0.5269164", "0.5266685", "0.526664", "0.52648115", "0.52620476", "0.5250513", "0.5243958", "0.52418995", "0.52389055", "0.5238043", "0.5237933", "0.52273524", "0.52244467", "0.5222941", "0.521973", "0.5218968", "0.5217573", "0.5214122" ]
0.76962256
0
EnvConfigFileReader reads the env_config json file and returns the config data as a struct
func EnvConfigFileReader() *EnvConfig { execName, execErr := os.Executable() cwd := filepath.Dir(execName) if execErr != nil { localLogger(execErr.Error(), global.StatusError) return nil } fileString := cwd + "/" + global.EnvFileName envFile, err := os.Open(fileString) var envConfig *EnvConfig if err != nil { localLogger(err.Error(), global.StatusError) return nil } else { if fileContent, openErr := ioutil.ReadAll(envFile); openErr == nil { unMarshallErr := json.Unmarshal(fileContent, &envConfig) if unMarshallErr == nil { return envConfig } else { localLogger(unMarshallErr.Error(), global.StatusError) return nil } } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func readEnviromentFile() *ServerEnv {\n\tvar serverEnv ServerEnv\n\tjsonFile, err := os.Open(\"dist/env.json\")\n\tif err != nil {\n\t\tfmt.Printf(\":0 PANIK , enviroment json not attempting local dir found\")\n\t\tjsonFile, err = os.Open(\"env.json\")\n\t\tif err != nil {\n\t\t\tpanic(\":0 PANIK , enviroment json not found\")\n\t\t}\n\t}\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\terr = json.Unmarshal(byteValue, &serverEnv)\n\tif err != nil {\n\t\tpanic(\":0 PANIK , enviroment json could not decode\")\n\t}\n\treturn &serverEnv\n}", "func loadEnvironmentConfig(env string) types.Options {\n\tconfigFile := \"config/\" + ServiceName + \"/\" + env + \".json\"\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\treturn parseConfigFile(configFile)\n}", "func ReadConfigFile(configFile string) {\n\tfileBytes, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to load configuration file %s\", configFile)\n\t\tpanic(err)\n\t}\n\n\tif hasJSONPrefix(fileBytes) {\n\t\terr = json.Unmarshal(fileBytes, &Config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\terr = yaml.Unmarshal(fileBytes, &Config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Next section allows env variable overwrites config file value\n\tfields := reflect.TypeOf(Config)\n\t// pointer to struct\n\tvalues := reflect.ValueOf(&Config)\n\t// struct\n\tst := values.Elem()\n\tfor i := 0; i < fields.NumField(); i++ {\n\t\tfield := fields.Field(i).Name\n\t\tf := st.FieldByName(field)\n\n\t\tif f.Kind() == reflect.String {\n\t\t\tenvV := os.Getenv(field)\n\t\t\tif len(envV) > 0 && f.IsValid() && f.CanSet() {\n\t\t\t\tf.SetString(strings.TrimSuffix(envV, \"\\n\")) // ensure no \\n at the end of line that was introduced by loading k8s secrete file\n\t\t\t}\n\t\t\tos.Setenv(field, f.String())\n\t\t}\n\t}\n\n\tif IsPulsarJWTEnabled() {\n\t\tSuperRoles = []string{}\n\t\tfor _, v := range strings.Split(Config.SuperRoles, \",\") {\n\t\t\tSuperRoles = append(SuperRoles, strings.TrimSpace(v))\n\t\t}\n\t} else {\n\t\tSuperRoles = []string{DummySuperRole}\n\t}\n\n\tlog.Infof(\"configuration loaded is %v\", Config)\n}", "func ReadConfig() *error {\n\tvar env = os.Getenv(\"ENV\")\n\n\tgame.Appartement.Bots = Config.Bots\n\tfile, err := os.Open(\"/env/config.\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Println(prefixWarn, \"ENV must be of: 'localhost', 'dev' or 'prod'. starting with default configuration\")\n\t\treturn &err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn &err\n\t}\n\n\treturn nil\n}", "func configFromFile(env string) (Config, error) {\n\tenv = strings.ToLower(env)\n\t// attempt to read config from {{environment}}.yml (defaults to development.yml)\n\tvar fname string\n\tvar conf Config\n\tif _, err := os.Stat(fmt.Sprintf(\"config/%s.yml\", env)); err == nil {\n\t\tfname = fmt.Sprintf(\"config/%s.yml\", env)\n\t} else {\n\t\tfname = fmt.Sprintf(\"config/development.yml\")\n\t}\n\n\tymlFile, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\terr = yaml.Unmarshal(ymlFile, &conf)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\treturn conf, nil\n\n}", "func (r *Reader) getProvidersFromEnv(filePath string) (\n\tproviders []provider.Provider, warnings []string, err error) {\n\ts := os.Getenv(\"CONFIG\")\n\tif s == \"\" {\n\t\treturn nil, nil, nil\n\t}\n\tr.logger.Info(\"reading JSON config from environment variable CONFIG\")\n\tr.logger.Debug(\"config read: \" + s)\n\n\tb := []byte(s)\n\n\tproviders, warnings, err = extractAllSettings(b)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"configuration given: %w\", err)\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\terr = json.Indent(buffer, b, \"\", \" \")\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\tconst mode = fs.FileMode(0600)\n\terr = r.writeFile(filePath, buffer.Bytes(), mode)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\n\treturn providers, warnings, nil\n}", "func readConfig() (*config, error) {\n\tcfgPath := *configPath\n\tuserSpecified := *configPath != \"\"\n\n\tvar homeDir string\n\tif testHomeDir != \"\" {\n\t\thomeDir = testHomeDir\n\t} else {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thomeDir = u.HomeDir\n\t}\n\n\tif !userSpecified {\n\t\tcfgPath = filepath.Join(homeDir, \"src-config.json\")\n\t} else if strings.HasPrefix(cfgPath, \"~/\") {\n\t\tcfgPath = filepath.Join(homeDir, cfgPath[2:])\n\t}\n\tdata, err := os.ReadFile(os.ExpandEnv(cfgPath))\n\tif err != nil && (!os.IsNotExist(err) || userSpecified) {\n\t\treturn nil, err\n\t}\n\tvar cfg config\n\tif err == nil {\n\t\tcfg.ConfigFilePath = cfgPath\n\t\tif err := json.Unmarshal(data, &cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tenvToken := os.Getenv(\"SRC_ACCESS_TOKEN\")\n\tenvEndpoint := os.Getenv(\"SRC_ENDPOINT\")\n\n\tif userSpecified {\n\t\t// If a config file is present, either zero or both environment variables must be present.\n\t\t// We don't want to partially apply environment variables.\n\t\tif envToken == \"\" && envEndpoint != \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t\tif envToken != \"\" && envEndpoint == \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t}\n\n\t// Apply config overrides.\n\tif envToken != \"\" {\n\t\tcfg.AccessToken = envToken\n\t}\n\tif envEndpoint != \"\" {\n\t\tcfg.Endpoint = envEndpoint\n\t}\n\tif cfg.Endpoint == \"\" {\n\t\tcfg.Endpoint = \"https://sourcegraph.com\"\n\t}\n\n\tcfg.AdditionalHeaders = parseAdditionalHeaders()\n\t// Ensure that we're not clashing additonal headers\n\t_, hasAuthorizationAdditonalHeader := cfg.AdditionalHeaders[\"authorization\"]\n\tif cfg.AccessToken != \"\" && hasAuthorizationAdditonalHeader {\n\t\treturn nil, errConfigAuthorizationConflict\n\t}\n\n\t// Lastly, apply endpoint flag if set\n\tif endpoint != nil && *endpoint != \"\" {\n\t\tcfg.Endpoint = *endpoint\n\t}\n\n\tcfg.Endpoint = cleanEndpoint(cfg.Endpoint)\n\n\treturn &cfg, nil\n}", "func readConfig(configFilePath string) *Config {\n\t// fmt.Println(\"doing readConfig\")\n\tfile, err := os.Open(configFilePath)\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := new(Config)\n\terr = decoder.Decode(config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn config\n}", "func ReadEnv(configString []byte) []string {\n\treturn regexp.MustCompile(`\\$\\{[a-zA-Z0-9_\\-]+\\}`).FindAllString(string(configString), -1)\n}", "func ReadFromFileAndEnv(settings interface{}) error {\n\tfile, err := os.Open(\"appsettings.json\")\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer file.Close()\n\tdata, err := ioutil.ReadAll(file)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to read appsettings\")\n\t}\n\n\terr = json.Unmarshal(data, settings)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to unmarshal appsettings\")\n\t}\n\n\terr = envconfig.Init(settings)\n\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"Failed to update with env vars\")\n\t}\n\treturn err\n}", "func readConfigJSON(configFile string) error {\n\tconfigByte, err := ioutil.ReadFile(configFile)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(configByte, &config); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ReadConfig(dest interface{}, filename string) error {\n\tfile, err := os.Open(filename)\n\tif err == nil {\n\t\tdefer file.Close()\n\t\tdecoder := json.NewDecoder(file)\n\t\terr := decoder.Decode(dest)\n\t\treturn err\n\t}\n\treturn err\n}", "func Env() (*Config, error) {\n\treturn readConfig(\"\", \"\")\n}", "func GetConfigData(f string, mergeEnv bool) (interface{}, error) {\n\tvar conf interface{}\n\t// First load any env data from files\n\tlogDebug.Printf(\"Loading config file:%s\\n\", f)\n\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading file '%s':%s\", f, err)\n\t}\n\tlogInfo.Printf(\"Loaded config data from %s\", f)\n\t// Allow templating of config data (e.g. env overrides of chart values):\n\tk8api := NewK8ApiNoop()\n\trendered, _, err := Render(k8api, string(b), EnvToMap())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error trying to render config data file '%s':%s\",\n\t\t\tf,\n\t\t\terr)\n\t}\n\n\t// Load yaml\n\tif err := yaml.Unmarshal([]byte(rendered), &conf); err != nil {\n\t\treturn nil, err\n\t}\n\t// Update any values which DON't exist from environment\n\tif mergeEnv && reflect.TypeOf(conf).Kind() == reflect.Map {\n\t\tconfTyped := conf.(map[interface{}]interface{})\n\t\tfor k, v := range EnvToMap() {\n\t\t\tif _, ok := confTyped[k]; !ok {\n\t\t\t\t// Value NOT found - update map:\n\t\t\t\tconfTyped[k] = v\n\t\t\t\tlogDebug.Printf(\"updated key %s from environment\", k)\n\t\t\t}\n\t\t}\n\t\t// Replace the referenced data with the strongly typed reference\n\t\tconf = confTyped\n\t}\n\treturn conf, nil\n}", "func configReader(conf string) {\n\tviper.AddConfigPath(\".\")\n\tviper.SetConfigFile(conf)\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(\"Fatal error, can't read the config file: \", err)\n\t}\n\n\t// Get basic settings\n\tregion = viper.GetString(\"region\")\n\tstackname = viper.GetString(\"stackname\")\n\n\t// Get all the values of variables under CF\n\t// and put them into a map\n\tcfvars = make(map[string]interface{})\n\tfor _, confvar := range viper.Sub(\"CF\").AllKeys() {\n\t\tif confvar != \"\" {\n\t\t\tconfval := viper.Get(\"CF.\" + confvar)\n\t\t\tcfvars[confvar] = confval\n\t\t}\n\t}\n}", "func readConfig() config {\n\tfile, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error Opening Config File: \", err)\n\t}\n\tconfigData := config{}\n\n\terr = json.Unmarshal([]byte(file), &configData)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error Parsing Config File: \", err)\n\t}\n\treturn configData\n}", "func ReadConfig(input io.Reader) (*specs.Spec, error) {\n\td := json.NewDecoder(input)\n\ts := specs.Spec{}\n\tif err := d.Decode(&s); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}", "func readConfigFile(path string) (config *Config, err error) {\n\tvar file *os.File\n\tfile, err = os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tconfig = new(Config)\n\terr = json.NewDecoder(file).Decode(config)\n\treturn config, err\n}", "func (config *configuration) getEnvVariables() error {\n\t// method 1: Decode json file\n\tfile, err := os.Open(confFile)\n\tif err != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Open config file error.\", err)\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoderErr := decoder.Decode(&config)\n\tif decoderErr != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Decode config file error.\", decoderErr)\n\t\treturn decoderErr\n\t}\n\n\t// method 2: Unmarshal json file\n\t// jsonData, err := ioutil.ReadFile(confFile)\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// unmarshalErr := json.Unmarshal(jsonData, &config)\n\t// if unmarshalErr != nil {\n\t// \treturn unmarshalErr\n\t// }\n\treturn nil\n}", "func readConfig(fileName string) (*gabs.Container, error) {\n\t// Read file\n\tfileBytes, readErr := ioutil.ReadFile(fileName)\n\n\tif readErr != nil {\n\t\treturn nil, readErr\n\t}\n\n\t// Convert to usable map\n\tparsedJson, parsedJsonErr := gabs.ParseJSON(fileBytes)\n\n\tif parsedJsonErr != nil {\n\t\treturn nil, parsedJsonErr\n\t}\n\n\treturn parsedJson, nil\n}", "func readConfig(name string, data interface{}) error {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\treturn json.NewDecoder(file).Decode(data)\n}", "func ReadConfig(r io.Reader, allowEnvironmentOverrides bool) (*model.Config, map[string]interface{}, error) {\n\t// Pre-flight check the syntax of the configuration file to improve error messaging.\n\tconfigData, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t} else {\n\t\tvar rawConfig interface{}\n\t\tif err := json.Unmarshal(configData, &rawConfig); err != nil {\n\t\t\treturn nil, nil, jsonutils.HumanizeJsonError(err, configData)\n\t\t}\n\t}\n\n\tv := newViper(allowEnvironmentOverrides)\n\tif err := v.ReadConfig(bytes.NewReader(configData)); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar config model.Config\n\tunmarshalErr := v.Unmarshal(&config)\n\t// https://github.com/spf13/viper/issues/324\n\t// https://github.com/spf13/viper/issues/348\n\tif unmarshalErr == nil {\n\t\tconfig.PluginSettings.Plugins = make(map[string]map[string]interface{})\n\t\tunmarshalErr = v.UnmarshalKey(\"pluginsettings.plugins\", &config.PluginSettings.Plugins)\n\t}\n\tif unmarshalErr == nil {\n\t\tconfig.PluginSettings.PluginStates = make(map[string]*model.PluginState)\n\t\tunmarshalErr = v.UnmarshalKey(\"pluginsettings.pluginstates\", &config.PluginSettings.PluginStates)\n\t}\n\n\tenvConfig := v.EnvSettings()\n\n\tvar envErr error\n\tif envConfig, envErr = fixEnvSettingsCase(envConfig); envErr != nil {\n\t\treturn nil, nil, envErr\n\t}\n\n\treturn &config, envConfig, unmarshalErr\n}", "func readConfig() Configuration {\n\tfmt.Println(\"Reading configuration file\")\n\n\tdir, _ := filepath.Abs(filepath.Dir(os.Args[0]))\n\tfilepath := []string{dir, \"config.json\"}\n\n\tfile, _ := os.Open(strings.Join(filepath, \"\\\\\"))\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn configuration\n}", "func readConfig() {\n\tconfigPath := io.FixPrefixPath(viper.GetString(\"datadir\"), viper.GetString(\"config\"))\n\n\tif io.FileExists(configPath) {\n\t\tmergeLocalConfig(configPath)\n\t} else {\n\t\tfmt.Println(\"config file not exist \", configPath)\n\t\tmergeOnlineConfig(viper.GetString(\"config\"))\n\t}\n\n\t// load injected config from ogbootstrap if any\n\tinjectedPath := io.FixPrefixPath(viper.GetString(\"datadir\"), \"injected.toml\")\n\tif io.FileExists(injectedPath) {\n\t\tmergeLocalConfig(injectedPath)\n\t}\n\n\tmergeEnvConfig()\n\tb, err := common.PrettyJson(viper.AllSettings())\n\tpanicIfError(err, \"dump json\")\n\tfmt.Println(b)\n}", "func Read() (*Config, error) {\n\tcfg := &Config{}\n\n\tif err := env.Parse(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func (parser envParser) Parse(r io.Reader) (interface{}, error) {\n\tcnf, ok := r.(*conf)\n\tif !ok {\n\t\treturn nil, errs.New(0, \"provided reader must be a a *conf pointer\")\n\t}\n\tcnf.values = ValueMap{}\n\tfor _, e := range os.Environ() {\n\t\tp1 := strings.Split(e, \"\\n\")\n\t\tif len(p1) > 0 {\n\t\t\tp2 := strings.Split(p1[0], \"=\")\n\t\t\tswitch {\n\t\t\tcase \"_\" == p2[0]:\n\t\t\t\tcontinue\n\t\t\tcase strings.HasPrefix(p2[0], \"BASH_FUNC_\"):\n\t\t\t\tcontinue\n\t\t\tcase \"\" != cnf.envPrefix && !strings.HasPrefix(p2[0], cnf.envPrefix):\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcnf.values[p2[0]] = NewVal(String, os.Getenv(p2[0]))\n\t\t}\n\t}\n\treturn cnf, nil\n}", "func Read(configPath string) (*schema.Configuration, []error) {\n\tviper.SetEnvPrefix(\"AUTHELIA\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\t// we need to bind all env variables as long as https://github.com/spf13/viper/issues/761\n\t// is not resolved.\n\tviper.BindEnv(\"jwt_secret\")\n\tviper.BindEnv(\"duo_api.secret_key\")\n\tviper.BindEnv(\"session.secret\")\n\tviper.BindEnv(\"authentication_backend.ldap.password\")\n\tviper.BindEnv(\"notifier.smtp.password\")\n\tviper.BindEnv(\"session.redis.password\")\n\tviper.BindEnv(\"storage.mysql.password\")\n\tviper.BindEnv(\"storage.postgres.password\")\n\n\tviper.SetConfigFile(configPath)\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treturn nil, []error{fmt.Errorf(\"unable to find config file %s\", configPath)}\n\t\t}\n\t}\n\n\tvar configuration schema.Configuration\n\tviper.Unmarshal(&configuration)\n\n\tval := schema.NewStructValidator()\n\tvalidator.Validate(&configuration, val)\n\n\tif val.HasErrors() {\n\t\treturn nil, val.Errors()\n\t}\n\n\treturn &configuration, nil\n}", "func ReadConfig(filename string) (c Config) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = json.Unmarshal(data, &c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func ReadConfig(fn string) (settings *Config) {\n // read from config file if exists\n b, err := ioutil.ReadFile(fn)\n if err != nil {\n log.Fatal(\"config file: \", err)\n }\n\n // parse json config\n var data map[string]interface{}\n if err := json.Unmarshal(b, &data); err != nil {\n log.Fatal(\"config file: \", err)\n }\n \n // test required properties\n for _, v := range requiredKeys {\n _, ok := data[v]\n if !ok {\n log.Fatal(\"config file: \" + v + \" is missing in \" + fn)\n }\n }\n\n // convert\n config := make(map[string]string)\n for k, v := range data {\n config[k] = v.(string)\n }\n\n return NewConfig(config)\n}", "func (conf *BuildConfig) Read(path string) error {\n\tf, err := os.Open(filepath.Clean(path))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tcloseErr := f.Close()\n\t\tif closeErr != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\tval, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(val, &conf.Config)\n\treturn err\n}", "func readConfig(settingFile string) ConfigJSON {\n\traw, err := ioutil.ReadFile(settingFile)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tvar s ConfigJSON\n\tjson.Unmarshal(raw, &s)\n\treturn s\n}", "func ReadConfig(config interface{}, allOptions ...Option) error {\n if reflect.TypeOf(config).Kind() != reflect.Ptr {\n return errors.Errorf(\n \"ReadConfig requires a pointer to your config struct, %[1]T \" +\n \"was provided but a *%[1]T is required\",\n config,\n )\n }\n opts := newOptions(allOptions)\n paths := opts.configPath\n envPrefix := opts.envVarPrefix\n envVar := fmt.Sprintf(\"%s_CONFIG_FILE\", envPrefix)\n if newPath, exists := os.LookupEnv(envVar); exists {\n paths = append([]string{newPath}, paths...)\n }\n\n found := false\n for _, path := range paths {\n configReader, err := opts.pathReader.Read(path)\n if err != nil {\n logging.Warn(\n \"Failed to load config data from file.\", logging.Extras{\n \"error\": err,\n \"path\": path,\n },\n )\n continue\n }\n configBytes, err := ioutil.ReadAll(configReader)\n if err != nil {\n return errors.Wrap(\n err, \"Error while reading data returned from path\",\n )\n }\n\n err = unmarshalConfigBytes(configBytes, config)\n if err != nil {\n return errors.Wrap(\n err, \"Error while reading data from config file\",\n )\n }\n\n for key, embedded := range opts.embeddedConfigs {\n if reflect.TypeOf(embedded).Kind() != reflect.Ptr {\n return errors.Errorf(\n \"ReadConfig requires a pointer to your embedded \" +\n \"config(s), %[1]T was provided but a *%[1]T is \" +\n \"required\",\n embedded,\n )\n }\n err = readEmbeddedConfig(configBytes, key, embedded)\n if err != nil {\n return errors.Wrap(\n err, \"Error while reading embedded config\",\n )\n }\n }\n\n found = true\n break\n }\n\n if !found {\n return errors.Errorf(\n \"Couldn't load any of the provided paths %v\", paths,\n )\n }\n\n err := readConfigFromEnvironment(config, envPrefix)\n if err != nil {\n return errors.Wrap(\n err, \"Error while reading config values from environment\",\n )\n }\n\n for key, embedded := range opts.embeddedConfigs {\n err := readConfigFromEnvironment(\n embedded, envPrefix, strings.ToUpper(key),\n )\n if err != nil {\n return errors.Wrap(\n err,\n \"Error while reading embedded config values from environment\",\n )\n }\n }\n\n return nil\n}", "func readConfig(configPath string ) (DBconfig, error) {\n\n\tjsonFile, err := os.Open(configPath); if err != nil {\n\t\tlog.Printf(\"Error openning file for config path : %v, error : %v\", configPath, err.Error())\n\t\treturn DBconfig{}, err\n\t}\n\tdefer jsonFile.Close()\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar DBconfig = DBconfig{}\n\tjson.Unmarshal(byteValue, &DBconfig)\n\n\treturn DBconfig, nil\n}", "func ReadConfig(r io.Reader) (*Config, error) {\n\tdecoder := json.NewDecoder(r)\n\tconfig := Config{}\n\terr := decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, &ConfigError{\n\t\t\tmsg: \"Invalid config file format\",\n\t\t\tinner: err,\n\t\t}\n\t}\n\n\tif config.Certificate != \"\" {\n\t\t_, err = os.Stat(config.Certificate)\n\t\tif err != nil {\n\t\t\treturn nil, &ConfigError{\n\t\t\t\tmsg: \"Cannot access certificate file `\" +\n\t\t\t\t\tconfig.Certificate + \"' \",\n\t\t\t\tinner: err,\n\t\t\t}\n\t\t}\n\t}\n\tif config.PrivateKey != \"\" {\n\t\t_, err = os.Stat(config.PrivateKey)\n\t\tif err != nil {\n\t\t\treturn nil, &ConfigError{\n\t\t\t\tmsg: \"Cannot access private key file `\" +\n\t\t\t\t\tconfig.PrivateKey + \"' \",\n\t\t\t\tinner: err,\n\t\t\t}\n\t\t}\n\t}\n\tif (config.Certificate != \"\" && config.PrivateKey == \"\") ||\n\t\t(config.Certificate == \"\" && config.PrivateKey != \"\") {\n\t\treturn nil, &ConfigError{\n\t\t\tmsg: \"To use https, both certificate and private-key must be specified\",\n\t\t\tinner: nil,\n\t\t}\n\t}\n\n\treturn &config, nil\n}", "func ReadConfig(file string) (*Config, error) {\n\n\tc := new(Config)\n\n\tlocalIP := net.ParseIP(\"127.0.0.1\")\n\n\t// defaults\n\tc.FlowAPI.Bind = fmt.Sprintf(\"%s:7777\", localIP)\n\tc.FlowAPI.Endpoint = c.FlowAPI.Bind\n\n\tc.IngressAPI.Bind = fmt.Sprintf(\"%s:6666\", localIP)\n\tc.IngressAPI.Endpoint = c.IngressAPI.Bind\n\n\tc.IsolateAPI.Bind = fmt.Sprintf(\"%s:8888\", localIP)\n\tc.IsolateAPI.Endpoint = c.IsolateAPI.Bind\n\tc.IsolateAPI.Isolation = \"vorteil\"\n\n\tc.SecretsAPI.Bind = fmt.Sprintf(\"%s:2610\", localIP)\n\tc.SecretsAPI.Endpoint = c.SecretsAPI.Bind\n\n\tc.Minio.Endpoint = \"127.0.0.1:9000\"\n\tc.Minio.User = \"vorteil\"\n\tc.Minio.Password = \"vorteilvorteil\"\n\tc.Minio.Encrypt = c.Minio.Password\n\tc.Minio.Region = \"us-east-1\"\n\n\tc.Kernel.Runtime = \"21.3.5\"\n\tc.Kernel.Linux = \"21.3.5\"\n\n\t// read config file if exists\n\tif len(file) > 0 {\n\n\t\tlog.Printf(\"read config file %s\", file)\n\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\terr = toml.Unmarshal(data, c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\t// overwrite with envs\n\tints := []struct {\n\t\tname string\n\t\tvalue *int\n\t}{\n\t\t{minioSecure, &c.Minio.Secure},\n\t\t{minioSSL, &c.Minio.SSL},\n\t\t{certSecure, &c.Certs.Secure},\n\t}\n\n\tfor _, i := range ints {\n\t\terr := setInt(c, i.name, i.value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstrings := []struct {\n\t\tname string\n\t\tvalue *string\n\t}{\n\t\t{dbConn, &c.Database.DB},\n\t\t{minioEndpoint, &c.Minio.Endpoint},\n\t\t{minioUser, &c.Minio.User},\n\t\t{minioPassword, &c.Minio.Password},\n\t\t{minioEncrypt, &c.Minio.Encrypt},\n\t\t{instanceLoggingDriver, &c.InstanceLogging.Driver},\n\t\t{minioRegion, &c.Minio.Region},\n\t\t{kernelLinux, &c.Kernel.Linux},\n\t\t{kernelRuntime, &c.Kernel.Runtime},\n\t\t{flowBind, &c.FlowAPI.Bind},\n\t\t{flowEndpoint, &c.FlowAPI.Endpoint},\n\t\t{flowRegistry, &c.FlowAPI.Registry.Name},\n\t\t{flowRegistryUser, &c.FlowAPI.Registry.User},\n\t\t{flowRegistryToken, &c.FlowAPI.Registry.Token},\n\t\t{ingressBind, &c.IngressAPI.Bind},\n\t\t{ingressEndpoint, &c.IngressAPI.Endpoint},\n\t\t{isolateBind, &c.IsolateAPI.Bind},\n\t\t{isolateEndpoint, &c.IsolateAPI.Endpoint},\n\t\t{secretsBind, &c.SecretsAPI.Bind},\n\t\t{secretsEndpoint, &c.SecretsAPI.Endpoint},\n\t\t{secretsConn, &c.SecretsAPI.DB},\n\t\t{certDir, &c.Certs.Directory},\n\t\t{isolation, &c.IsolateAPI.Isolation},\n\t}\n\n\tfor _, i := range strings {\n\t\terr := setString(c, i.name, i.value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// test database is set\n\tif len(c.Database.DB) == 0 && len(c.SecretsAPI.DB) == 0 {\n\t\treturn nil, fmt.Errorf(\"no database configured\")\n\t}\n\n\treturn c, nil\n\n}", "func ReadEnvironmentFromMemory() (*Environment, error) {\n\tdata, err := ioutil.ReadFile(filepath.FromSlash(fmt.Sprintf(\"%s/config/environment.json\", common.DataDir))) // Read file\n\n\tif err != nil { // Check for errors\n\t\treturn &Environment{}, err // Return error\n\t}\n\n\tbuffer := &Environment{} // Initialize buffer\n\n\terr = json.Unmarshal(data, buffer) // Read json into buffer\n\n\tif err != nil { // Check for errors\n\t\treturn &Environment{}, err // Return error\n\t}\n\n\treturn buffer, nil // No error occurred, return read config\n}", "func ReadConfigFile(file string) types.Config {\n\tvar data types.Config\n\tjsonFile, err := os.Open(file)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tdefer jsonFile.Close()\n\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\tjson.Unmarshal(byteValue, &data)\n\n\treturn data\n}", "func readConfig() (config Config) {\n\tconfigJson, _ := Asset(\"config.json\")\n\terr := json.Unmarshal(configJson, &config)\n\tif err != nil {\n\t\tprintError(CONFIG_READ_ERROR + err.Error())\n\t}\n\treturn config\n}", "func ReadConfigFile(filename string) (*Config, error) {\n\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read config file %q: %v\", filename, err)\n\t}\n\n\tdec := json.NewDecoder(bytes.NewReader(data))\n\n\tvar out Config\n\tif err := dec.Decode(&out); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not decode config file %q: %v\", filename, err)\n\t}\n\n\treturn &out, nil\n}", "func (ec *ExecutionContext) readConfig() error {\n\tvar op errors.Op = \"cli.ExecutionContext.readConfig\"\n\t// need to get existing viper because https://github.com/spf13/viper/issues/233\n\tv := ec.Viper\n\tv.SetEnvPrefix(util.ViperEnvPrefix)\n\tv.SetEnvKeyReplacer(util.ViperEnvReplacer)\n\tv.AutomaticEnv()\n\tv.SetConfigName(\"config\")\n\tv.SetDefault(\"version\", \"1\")\n\tv.SetDefault(\"endpoint\", \"http://localhost:8080\")\n\tv.SetDefault(\"admin_secret\", \"\")\n\tv.SetDefault(\"access_key\", \"\")\n\tv.SetDefault(\"api_paths.query\", \"v1/query\")\n\tv.SetDefault(\"api_paths.v2_query\", \"v2/query\")\n\tv.SetDefault(\"api_paths.v1_metadata\", \"v1/metadata\")\n\tv.SetDefault(\"api_paths.graphql\", \"v1/graphql\")\n\tv.SetDefault(\"api_paths.config\", \"v1alpha1/config\")\n\tv.SetDefault(\"api_paths.pg_dump\", \"v1alpha1/pg_dump\")\n\tv.SetDefault(\"api_paths.version\", \"v1/version\")\n\tv.SetDefault(\"metadata_directory\", DefaultMetadataDirectory)\n\tv.SetDefault(\"migrations_directory\", DefaultMigrationsDirectory)\n\tv.SetDefault(\"seeds_directory\", DefaultSeedsDirectory)\n\tv.SetDefault(\"actions.kind\", \"synchronous\")\n\tv.SetDefault(\"actions.handler_webhook_baseurl\", \"http://localhost:3000\")\n\tv.SetDefault(\"actions.codegen.framework\", \"\")\n\tv.SetDefault(\"actions.codegen.output_dir\", \"\")\n\tv.SetDefault(\"actions.codegen.uri\", \"\")\n\tv.AddConfigPath(ec.ExecutionDirectory)\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"cannot read config from file/env: %w\", err))\n\t}\n\tadminSecret := v.GetString(\"admin_secret\")\n\tif adminSecret == \"\" {\n\t\tadminSecret = v.GetString(\"access_key\")\n\t}\n\n\t// Admin secrets can be specified as a string value of format\n\t// [\"secret1\", \"secret2\"], similar to how the corresponding environment variable\n\t// HASURA_GRAPHQL_ADMIN_SECRETS is configured with the server\n\tadminSecretsList := v.GetString(\"admin_secrets\")\n\tadminSecrets := []string{}\n\tif len(adminSecretsList) > 0 {\n\t\tif err = json.Unmarshal([]byte(adminSecretsList), &adminSecrets); err != nil {\n\t\t\treturn errors.E(op, fmt.Errorf(\"parsing 'admin_secrets' from config.yaml / environment variable HASURA_GRAPHQL_ADMIN_SECRETS failed: expected value of format [\\\"secret1\\\", \\\"secret2\\\"]: %w\", err))\n\t\t}\n\t}\n\n\tec.Config = &Config{\n\t\tVersion: ConfigVersion(v.GetInt(\"version\")),\n\t\tDisableInteractive: v.GetBool(\"disable_interactive\"),\n\t\tServerConfig: ServerConfig{\n\t\t\tEndpoint: v.GetString(\"endpoint\"),\n\t\t\tAdminSecret: adminSecret,\n\t\t\tAdminSecrets: adminSecrets,\n\t\t\tAPIPaths: &ServerAPIPaths{\n\t\t\t\tV1Query: v.GetString(\"api_paths.query\"),\n\t\t\t\tV2Query: v.GetString(\"api_paths.v2_query\"),\n\t\t\t\tV1Metadata: v.GetString(\"api_paths.v1_metadata\"),\n\t\t\t\tGraphQL: v.GetString(\"api_paths.graphql\"),\n\t\t\t\tConfig: v.GetString(\"api_paths.config\"),\n\t\t\t\tPGDump: v.GetString(\"api_paths.pg_dump\"),\n\t\t\t\tVersion: v.GetString(\"api_paths.version\"),\n\t\t\t},\n\t\t\tInsecureSkipTLSVerify: v.GetBool(\"insecure_skip_tls_verify\"),\n\t\t\tCAPath: v.GetString(\"certificate_authority\"),\n\t\t},\n\t\tMetadataDirectory: v.GetString(\"metadata_directory\"),\n\t\tMetadataFile: v.GetString(\"metadata_file\"),\n\t\tMigrationsDirectory: v.GetString(\"migrations_directory\"),\n\t\tSeedsDirectory: v.GetString(\"seeds_directory\"),\n\t\tActionConfig: &types.ActionExecutionConfig{\n\t\t\tKind: v.GetString(\"actions.kind\"),\n\t\t\tHandlerWebhookBaseURL: v.GetString(\"actions.handler_webhook_baseurl\"),\n\t\t\tCodegen: &types.CodegenExecutionConfig{\n\t\t\t\tFramework: v.GetString(\"actions.codegen.framework\"),\n\t\t\t\tOutputDir: v.GetString(\"actions.codegen.output_dir\"),\n\t\t\t\tURI: v.GetString(\"actions.codegen.uri\"),\n\t\t\t},\n\t\t},\n\t}\n\tif !ec.Config.Version.IsValid() {\n\t\treturn errors.E(op, ErrInvalidConfigVersion)\n\t}\n\terr = ec.Config.ServerConfig.ParseEndpoint()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"unable to parse server endpoint: %w\", err))\n\t}\n\treturn nil\n}", "func EnvConfigValidator() error {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn execErr\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\t_, openErr := os.Open(fileString)\n\n\tif openErr != nil {\n\t\tlocalLogger(openErr.Error(), global.StatusError)\n\t\treturn openErr\n\t} else {\n\t\tif envContent := EnvConfigFileReader(); envContent == nil {\n\t\t\tlocalLogger(\"Unable to read env file\", global.StatusError)\n\t\t\treturn types.Error{Msg: \"Invalid content in env_config file\"}\n\t\t}\n\t}\n\treturn nil\n}", "func ReadAndExtractEnv(filename, keyDir, privateKey string) (map[string]string, error) {\n\tsecrets, err := readSecrets(filename, keyDir, privateKey)\n\tif nil != err {\n\t\treturn map[string]string{}, fmt.Errorf(\"could not load ejson file: %s\", err)\n\t}\n\n\treturn ExtractEnv(secrets)\n}", "func ReadConfig(data []byte) (Config, error) {\n\tconfig := NewConfig()\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\tlog.Printf(\"unable to unmarshal application configuration file data, error: %s\\n\", err.Error())\n\t\treturn config, err\n\t}\n\n\tif err := config.Validate(); err != nil {\n\t\treturn config, err\n\t}\n\n\tlog.Printf(\"Configuration loaded. Source type: %s, Destination type: %s\\n\", config.Source.Type, config.Destination.Type)\n\tlog.Printf(\"%v Sync sets found:\\n\", len(config.SyncSets))\n\n\tfor i, syncSet := range config.SyncSets {\n\t\tlog.Printf(\" %v) %s\\n\", i+1, syncSet.Name)\n\t}\n\n\treturn config, nil\n}", "func readConfig(file string) wConfig {\n\tvar c = wConfig{}\n\t_, err := os.Stat(file)\n\tif err == nil {\n\t\tf, _ := os.Open(file)\n\t\tdefer f.Close()\n\t\tdecoder := json.NewDecoder(f)\n\t\terr := decoder.Decode(&c)\n\t\tcheck(err)\n\t} else {\n\t\tif !os.IsNotExist(err) {\n\t\t\tlog.Fatalf(\"Unable to read %s: %s\\n\", file, err)\n\t\t}\n\t}\n\treturn c\n}", "func RRReadConfig() {\n\tfolderPath, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// fmt.Printf(\"Executable folder = %s\\n\", folderPath)\n\tfname := folderPath + \"/conf.json\"\n\t_, err = os.Stat(fname)\n\tif nil != err {\n\t\tfmt.Printf(\"RRReadConfig: error reading %s: %v\\n\", fname, err)\n\t\tos.Exit(1)\n\t}\n\tcontent, err := ioutil.ReadFile(fname)\n\tErrcheck(err)\n\tErrcheck(json.Unmarshal(content, &AppConfig))\n\t// fmt.Printf(\"RRReadConfig: AppConfig = %#v\\n\", AppConfig)\n}", "func ConfigLoadReader(r io.Reader) (*Config, error) {\n\tc := ConfigNew()\n\tif err := json.NewDecoder(r).Decode(c); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn nil, err\n\t}\n\t// verify loaded version is not higher than supported version\n\tif c.Version > 1 {\n\t\treturn c, ErrUnsupportedConfigVersion\n\t}\n\tfor h := range c.Hosts {\n\t\tif c.Hosts[h].Name == \"\" {\n\t\t\tc.Hosts[h].Name = h\n\t\t}\n\t\tif c.Hosts[h].Hostname == \"\" {\n\t\t\tc.Hosts[h].Hostname = h\n\t\t}\n\t\tif c.Hosts[h].TLS == regclient.TLSUndefined {\n\t\t\tc.Hosts[h].TLS = regclient.TLSEnabled\n\t\t}\n\t\tif h == regclient.DockerRegistryDNS || h == regclient.DockerRegistry {\n\t\t\tc.Hosts[h].Name = regclient.DockerRegistry\n\t\t\tif c.Hosts[h].Hostname == h {\n\t\t\t\tc.Hosts[h].Hostname = regclient.DockerRegistryDNS\n\t\t\t}\n\t\t}\n\t\tif c.Hosts[h].Name != h {\n\t\t\tc.Hosts[c.Hosts[h].Name] = c.Hosts[h]\n\t\t\tdelete(c.Hosts, h)\n\t\t}\n\t}\n\treturn c, nil\n}", "func (a *App) readConfig() {\n\tvar configLocation string\n\tif _, err := os.Stat(\"./configs\"); err == nil {\n\t\tconfigLocation = \"./configs\"\n\t}\n\n\ta.Config = config.NewEnvFile(configLocation)\n}", "func (c *Config) ReadEnvironment() error {\n\tvar envAddress string\n\tvar envAgentAddress string\n\tvar envCACert string\n\tvar envCACertBytes []byte\n\tvar envCAPath string\n\tvar envClientCert string\n\tvar envClientKey string\n\tvar envClientTimeout time.Duration\n\tvar envInsecure bool\n\tvar envTLSServerName string\n\tvar envMaxRetries *uint64\n\tvar envSRVLookup bool\n\tvar limit *rate.Limiter\n\tvar envVaultProxy string\n\tvar envVaultDisableRedirects bool\n\n\t// Parse the environment variables\n\tif v := os.Getenv(EnvVaultAddress); v != \"\" {\n\t\tenvAddress = v\n\t}\n\tif v := os.Getenv(EnvVaultAgentAddr); v != \"\" {\n\t\tenvAgentAddress = v\n\t}\n\tif v := os.Getenv(EnvVaultMaxRetries); v != \"\" {\n\t\tmaxRetries, err := strconv.ParseUint(v, 10, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tenvMaxRetries = &maxRetries\n\t}\n\tif v := os.Getenv(EnvVaultCACert); v != \"\" {\n\t\tenvCACert = v\n\t}\n\tif v := os.Getenv(EnvVaultCACertBytes); v != \"\" {\n\t\tenvCACertBytes = []byte(v)\n\t}\n\tif v := os.Getenv(EnvVaultCAPath); v != \"\" {\n\t\tenvCAPath = v\n\t}\n\tif v := os.Getenv(EnvVaultClientCert); v != \"\" {\n\t\tenvClientCert = v\n\t}\n\tif v := os.Getenv(EnvVaultClientKey); v != \"\" {\n\t\tenvClientKey = v\n\t}\n\tif v := os.Getenv(EnvRateLimit); v != \"\" {\n\t\trateLimit, burstLimit, err := parseRateLimit(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlimit = rate.NewLimiter(rate.Limit(rateLimit), burstLimit)\n\t}\n\tif t := os.Getenv(EnvVaultClientTimeout); t != \"\" {\n\t\tclientTimeout, err := parseutil.ParseDurationSecond(t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %q\", EnvVaultClientTimeout)\n\t\t}\n\t\tenvClientTimeout = clientTimeout\n\t}\n\tif v := os.Getenv(EnvVaultSkipVerify); v != \"\" {\n\t\tvar err error\n\t\tenvInsecure, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultSkipVerify)\n\t\t}\n\t}\n\tif v := os.Getenv(EnvVaultSRVLookup); v != \"\" {\n\t\tvar err error\n\t\tenvSRVLookup, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultSRVLookup)\n\t\t}\n\t}\n\n\tif v := os.Getenv(EnvVaultTLSServerName); v != \"\" {\n\t\tenvTLSServerName = v\n\t}\n\n\tif v := os.Getenv(EnvHTTPProxy); v != \"\" {\n\t\tenvVaultProxy = v\n\t}\n\n\t// VAULT_PROXY_ADDR supersedes VAULT_HTTP_PROXY\n\tif v := os.Getenv(EnvVaultProxyAddr); v != \"\" {\n\t\tenvVaultProxy = v\n\t}\n\n\tif v := os.Getenv(EnvVaultDisableRedirects); v != \"\" {\n\t\tvar err error\n\t\tenvVaultDisableRedirects, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse %s\", EnvVaultDisableRedirects)\n\t\t}\n\n\t\tc.DisableRedirects = envVaultDisableRedirects\n\t}\n\n\t// Configure the HTTP clients TLS configuration.\n\tt := &TLSConfig{\n\t\tCACert: envCACert,\n\t\tCACertBytes: envCACertBytes,\n\t\tCAPath: envCAPath,\n\t\tClientCert: envClientCert,\n\t\tClientKey: envClientKey,\n\t\tTLSServerName: envTLSServerName,\n\t\tInsecure: envInsecure,\n\t}\n\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\n\tc.SRVLookup = envSRVLookup\n\tc.Limiter = limit\n\n\tif err := c.configureTLS(t); err != nil {\n\t\treturn err\n\t}\n\n\tif envAddress != \"\" {\n\t\tc.Address = envAddress\n\t}\n\n\tif envAgentAddress != \"\" {\n\t\tc.AgentAddress = envAgentAddress\n\t}\n\n\tif envMaxRetries != nil {\n\t\tc.MaxRetries = int(*envMaxRetries)\n\t}\n\n\tif envClientTimeout != 0 {\n\t\tc.Timeout = envClientTimeout\n\t}\n\n\tif envVaultProxy != \"\" {\n\t\tu, err := url.Parse(envVaultProxy)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttransport := c.HttpClient.Transport.(*http.Transport)\n\t\ttransport.Proxy = http.ProxyURL(u)\n\t}\n\n\treturn nil\n}", "func readConfig(configfile string) (map[string]*json.RawMessage, error) {\n\n\tvar (\n\t\tfile []byte\n\t\tobjmap map[string]*json.RawMessage\n\t\terr error\n\t)\n\n\tfile, err = ioutil.ReadFile(configfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlines := strings.Split(string(file), \"\\n\")\n\tvar jdata []byte\n\tfor _, line := range lines {\n\t\tif !strings.HasPrefix(strings.TrimSpace(line), \"//\") {\n\t\t\tjdata = append(jdata, []byte(line+\"\\n\")...)\n\t\t}\n\t}\n\n\terr = json.Unmarshal(jdata, &objmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objmap, nil\n}", "func ReadVTGRConfig(file string) (*VTGRConfig, error) {\n\tvtgrFile, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(vtgrFile)\n\terr = decoder.Decode(vtgrCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn vtgrCfg, nil\n}", "func ReadEnv(c interface{}) {\r\n\tfor _, value := range os.Environ() {\r\n\t\tif strings.HasPrefix(value, \"ENV_\") {\r\n\t\t\tkv := strings.SplitN(value,\"=\",2)\r\n\t\t\tkv[0] = strings.ToLower(strings.Replace(kv[0],\"_\",\".\",-1))[4:]\r\n\t\t\tSetData(c,strings.Join(kv,\"=\"))\r\n\t\t}\r\n\t}\r\n}", "func Read() (*viper.Viper, error) {\n\n\t// Viper config management initialization\n\t// Support either json or yaml file types (json for backwards compatibility\n\t// with previous versions)\n\tcfg.SetConfigType(\"json\")\n\tcfg.SetConfigType(\"yaml\")\n\tcfg.SetConfigName(\"director_config\")\n\tcfg.AddConfigPath(\".\")\n\n\t// Read in config file using Viper\n\terr := cfg.ReadInConfig()\n\tif err != nil {\n\t\tcfgLog.WithError(err).Fatal(\"Fatal error reading config file\")\n\t}\n\n\t// Bind this envvars to viper config vars.\n\t// https://github.com/spf13/viper#working-with-environment-variables\n\t// One important thing to recognize when working with ENV variables is\n\t// that the value will be read each time it is accessed. Viper does not\n\t// fix the value when the BindEnv is called.\n\tfor cfgKey, envVar := range envMappings {\n\t\terr = cfg.BindEnv(cfgKey, envVar)\n\n\t\tif err != nil {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\": envVar,\n\t\t\t\t\"error\": err.Error(),\n\t\t\t\t\"module\": \"config\",\n\t\t\t}).Warn(\"Unable to bind environment var as a config variable\")\n\n\t\t} else {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\": envVar,\n\t\t\t\t\"module\": \"config\",\n\t\t\t}).Info(\"Binding environment var as a config variable\")\n\t\t}\n\t}\n\n\t// Look for updates to the config; in Kubernetes, this is implemented using\n\t// a ConfigMap that is written to the matchmaker_config.yaml file, which is\n\t// what the Open Match components using Viper monitor for changes.\n\t// More details about Open Match's use of Kubernetes ConfigMaps at:\n\t// https://github.com/GoogleCloudPlatform/open-match/issues/42\n\tcfg.WatchConfig() // Watch and re-read config file.\n\treturn cfg, err\n}", "func readConfig(c *cli.Context) (service.Config, error) {\n\typath := c.GlobalString(\"config\")\n\tconfig := service.Config{}\n\tif _, err := os.Stat(ypath); err != nil {\n\t\treturn config, errors.New(\"config file path is not valid\")\n\t}\n\tydata, err := ioutil.ReadFile(ypath)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\terr = yaml.Unmarshal([]byte(ydata), &config)\n\treturn config, err\n}", "func ReadConfig(configFile string) (*Config, error) {\n\tcontent, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cfg Config\n\terr = json.Unmarshal(content, &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}", "func ReadConfig(fn string) (*Configuration, error) {\n\tdata, err := getRawConfig(fn)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"reading config data for '%s'\", fn)\n\t}\n\n\tc := newTestConfig()\n\tc.filename = fn\n\t// we don't take the lock here because this function doesn't\n\t// spawn threads, and nothing else can see the object we're\n\t// building. If either of those things change we should take\n\t// the lock here.\n\n\tif err = json.Unmarshal(data, c); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"parsing config '%s'\", fn)\n\t}\n\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif err = c.parseTests(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"parsing tests from file '%s'\", fn)\n\t}\n\n\tgrip.Infoln(\"loading config file:\", fn)\n\n\treturn c, nil\n}", "func getConfigFile() ([]byte, error) {\n\tif len(configFile) != 0 {\n\t\treturn configFile, nil\n\t}\n\tenvConf := os.Getenv(\"IGOR_CONFIG\")\n\tif envConf != \"\" {\n\t\treturn []byte(envConf), nil\n\t}\n\tfilename, _ := filepath.Abs(\"./config.json\")\n\tif _, err := os.Stat(filename); err != nil {\n\t\tjsonConfig = false\n\t\tfilename, _ = filepath.Abs(\"./config.yml\")\n\t}\n\tconfigFile, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn configFile, err\n\t}\n\treturn configFile, nil\n}", "func EnvConfigFileGenerator() error {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn types.Error{Msg: execErr.Error()}\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\n\tenvContent, _ := json.MarshalIndent(&EnvConfig{\n\t\tDataBaseFile: cwd + \"/\" + global.DatabaseFilePath,\n\t\tPort: global.DefaultPort,\n\t}, \"\", \" \")\n\n\treturn ioutil.WriteFile(fileString, envContent, 0755)\n}", "func ParserConfig(_struct interface{}) error {\n\tpath := \"/var/arposter/config.json\"\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(&_struct); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ParseEnvFile(envInput io.Reader) (map[string]string, error) {\n\tenvMap := make(map[string]string)\n\n\tscanner := bufio.NewScanner(envInput)\n\tvar line string\n\tlineNumber := 0\n\n\tfor scanner.Scan() {\n\t\tline = strings.TrimSpace(scanner.Text())\n\t\tlineNumber++\n\n\t\t// skip lines starting with comment\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// skip empty line\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.SplitN(line, \"=\", 2)\n\t\tif len(fields) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Can't parse line %d; line should be in KEY=VALUE format\", lineNumber)\n\t\t}\n\n\t\tif strings.Contains(fields[0], \" \") {\n\t\t\treturn nil, fmt.Errorf(\"Can't parse line %d; KEY contains whitespace\", lineNumber)\n\t\t}\n\n\t\tkey := fields[0]\n\t\tval := fields[1]\n\n\t\tif key == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"Can't parse line %d; KEY can't be empty string\", lineNumber)\n\t\t}\n\t\tenvMap[key] = val\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn envMap, nil\n}", "func ReadConfig() (Config, error) {\n\tif len(os.Args) > 1 {\n\t\treturn readFile(os.Args[1])\n\t}\n\n\tfor _, f := range []string{\"/etc/craftdoor/master.json\", \"./develop.json\"} {\n\t\t_, err := os.Stat(f)\n\t\tif err == nil {\n\t\t\treturn readFile(f)\n\t\t}\n\t}\n\n\treturn Config{}, fmt.Errorf(\"could not find config file\")\n}", "func ReadConfig(configFlag string) Configuration {\n\tabsPath, errPath := filepath.Abs(configFlag)\n\tif errPath != nil {\n\t\tlog.Fatalf(\"abspath error %v\", absPath)\n\t\tpanic(errPath)\n\t}\n\tlog.Printf(\"[DEBUG] absPath:: %v \", absPath)\n\tconfigFile, err := ioutil.ReadFile(absPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdata := Configuration{}\n\tjsonErr := json.Unmarshal([]byte(configFile), &data)\n\tif jsonErr != nil {\n\t\tpanic(jsonErr)\n\t}\n\treturn data\n}", "func ConfigFileReader(filePath string) (map[string][]map[string]string, error) {\n\t// file path is the configuration file which is written in yaml\n\tvar config map[string][]map[string]string\n\t// opening config file\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn config, fmt.Errorf(\"unable to parse config file %v file \", err)\n\t}\n\n\tdefer file.Close()\n\n\tif yaml.NewDecoder(file).Decode(&config); err != nil {\n\t\treturn config, fmt.Errorf(\"unable to decode file %v file \", err)\n\t}\n\treturn config, nil\n}", "func ReadConfig(filename string) Config {\n\tconfig := Config{}\n\tfile, err := os.Open(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Fatal(\"Config Not Found!\")\n\t} else {\n\t\terr = json.NewDecoder(file).Decode(&config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\treturn config\n}", "func readConfig(projectHome string) (map[string]string, error) {\n\tvars := make(map[string]string)\n\tsep := \"/\"\n\tif strings.HasSuffix(projectHome, \"/\") {\n\t\tsep = \"\"\n\t}\n\tfileName := projectHome + sep + \"config.yaml\"\n\tconfigFile, err := os.Open(fileName)\n\tif err != nil {\n\t\tprojectHome = \".\"\n\t\tlog.Printf(\"config.readConfig: setting projectHome to: '%s'\\n\",\n\t\t\tprojectHome)\n\t\tfileName = projectHome + \"/config.yaml\"\n\t\tconfigFile, err = os.Open(fileName)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"error opening config.yaml: %v\", err)\n\t\t\treturn map[string]string{}, err\n\t\t}\n\t}\n\tdefer configFile.Close()\n\treader := bufio.NewReader(configFile)\n\teof := false\n\tfor !eof {\n\t\tvar line string\n\t\tline, err = reader.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\terr = nil\n\t\t\teof = true\n\t\t} else if err != nil {\n\t\t\terr := fmt.Errorf(\"error reading config file: %v\", err)\n\t\t\treturn map[string]string{}, err\n\t\t}\n\t\t// Ignore comments\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.Index(line, \":\")\n\t\tif i > 0 {\n\t\t\tvarName := line[:i]\n\t\t\tval := strings.TrimSpace(line[i+1:])\n\t\t\tvars[varName] = val\n\t\t}\n\t}\n\treturn vars, nil\n}", "func (a *app) ReadConfig(configFile string) error {\n\ta.logger.Trace().Printf(\"[ReadConfig] opening '%s'\", configFile)\n\tf, err := os.Open(configFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't open configuration file: %v\", err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\terr = d.Decode(&a.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't decode configuration file: %v\", err)\n\t}\n\treturn nil\n}", "func ReadConfig() (*Config, error) {\n\tconfig := &Config{}\n\tconfig.MinIOProvider = &MinIOProvider{}\n\n\tfor _, cv := range configVars {\n\t\tvar value any\n\t\tvar parseErr error\n\t\tstrValue, err := readConfigVar(cv)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Parse the environment variable depending of its type\n\t\tswitch cv.varType {\n\t\tcase stringType:\n\t\t\tvalue = strings.TrimSpace(strValue)\n\t\tcase stringSliceType:\n\t\t\tvalue = parseStringSlice(strValue)\n\t\tcase intType:\n\t\t\tvalue, parseErr = strconv.Atoi(strValue)\n\t\tcase boolType:\n\t\t\tvalue, parseErr = strconv.ParseBool(strValue)\n\t\tcase secondsType:\n\t\t\tvalue, parseErr = parseSeconds(strValue)\n\t\tcase serverlessBackendType:\n\t\t\tvalue, parseErr = parseServerlessBackend(strValue)\n\t\tcase urlType:\n\t\t\t// Only check if can be parsed\n\t\t\t_, parseErr = url.Parse(strValue)\n\t\t\tvalue = strValue\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\t// If there are some parseErr return error\n\t\tif parseErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"the %s value is not valid. Expected type: %s. Error: %v\", cv.envVarName, cv.varType, parseErr)\n\t\t}\n\n\t\t// Set the value in the Config struct\n\t\tsetValue(value, cv.name, config)\n\n\t}\n\n\treturn config, nil\n}", "func TestConfigIsJSON(t *testing.T) {\n\thomedir := os.Getenv(\"HOME\")\n\tconfigpath := (homedir + \"/.stalker.json\")\n\tfile, _ := os.Open(configpath)\n\n\tdecoder := json.NewDecoder(file)\n\tconfiguration := Configuration{}\n\terr := decoder.Decode(&configuration)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t} else {\n\t\tt.Log(\"config is valid JSON\")\n\t}\n}", "func readFromENV() (err error) {\n\tlog.Println(\"Looking for ENV configuration\")\n\n\terr = envconfig.Process(\"PS\", &Config)\n\n\tif err == nil && Config.isMissing() {\n\t\terr = errors.New(\"Configuration is missing\")\n\t} else {\n\t\tlog.Println(\"ENV configuration has been read successfully\")\n\t}\n\n\treturn err\n}", "func (s *Service) readConfig() (*Config, error) {\n\tif _, err := os.Stat(s.Config); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\traw, err := ioutil.ReadFile(s.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &Config{}\n\terr = json.Unmarshal(raw, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}", "func getConf(configFile string) (configuration, error) {\n\tfile, _ := os.Open(configFile)\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tConf := configuration{}\n\terr := decoder.Decode(&Conf)\n\n\t// in case of err Conf will be empty struct\n\treturn Conf, err\n\n}", "func ReadConfig(ctx context.Context, git *Tool) (*Config, error) {\n\tp, err := git.Start(ctx, \"config\", \"-z\", \"--list\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", err)\n\t}\n\tcfg, parseErr := parseConfig(p)\n\twaitErr := p.Wait()\n\tif waitErr != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", waitErr)\n\t}\n\tif parseErr != nil {\n\t\treturn nil, fmt.Errorf(\"read git config: %v\", parseErr)\n\t}\n\treturn cfg, nil\n}", "func Read() *Config {\n\tvar cfg Config\n\tvar cfgPath string\n\n\tcfgPath = os.Getenv(\"TOKEN_SVC_CONF\")\n\n\tif len(cfgPath) <= 0 {\n\t\tlog.Println(\"TOKEN_SVC_CONF env variable not set\")\n\t\tlog.Println(\"using default config value...\")\n\t\tcfg = defConfig()\n\t} else {\n\t\t_, err := toml.DecodeFile(cfgPath, &cfg)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"unable to parse config: %v\", err.Error())\n\t\t}\n\t}\n\treturn &cfg\n}", "func getConfig(fpath string) {\n\traw, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to read config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(raw, &ctx.config)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to json-unmarshal config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n}", "func ReadExpansionConfigFile(ctx context.Context, filename string) (*ExpansionConfig, error) {\n\tbc, err := ioutils.ReadBytes(ctx, filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := &ExpansionConfig{}\n\tif err := json.Unmarshal(bc, config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, validateExpansionConfig(config)\n}", "func loadExitConfig(fname string) (cfg exitConfig, err error) {\n var data []byte\n data, err = ioutil.ReadFile(fname)\n if err == nil {\n err = json.Unmarshal(data, &cfg)\n }\n return\n}", "func (c *configInitializer) parseConfig(configFile string) {\n\tfd, err := os.Open(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fd.Close()\n\n\tcfgBytes, err := ioutil.ReadAll(fd)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal([]byte(cfgBytes), c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func ReadConfig(fileName string) (*Config, error) {\n\tvar config Config\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func readConfigFile(cfgFile string) (Config, error) {\n\n\tlog.Info(\"RabbitRelay: reading configuration from: \", cfgFile)\n\n\tconfig := Config{}\n\n\tvar err error\n\tfileContents, err := ioutil.ReadFile(cfgFile)\n\n\tif err != nil {\n\n\t\tlog.Critical(\"Error reading config file: \", err)\n\n\t} else {\n\n\t\t// This doesn't work, only the top level items are populated\n\t\t// err = jsonpointer.FindDecode(fileContents,\"\",&config)\n\t\terr = jsonpointer.FindDecode(fileContents, \"/masterRabbitServer\", &config.masterServer)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading master server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t\terr = jsonpointer.FindDecode(fileContents, \"/slaveRabbitServers\", &config.slaveServers)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading slave server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t}\n\treturn config, err\n}", "func initEnvironmentsFile() {\n\tabs, err := filepath.Abs(viper.GetString(\"environments-config\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tenvironmentsFile = environment.EnvironmentsFile{\n\t\tPath: abs,\n\t}\n\n\tif _, err = os.Stat(environmentsFile.Path); errors.Is(err, os.ErrNotExist) {\n\t\tenvironmentsFile.Environments = environment.Environments{}\n\t\treturn\n\t}\n\n\tif err = environmentsFile.Read(); err == nil {\n\t\treturn\n\t} else {\n\t\tlog.Fatal(\"Unable to read environments file\")\n\t}\n}", "func read(fileName string) (*Configuration, error) {\n\tif fileName == \"\" {\n\t\treturn Config, fmt.Errorf(\"Empty file name\")\n\t}\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn Config, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(Config)\n\tif err == nil {\n\t\tlog.Infof(\"Read config: %s\", fileName)\n\t} else {\n\t\tlog.Fatal(\"Cannot read config file:\", fileName, err)\n\t}\n\tif err := Config.postReadAdjustments(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn Config, err\n}", "func (c *Config) Read(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn errors.New(\"reading config \" + path + \", \" + err.Error())\n\t}\n\n\terr = json.Unmarshal(data, c)\n\tif err != nil {\n\t\treturn errors.New(\"parsing config \" + path + \", \" + err.Error())\n\t}\n\n\tabsolutePath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn errors.New(\"error in get absolute path\")\n\t}\n\n\tparentDir := filepath.Dir(absolutePath)\n\tc.DeploymentTemplatePath = parentDir + \"/\" + c.DeploymentTemplatePath\n\n\tdata, err = ioutil.ReadFile(c.DeploymentTemplatePath)\n\tif err != nil {\n\t\treturn errors.New(\"reading deployment template \" + c.DeploymentTemplatePath + \", \" + err.Error())\n\t}\n\tc.DeploymentTemplate = string(data)\n\t//TODO validate\n\tlogger.Infof(\"config listing\")\n\tlogger.Infof(\"deployment template path: %s\", c.DeploymentTemplatePath)\n\tlogger.Infof(\"wait for creating timeout: %d\", c.WaitForCreatingTimeout)\n\tlogger.Infof(\"pod lifetime %d\", c.PodLifetime)\n\tlogger.Infof(\"listen: %s\", c.Listen)\n\tlogger.Infof(\"namespace: %s\", c.Namespace)\n\treturn nil\n}", "func readConf() error {\n\tbuf := new(bytes.Buffer)\n\tif _, err := os.Stat(ConfigFile); os.IsNotExist(err) {\n\t\terr := ioutil.WriteFile(ConfigFile, []byte(ConfigFileTemplate), 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tbuf.Reset()\n\ttomlData, err := os.Open(ConfigFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(buf, tomlData)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttomlData.Close()\n\tif _, err := toml.Decode(buf.String(), &pubConf); err != nil {\n\t\treturn err\n\t}\n\tif err := json.Unmarshal([]byte(pubConf.Sample.Storage), &sampleJobs); err != nil {\n\t\treturn err\n\t}\n\tparseConf()\n\treturn nil\n}", "func ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error) {\n\tif len(searchPaths) == 0 {\n\t\tsearchPaths = DefaultDockerConfigJSONPaths()\n\t}\n\tfor _, configPath := range searchPaths {\n\t\tabsDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configJSONFileName))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"while trying to canonicalize %s: %v\", configPath, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"looking for %s at %s\", configJSONFileName, absDockerConfigFileLocation)\n\t\tcfg, err = ReadSpecificDockerConfigJSONFile(absDockerConfigFileLocation)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tklog.V(4).Infof(\"while trying to read %s: %v\", absDockerConfigFileLocation, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"found valid %s at %s\", configJSONFileName, absDockerConfigFileLocation)\n\t\treturn cfg, nil\n\t}\n\treturn nil, fmt.Errorf(\"couldn't find valid %s after checking in %v\", configJSONFileName, searchPaths)\n\n}", "func ReadConfigFile() {\n\tVarsConfig = Configuration{\n\t\tServer: ServerConfiguration{\n\t\t\tPort: os.Getenv(\"SERVER_PORT\"),\n\t\t},\n\t\tRedis: RedisConfiguration{\n\t\t\tHost: os.Getenv(\"REDIS_HOST\"),\n\t\t\tPoolSize: os.Getenv(\"REDIS_POOL_SIZE\"),\n\t\t},\n\t}\n\treturn\n}", "func GetConfigFromJSON(configFile string) Config {\n\tvar config Config\n\tcontents, _ := ioutil.ReadFile(configFile)\n\tjson.Unmarshal(contents, &config)\n\tcheckSiteConfig(config)\n\treturn config\n}", "func ReadConfigFile(path string, allowEnvironmentOverrides bool) (*model.Config, map[string]interface{}, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer f.Close()\n\treturn ReadConfig(f, allowEnvironmentOverrides)\n}", "func getConfigFile() (*os.File, error) {\n\treturn os.Open(env.WorkDir() + \"/configs/config.json\")\n}", "func readFromJSON(configFilePath string) error {\n\tlog.Printf(\"Looking for JSON config file (%s)\", configFilePath)\n\n\tcontents, err := ioutil.ReadFile(configFilePath)\n\tif err == nil {\n\t\treader := bytes.NewBuffer(contents)\n\t\terr = json.NewDecoder(reader).Decode(&Config)\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"Reading configuration from JSON (%s) failed: %s\\n\", configFilePath, err)\n\t} else {\n\t\tlog.Printf(\"Configuration has been read from JSON (%s) successfully\\n\", configFilePath)\n\t}\n\n\treturn err\n}", "func readConfig(filename string) (driver, connstring string, err error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tconf := struct {\n\t\tDBX struct {\n\t\t\tDriver string `yaml:\"Driver\"`\n\t\t\tConnstring string `yaml:\"Connstring\"`\n\t\t} `yaml:\"DBX\"`\n\t}{}\n\n\tif err := yaml.Unmarshal(b, &conf); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn os.ExpandEnv(conf.DBX.Driver), os.ExpandEnv(conf.DBX.Connstring), nil\n}", "func ReadDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error) {\n\tif err = json.Unmarshal(contents, &cfg); err != nil {\n\t\treturn nil, errors.New(\"error occurred while trying to unmarshal json\")\n\t}\n\treturn\n}", "func ReadConfig() (c ConfigFile, err error) {\n\tconfig, err := GetConfigPath()\n\tif err != nil {\n\t\treturn\n\t}\n\tconfigBytes, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(configBytes, &c)\n\treturn\n}", "func readTendermintConfig(tmcfg *config.Config, dataDir string) error {\n\tv := viper.New()\n\tv.SetEnvPrefix(\"TM\")\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\", \"-\", \"_\"))\n\tv.AutomaticEnv()\n\tv.SetConfigName(\"config\")\n\tv.AddConfigPath(path.Join(dataDir, \"config\"))\n\tif err := v.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\terr := v.Unmarshal(tmcfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ReadJSONConfig(filename string) (*AppConfig, error) {\n\tf, err := os.Open(filename)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tfileBytes, err := ioutil.ReadAll(f)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tvar config AppConfig\n\tconfig.Debug = true\n\tif err = json.Unmarshal(fileBytes, &config); nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func ParseConfig(path string) Config {\n file, err := os.Open(path)\n if err != nil {\n log.Panicf(\"Can't load config: %s\", err.Error())\n }\n decoder := json.NewDecoder(file)\n var config Config\n err = decoder.Decode(&config)\n if err != nil {\n log.Panicf(\"Can't parse config file: %s. Error: %s\", path, err.Error())\n }\n return config\n}", "func init() {\n\tWorkEnv = os.Getenv(\"WorkEnv\")\n\tjsonFile, err := os.Open(\"./config/config.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar environments Environments\n\tjson.Unmarshal(byteValue, &environments)\n\tvar checkWorkEnv = 0\n\tfor i := 0; i < len(environments.Environments); i++ {\n\t\tif WorkEnv == environments.Environments[i].Env || (WorkEnv == \"\" && environments.Environments[i].Env == \"dev\") {\n\t\t\tAddress = environments.Environments[i].Database.Address\n\t\t\tDbName = environments.Environments[i].Database.DBName\n\t\t\tDbUsername = environments.Environments[i].Database.DBUsername\n\t\t\tDbPassword = environments.Environments[i].Database.DBPassword\n\t\t\tPort = environments.Environments[i].API.Port\n\t\t\tcheckWorkEnv = 1\n\t\t}\n\t}\n\tif checkWorkEnv == 0 {\n\t}\n}", "func GetConfig(fname string) (config Config, err error) {\n\tconfig = Config{}\n\n\tdata, err := simplejson.Load(fname)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconfig.Id = data.Get(\"id\").MustString(\"\")\n\tconfig.Name = data.Get(\"name\").MustString(\"\")\n\tconfig.Role = data.Get(\"role\").MustString(\"\")\n\tconfig.PassWord = data.Get(\"password\").MustString(\"\")\n\tconfig.ServerKey = data.Get(\"server_key\").MustString(\"\")\n\tconfig.ServerUrl = data.Get(\"server_url\").MustString(\"\")\n\tconfig.DaemonUser = data.Get(\"daemon_user\").MustString(\"\")\n\tconfig.PidFile = data.Get(\"pid_file\").MustString(\"\")\n\tconfig.LogFile = data.Get(\"log_file\").MustString(\"\")\n\tconfig.BaseDir = data.Get(\"base_dir\").MustString(\"\")\n\tconfig.DataDir = data.Get(\"data_dir\").MustString(\"\")\n\tconfig.HttpListen = data.Get(\"http_listen\").MustString(\"\")\n\tconfig.File = fname\n\n\tif config.Id == \"\" {\n\t\treturn config, errors.New(\"missing id config\")\n\t}\n\n\tif config.Role == \"\" {\n\t\treturn config, errors.New(\"missing role config\")\n\t}\n\n\tif config.ServerKey == \"\" {\n\t\treturn config, errors.New(\"missing server_key config\")\n\t}\n\n\tif config.PidFile == \"\" {\n\t\treturn config, errors.New(\"missing pid_file config\")\n\t}\n\n\tif config.LogFile == \"\" {\n\t\treturn config, errors.New(\"missing log_file config\")\n\t}\n\n\tif config.BaseDir == \"\" {\n\t\treturn config, errors.New(\"missing base_dir config\")\n\t}\n\n\tif config.Role == \"server\" {\n\t\tif config.PassWord == \"\" {\n\t\t\treturn config, errors.New(\"missing password config\")\n\t\t}\n\t\tif config.DataDir == \"\" {\n\t\t\treturn config, errors.New(\"missing data_dir config\")\n\t\t}\n\t\tif config.HttpListen == \"\" {\n\t\t\treturn config, errors.New(\"missing http_listen config\")\n\t\t}\n\t} else {\n\t\tif config.ServerUrl == \"\" {\n\t\t\treturn config, errors.New(\"missing server_url config\")\n\t\t}\n\t}\n\n\tif !strings.HasSuffix(config.BaseDir, \"/\") {\n\t\tconfig.BaseDir += \"/\"\n\t}\n\n\tif strings.HasSuffix(config.ServerUrl, \"/\") {\n\t\tconfig.ServerUrl = config.ServerUrl[:len(config.ServerUrl)-1]\n\t}\n\n\terr = SaveConfig(config)\n\n\treturn\n}", "func ReadJsonConfig(fileRead []byte, o *interface{}) error {\n\terr := json.Unmarshal(fileRead, o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func loadConfig(file string) error {\n\tf, err := os.Open(file) // Open file\n\n\t// Error checking, returns error\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close() // Defer file closing to end of function\n\n\tdecoder := json.NewDecoder(f) // Create json decoder\n\terr = decoder.Decode(&cfg) // Decode the json into the config struct\n\n\t// Error checking\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ConfigReader(filePath string) (Config, error) {\n\tvar c Config\n\n\tfile, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\terr = toml.Unmarshal(file, &c)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\treturn c, nil\n}", "func ReadConfig(file string) (*Setting, error) {\n\tconfigFile, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer configFile.Close()\n\tvar setting Setting\n\tif err := json.NewDecoder(configFile).Decode(&setting); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &setting, err\n}" ]
[ "0.6759943", "0.6669569", "0.65060747", "0.64998543", "0.64024603", "0.6366553", "0.6363055", "0.6342831", "0.6338858", "0.626114", "0.62590086", "0.6227118", "0.6226288", "0.61894345", "0.6188248", "0.61833155", "0.6154567", "0.6153561", "0.6141254", "0.61349624", "0.6111502", "0.61095613", "0.6103885", "0.6093317", "0.60850185", "0.6056128", "0.602044", "0.60074174", "0.6005855", "0.5996346", "0.5989658", "0.59685314", "0.5959984", "0.5953059", "0.5929872", "0.592334", "0.5920543", "0.59181356", "0.5916529", "0.5908717", "0.5902251", "0.5889597", "0.5886968", "0.58860564", "0.5885885", "0.588195", "0.5880718", "0.5880017", "0.5873634", "0.58717686", "0.58629155", "0.58571416", "0.58559406", "0.58492786", "0.58222115", "0.58181536", "0.5812368", "0.5810906", "0.5807718", "0.57834977", "0.57807404", "0.5776386", "0.5774981", "0.57649344", "0.5763698", "0.5760356", "0.5747607", "0.5746487", "0.57283396", "0.5726864", "0.57221204", "0.57174057", "0.5716382", "0.5708241", "0.5695045", "0.5694312", "0.5691291", "0.5677008", "0.56747556", "0.56736094", "0.56661445", "0.56624955", "0.566247", "0.56609315", "0.5655688", "0.5654767", "0.5654118", "0.564884", "0.5646695", "0.5640979", "0.5636627", "0.56322515", "0.5629025", "0.56099653", "0.5603446", "0.55930185", "0.55921656", "0.5590304", "0.55898607", "0.55883884" ]
0.8121165
0
EnvConfigFileGenerator will be invoked when the EnvConfigValidator returns an error or if EnvConfigFileReader returns no data The function generates a new env_config.json file and populates it with the default config data
func EnvConfigFileGenerator() error { execName, execErr := os.Executable() cwd := filepath.Dir(execName) if execErr != nil { localLogger(execErr.Error(), global.StatusError) return types.Error{Msg: execErr.Error()} } fileString := cwd + "/" + global.EnvFileName envContent, _ := json.MarshalIndent(&EnvConfig{ DataBaseFile: cwd + "/" + global.DatabaseFilePath, Port: global.DefaultPort, }, "", " ") return ioutil.WriteFile(fileString, envContent, 0755) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Parser) GenerateEnvConfig() []byte {\n\tvar result bytes.Buffer\n\tfor _, rule := range p.rules {\n\t\tif rule.EnvVar == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tresult.Write(rule.GenerateEnvUsage(p.cfg.WordWrap))\n\t}\n\treturn result.Bytes()\n}", "func EnvConfigFileReader() *EnvConfig {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn nil\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\tenvFile, err := os.Open(fileString)\n\n\tvar envConfig *EnvConfig\n\n\tif err != nil {\n\t\tlocalLogger(err.Error(), global.StatusError)\n\t\treturn nil\n\t} else {\n\t\tif fileContent, openErr := ioutil.ReadAll(envFile); openErr == nil {\n\t\t\tunMarshallErr := json.Unmarshal(fileContent, &envConfig)\n\t\t\tif unMarshallErr == nil {\n\t\t\t\treturn envConfig\n\t\t\t} else {\n\t\t\t\tlocalLogger(unMarshallErr.Error(), global.StatusError)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func initializeConfigFile() Configuration {\n\t// check if ~/.kube/kubectl exists if not create it\n\t// log.Print(\"[DEBUG] checking ~/.kube/kubectl\")\n\thome, err := CreateKubectlHome()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// if env var does not exists try to read from ~/.kube/kubectl/config\n\tconfig := fmt.Sprintf(\"%v/config\", home)\n\tif _, err := os.Stat(config); os.IsNotExist(err) {\n\t\t_, err := os.Create(config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tseed, seedErr := json.MarshalIndent(SeedData(), \"\", \" \")\n\t\tif seedErr != nil {\n\t\t\tpanic(seedErr)\n\t\t}\n\t\tlog.Print(\"[DEBUG] writing file ~/.kube/kubectl/config\")\n\t\tnoWriteErr := ioutil.WriteFile(config, seed, 0666)\n\t\tif noWriteErr != nil {\n\t\t\tpanic(noWriteErr)\n\t\t}\n\t}\n\t// log.Print(\"[DEBUG] File ~/.kube/kubectl/config exists now reading it....\")\n\t// config file is already exists at this point (created above or already exists) read it now\n\tconfigFile, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get configFile:: %v\", configFile)\n\t\tpanic(err)\n\t}\n\tdata := Configuration{}\n\tjsonErr := json.Unmarshal([]byte(configFile), &data)\n\tif jsonErr != nil {\n\t\tpanic(jsonErr)\n\t}\n\treturn data\n}", "func initEnvironmentsFile() {\n\tabs, err := filepath.Abs(viper.GetString(\"environments-config\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tenvironmentsFile = environment.EnvironmentsFile{\n\t\tPath: abs,\n\t}\n\n\tif _, err = os.Stat(environmentsFile.Path); errors.Is(err, os.ErrNotExist) {\n\t\tenvironmentsFile.Environments = environment.Environments{}\n\t\treturn\n\t}\n\n\tif err = environmentsFile.Read(); err == nil {\n\t\treturn\n\t} else {\n\t\tlog.Fatal(\"Unable to read environments file\")\n\t}\n}", "func EnvConfigValidator() error {\n\texecName, execErr := os.Executable()\n\tcwd := filepath.Dir(execName)\n\n\tif execErr != nil {\n\t\tlocalLogger(execErr.Error(), global.StatusError)\n\t\treturn execErr\n\t}\n\n\tfileString := cwd + \"/\" + global.EnvFileName\n\t_, openErr := os.Open(fileString)\n\n\tif openErr != nil {\n\t\tlocalLogger(openErr.Error(), global.StatusError)\n\t\treturn openErr\n\t} else {\n\t\tif envContent := EnvConfigFileReader(); envContent == nil {\n\t\t\tlocalLogger(\"Unable to read env file\", global.StatusError)\n\t\t\treturn types.Error{Msg: \"Invalid content in env_config file\"}\n\t\t}\n\t}\n\treturn nil\n}", "func (env *Env) GenerateJSONConfig(rw http.ResponseWriter, req *http.Request) {\n\thostname := mux.Vars(req)[\"hostname\"]\n\t// TODO: Verify that the sessionID matches the host.CurrentSessionIDs.Stage2ID.\n\t// sessionID := mux.Vars(req)[\"sessionID\"]\n\n\t// Use hostname as key to load record from Datastore.\n\thost, err := env.Config.Load(hostname)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\terr = env.requestIsFromHost(req, host)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusForbidden)\n\t\treturn\n\t}\n\n\t// TODO(soltesz):\n\t// * Save information sent in PostForm, e.g. ssh host key.\n\tstage := path.Base(req.URL.Path)\n\n\tscript := template.FormatJSONConfig(host, stage)\n\n\t// Complete request as successful.\n\trw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\trw.WriteHeader(http.StatusOK)\n\t_, err = fmt.Fprintf(rw, script)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to write response to %q: %v\", hostname, err)\n\t}\n\treturn\n}", "func init() {\n\tWorkEnv = os.Getenv(\"WorkEnv\")\n\tjsonFile, err := os.Open(\"./config/config.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t// defer the closing of our jsonFile so that we can parse it later on\n\tdefer jsonFile.Close()\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar environments Environments\n\tjson.Unmarshal(byteValue, &environments)\n\tvar checkWorkEnv = 0\n\tfor i := 0; i < len(environments.Environments); i++ {\n\t\tif WorkEnv == environments.Environments[i].Env || (WorkEnv == \"\" && environments.Environments[i].Env == \"dev\") {\n\t\t\tAddress = environments.Environments[i].Database.Address\n\t\t\tDbName = environments.Environments[i].Database.DBName\n\t\t\tDbUsername = environments.Environments[i].Database.DBUsername\n\t\t\tDbPassword = environments.Environments[i].Database.DBPassword\n\t\t\tPort = environments.Environments[i].API.Port\n\t\t\tcheckWorkEnv = 1\n\t\t}\n\t}\n\tif checkWorkEnv == 0 {\n\t}\n}", "func generateConfigFile(context *clusterd.Context, clusterInfo *ClusterInfo, pathRoot, keyringPath string, globalConfig *CephConfig, clientSettings map[string]string) (string, error) {\n\n\t// create the config directory\n\tif err := os.MkdirAll(pathRoot, 0744); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create config directory at %q\", pathRoot)\n\t}\n\n\tconfigFile, err := createGlobalConfigFileSection(context, clusterInfo, globalConfig)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to create global config section\")\n\t}\n\n\tif err := mergeDefaultConfigWithRookConfigOverride(context, clusterInfo, configFile); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to merge global config with %q\", k8sutil.ConfigOverrideName)\n\t}\n\n\tqualifiedUser := getQualifiedUser(clusterInfo.CephCred.Username)\n\tif err := addClientConfigFileSection(configFile, qualifiedUser, keyringPath, clientSettings); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to add admin client config section\")\n\t}\n\n\t// write the entire config to disk\n\tfilePath := getConfFilePath(pathRoot, clusterInfo.Namespace)\n\tlogger.Infof(\"writing config file %s\", filePath)\n\tif err := configFile.SaveTo(filePath); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to save config file %s\", filePath)\n\t}\n\n\treturn filePath, nil\n}", "func GenerateConfigFile(tfeToken string, tfeHostname string, home string) error {\n\tconfig := fmt.Sprintf(rcFileContents, tfeHostname, tfeToken)\n\trcFile := filepath.Join(home, rcFilename)\n\n\t// If there is already a .terraformrc file and its contents aren't exactly\n\t// what we would have written to it, then we error out because we don't\n\t// want to overwrite anything.\n\tif _, err := os.Stat(rcFile); err == nil {\n\t\tcurrContents, err := os.ReadFile(rcFile) // nolint: gosec\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"trying to read %s to ensure we're not overwriting it\", rcFile)\n\t\t}\n\t\tif config != string(currContents) {\n\t\t\treturn fmt.Errorf(\"can't write TFE token to %s because that file has contents that would be overwritten\", rcFile)\n\t\t}\n\t\t// Otherwise we don't need to write the file because it already has\n\t\t// what we need.\n\t\treturn nil\n\t}\n\n\tif err := os.WriteFile(rcFile, []byte(config), 0600); err != nil {\n\t\treturn errors.Wrapf(err, \"writing generated %s file with TFE token to %s\", rcFilename, rcFile)\n\t}\n\treturn nil\n}", "func loadEnvironmentConfig(env string) types.Options {\n\tconfigFile := \"config/\" + ServiceName + \"/\" + env + \".json\"\n\tif _, err := os.Stat(configFile); os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\treturn parseConfigFile(configFile)\n}", "func TestGenerateConfigGoResource(t *testing.T) {\n\tconst (\n\t\toutFileName = \"configtemplate.go\"\n\t\tsourceFileName = \"testdata/config.yaml\"\n\t)\n\n\tif _, err := os.Stat(outFileName); !os.IsNotExist(err) {\n\t\tif b, _ := strconv.ParseBool(os.Getenv(\"GENERATE_CONFIG_TEMPLATE\")); !b {\n\t\t\tt.Skip(\"GENERATE_CONFIG_TEMPLATE is not set. Skipping template generation.\")\n\t\t\treturn\n\t\t}\n\t}\n\n\toutFile, err := os.Create(outFileName)\n\tassert.NoError(t, err)\n\n\tinFileData, err := ioutil.ReadFile(sourceFileName)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"package main\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"// Generated content\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"var templateConfigData = []byte(`\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write(inFileData)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"`)\\n\"))\n\tassert.NoError(t, err)\n}", "func Ensure(fname string) (cfg *Config, err error) {\n\t_, err = os.Stat(fname)\n\tif os.IsNotExist(err) {\n\t\terr = nil\n\t\tvar d []byte\n\t\td, err = json.Marshal(&DefaultConfig)\n\t\tif err == nil {\n\t\t\tb := new(bytes.Buffer)\n\t\t\terr = json.Indent(b, d, \"\", \" \")\n\t\t\tif err == nil {\n\t\t\t\terr = ioutil.WriteFile(fname, b.Bytes(), 0600)\n\t\t\t}\n\t\t}\n\t}\n\tif err == nil {\n\t\tcfg, err = Load(fname)\n\t}\n\treturn\n}", "func InitEnv() error {\n\tfile, err := ioutil.ReadFile(envPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif errMarsh := codec.DecJson(file, &env); errMarsh != nil {\n\t\treturn fmt.Errorf(\"failed to parse %s. decode error: %v\", string(file), err)\n\t}\n\n\treturn nil\n}", "func createCredentialsConfig(t *testing.T) {\n\tif err := os.MkdirAll(\".chef\", os.ModePerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcreds := []byte(`[default]\nclient_name = \"foo\"\nclient_key = \".chef/foo.pem\"\nchef_server_url = \"chef-server.example.com/organizations/bubu\"\n\n[dev]\nclient_name = \"dev\"\nclient_key = \".chef/dev.pem\"\nchef_server_url = \"chef-server.example.com/organizations/dev\"\n\n[empty]\nclient_name = \"empty\"\nclient_key = \".chef/empty.pem\"\nchef_server_url = \"chef-server.example.com/organizations/empty\"\n`)\n\terr := ioutil.WriteFile(\".chef/credentials\", creds, 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = ioutil.WriteFile(\".chef/foo.pem\", key(), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = ioutil.WriteFile(\".chef/dev.pem\", key(), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = ioutil.WriteFile(\".chef/empty.pem\", []byte(\"\"), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func DefaultEnvConfig() (*Config, error) {\n\tif !env.OnGCE() {\n\t\treturn nil, nil\n\t}\n\tauth := \"none\"\n\tuser, _ := metadata.InstanceAttributeValue(\"camlistore-username\")\n\tpass, _ := metadata.InstanceAttributeValue(\"camlistore-password\")\n\tconfBucket, err := metadata.InstanceAttributeValue(\"camlistore-config-dir\")\n\tif confBucket == \"\" || err != nil {\n\t\treturn nil, fmt.Errorf(\"VM instance metadata key 'camlistore-config-dir' not set: %v\", err)\n\t}\n\tblobBucket, err := metadata.InstanceAttributeValue(\"camlistore-blob-dir\")\n\tif blobBucket == \"\" || err != nil {\n\t\treturn nil, fmt.Errorf(\"VM instance metadata key 'camlistore-blob-dir' not set: %v\", err)\n\t}\n\tif user != \"\" && pass != \"\" {\n\t\tauth = \"userpass:\" + user + \":\" + pass\n\t}\n\n\tif v := osutil.SecretRingFile(); !strings.HasPrefix(v, \"/gcs/\") {\n\t\treturn nil, fmt.Errorf(\"Internal error: secret ring path on GCE should be at /gcs/, not %q\", v)\n\t}\n\tkeyID, secRing, err := getOrMakeKeyring()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thighConf := &serverconfig.Config{\n\t\tAuth: auth,\n\t\tHTTPS: true,\n\t\tIdentity: keyID,\n\t\tIdentitySecretRing: secRing,\n\t\tGoogleCloudStorage: \":\" + strings.TrimPrefix(blobBucket, \"gs://\"),\n\t\tPackRelated: true,\n\t\tShareHandler: true,\n\t}\n\n\texternalIP, _ := metadata.ExternalIP()\n\thostName, _ := metadata.InstanceAttributeValue(\"camlistore-hostname\")\n\t// If they specified a hostname (probably with pk-deploy), then:\n\t// if it looks like an FQDN, perkeepd is going to rely on Let's\n\t// Encrypt, else perkeepd is going to generate some self-signed for that\n\t// hostname.\n\t// Also, if the hostname is in camlistore.net, we want Perkeep to initialize\n\t// exactly as if the instance had no hostname, so that it registers its hostname/IP\n\t// with the camlistore.net DNS server (possibly needlessly, if the instance IP has\n\t// not changed) again.\n\tif hostName != \"\" && !strings.HasSuffix(hostName, CamliNetDomain) {\n\t\thighConf.BaseURL = fmt.Sprintf(\"https://%s\", hostName)\n\t\thighConf.Listen = \"0.0.0.0:443\"\n\t} else {\n\t\thighConf.CamliNetIP = externalIP\n\t}\n\n\t// Detect a linked Docker MySQL container. It must have alias \"mysqldb\".\n\tmysqlPort := os.Getenv(\"MYSQLDB_PORT\")\n\tif !strings.HasPrefix(mysqlPort, \"tcp://\") {\n\t\t// No MySQL\n\t\t// TODO: also detect Cloud SQL.\n\t\thighConf.KVFile = \"/index.kv\"\n\t\treturn genLowLevelConfig(highConf)\n\t}\n\thostPort := strings.TrimPrefix(mysqlPort, \"tcp://\")\n\thighConf.MySQL = \"root@\" + hostPort + \":\" // no password\n\tconfigVersion, err := metadata.InstanceAttributeValue(\"perkeep-config-version\")\n\tif configVersion == \"\" || err != nil {\n\t\t// the launcher is deploying a pre-\"perkeep-config-version\" Perkeep, which means\n\t\t// we want the old configuration, with DBNames\n\t\thighConf.DBUnique = useDBNamesConfig\n\t} else if configVersion != \"1\" {\n\t\treturn nil, fmt.Errorf(\"unexpected value for VM instance metadata key 'perkeep-config-version': %q\", configVersion)\n\t}\n\n\tconf, err := genLowLevelConfig(highConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := conf.readFields(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func initConfig() {\n\tif viper.GetBool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t\tlog.Debugf(\"Debug logging enabled!\")\n\t} else {\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\tlog.Debugf(\"Cago Version: %s\", Version)\n\n\t// Enable overriding of configuration values using environment variables\n\tviper.SetEnvPrefix(\"CAGO\")\n\tviper.AutomaticEnv()\n\n\t// Check for the configuration file in the following order:\n\t// 1. Local configuration file specified using a command line argument\n\t// 2. Remote configuration file specified using the CAGO_CONFIG_URL environment variable\n\t// 3. Local configuration file cached from a previous download\n\t// 4. Local configuration file manually created by user\n\n\t// Step 1: Check to see if the configuration file path is set via command line argument\n\tconfigurationFilePath := viper.GetString(configFileFlagLong)\n\tif configurationFilePath != \"\" {\n\t\tlog.Debugf(\"Configuration file command line argument '%s' is set to: %s\", configFileFlagLong, configurationFilePath)\n\t} else {\n\t\tlog.Debugf(\"Configuration file command line argument '%s' is not set\", configFileFlagLong)\n\t}\n\n\t// Step 2 and 3: Download a remote file or used a previously cached version\n\tif configurationFilePath == \"\" {\n\t\tremoteConfigurationFileURL, ok := os.LookupEnv(\"CAGO_CONFIG_URL\")\n\t\tif ok {\n\t\t\tlog.Debugf(\"Environment variable '%s' is set to: %s\", remoteConfigFileEnvVariable, remoteConfigurationFileURL)\n\t\t\tconfigurationFilePath = getRemoteConfigurationFile(remoteConfigurationFileURL)\n\t\t} else {\n\t\t\tlog.Debugf(\"Environment variable '%s' is not set\", remoteConfigFileEnvVariable)\n\t\t}\n\t}\n\n\t// Step 4: Use a manually created local file\n\tif configurationFilePath == \"\" {\n\t\t// If the didn't load, try finding the remote configuration file\n\t\tconfigurationFilePath = getLocalConfigurationFile()\n\t}\n\n\tif configurationFilePath == \"\" {\n\t\tlog.Errorf(\"Cago could not find a configuration file to use! Here's what Cago checks:\")\n\t\tlog.Errorf(\" 1. Configuration file path specified using command line argument: %s\", configFileFlagLong)\n\t\tlog.Errorf(\" 2. Remote configuration file URL specified using environment variable: %s\", remoteConfigFileEnvVariable)\n\t\tlog.Errorf(\" 3. Previously cached remote configuration file in: %s\", cachedConfigFile)\n\t\tlog.Errorf(\" 4. Manually created configuration file here: %s\", localConfigFile)\n\n\t\tos.Exit(1)\n\t}\n\n\t// Read the configuration file\n\tviper.SetConfigFile(configurationFilePath)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.Fatalf(\"Could not process configuration file (%s), bailing out: %s\", configurationFilePath, err)\n\t\tos.Exit(1)\n\t}\n}", "func readConfig() (*config, error) {\n\tcfgPath := *configPath\n\tuserSpecified := *configPath != \"\"\n\n\tvar homeDir string\n\tif testHomeDir != \"\" {\n\t\thomeDir = testHomeDir\n\t} else {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thomeDir = u.HomeDir\n\t}\n\n\tif !userSpecified {\n\t\tcfgPath = filepath.Join(homeDir, \"src-config.json\")\n\t} else if strings.HasPrefix(cfgPath, \"~/\") {\n\t\tcfgPath = filepath.Join(homeDir, cfgPath[2:])\n\t}\n\tdata, err := os.ReadFile(os.ExpandEnv(cfgPath))\n\tif err != nil && (!os.IsNotExist(err) || userSpecified) {\n\t\treturn nil, err\n\t}\n\tvar cfg config\n\tif err == nil {\n\t\tcfg.ConfigFilePath = cfgPath\n\t\tif err := json.Unmarshal(data, &cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tenvToken := os.Getenv(\"SRC_ACCESS_TOKEN\")\n\tenvEndpoint := os.Getenv(\"SRC_ENDPOINT\")\n\n\tif userSpecified {\n\t\t// If a config file is present, either zero or both environment variables must be present.\n\t\t// We don't want to partially apply environment variables.\n\t\tif envToken == \"\" && envEndpoint != \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t\tif envToken != \"\" && envEndpoint == \"\" {\n\t\t\treturn nil, errConfigMerge\n\t\t}\n\t}\n\n\t// Apply config overrides.\n\tif envToken != \"\" {\n\t\tcfg.AccessToken = envToken\n\t}\n\tif envEndpoint != \"\" {\n\t\tcfg.Endpoint = envEndpoint\n\t}\n\tif cfg.Endpoint == \"\" {\n\t\tcfg.Endpoint = \"https://sourcegraph.com\"\n\t}\n\n\tcfg.AdditionalHeaders = parseAdditionalHeaders()\n\t// Ensure that we're not clashing additonal headers\n\t_, hasAuthorizationAdditonalHeader := cfg.AdditionalHeaders[\"authorization\"]\n\tif cfg.AccessToken != \"\" && hasAuthorizationAdditonalHeader {\n\t\treturn nil, errConfigAuthorizationConflict\n\t}\n\n\t// Lastly, apply endpoint flag if set\n\tif endpoint != nil && *endpoint != \"\" {\n\t\tcfg.Endpoint = *endpoint\n\t}\n\n\tcfg.Endpoint = cleanEndpoint(cfg.Endpoint)\n\n\treturn &cfg, nil\n}", "func GenerateConfig(f string) error {\n\texists, err := pathExists(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\treturn errors.New(\"output config file already exists: \" + f)\n\t}\n\text := filepath.Ext(f)\n\n\tif len(ext) > 1 {\n\t\text = ext[1:]\n\t}\n\n\tsupportedExts := []string{\"json\", \"toml\", \"yaml\", \"yml\"}\n\n\tif !stringInSlice(ext, supportedExts) {\n\t\treturn errors.New(\"output config file must have one of supported extensions: \" + strings.Join(supportedExts, \", \"))\n\t}\n\n\tvar t *template.Template\n\n\tswitch ext {\n\tcase \"json\":\n\t\tt, err = template.New(\"config\").Parse(jsonConfigTemplate)\n\tcase \"toml\":\n\t\tt, err = template.New(\"config\").Parse(tomlConfigTemplate)\n\tcase \"yaml\", \"yml\":\n\t\tt, err = template.New(\"config\").Parse(yamlConfigTemplate)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar output bytes.Buffer\n\t_ = t.Execute(&output, struct {\n\t\tTokenSecret string\n\t\tAdminPassword string\n\t\tAdminSecret string\n\t\tAPIKey string\n\t}{\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t\tuuid.New().String(),\n\t})\n\n\treturn ioutil.WriteFile(f, output.Bytes(), 0644)\n}", "func (cfg *Config) FromEnv() error {\n\n\t//Init\n\tif cfg.VirtualCenter == nil {\n\t\tcfg.VirtualCenter = make(map[string]*VirtualCenterConfig)\n\t}\n\n\t//Globals\n\tif v := os.Getenv(\"VSPHERE_VCENTER\"); v != \"\" {\n\t\tcfg.Global.VCenterIP = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_VCENTER_PORT\"); v != \"\" {\n\t\tcfg.Global.VCenterPort = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_USER\"); v != \"\" {\n\t\tcfg.Global.User = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_PASSWORD\"); v != \"\" {\n\t\tcfg.Global.Password = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_DATACENTER\"); v != \"\" {\n\t\tcfg.Global.Datacenters = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAME\"); v != \"\" {\n\t\tcfg.Global.SecretName = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_SECRET_NAMESPACE\"); v != \"\" {\n\t\tcfg.Global.SecretNamespace = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_ROUNDTRIP_COUNT\"); v != \"\" {\n\t\ttmp, err := strconv.ParseUint(v, 10, 32)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_ROUNDTRIP_COUNT: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.RoundTripperCount = uint(tmp)\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_INSECURE\"); v != \"\" {\n\t\tInsecureFlag, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_INSECURE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.InsecureFlag = InsecureFlag\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_DISABLE\"); v != \"\" {\n\t\tAPIDisable, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse VSPHERE_API_DISABLE: %s\", err)\n\t\t} else {\n\t\t\tcfg.Global.APIDisable = APIDisable\n\t\t}\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_API_BINDING\"); v != \"\" {\n\t\tcfg.Global.APIBinding = v\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_SECRETS_DIRECTORY\"); v != \"\" {\n\t\tcfg.Global.SecretsDirectory = v\n\t}\n\tif cfg.Global.SecretsDirectory == \"\" {\n\t\tcfg.Global.SecretsDirectory = DefaultSecretDirectory\n\t}\n\tif _, err := os.Stat(cfg.Global.SecretsDirectory); os.IsNotExist(err) {\n\t\tcfg.Global.SecretsDirectory = \"\" //Dir does not exist, set to empty string\n\t}\n\n\tif v := os.Getenv(\"VSPHERE_CAFILE\"); v != \"\" {\n\t\tcfg.Global.CAFile = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_THUMBPRINT\"); v != \"\" {\n\t\tcfg.Global.Thumbprint = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_REGION\"); v != \"\" {\n\t\tcfg.Labels.Region = v\n\t}\n\tif v := os.Getenv(\"VSPHERE_LABEL_ZONE\"); v != \"\" {\n\t\tcfg.Labels.Zone = v\n\t}\n\n\t//Build VirtualCenter from ENVs\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\n\t\tif len(pair) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := pair[0]\n\t\tvalue := pair[1]\n\n\t\tif strings.HasPrefix(key, \"VSPHERE_VCENTER_\") && len(value) > 0 {\n\t\t\tid := strings.TrimPrefix(key, \"VSPHERE_VCENTER_\")\n\t\t\tvcenter := value\n\n\t\t\t_, username, errUsername := getEnvKeyValue(\"VCENTER_\"+id+\"_USERNAME\", false)\n\t\t\tif errUsername != nil {\n\t\t\t\tusername = cfg.Global.User\n\t\t\t}\n\t\t\t_, password, errPassword := getEnvKeyValue(\"VCENTER_\"+id+\"_PASSWORD\", false)\n\t\t\tif errPassword != nil {\n\t\t\t\tpassword = cfg.Global.Password\n\t\t\t}\n\t\t\t_, server, errServer := getEnvKeyValue(\"VCENTER_\"+id+\"_SERVER\", false)\n\t\t\tif errServer != nil {\n\t\t\t\tserver = \"\"\n\t\t\t}\n\t\t\t_, port, errPort := getEnvKeyValue(\"VCENTER_\"+id+\"_PORT\", false)\n\t\t\tif errPort != nil {\n\t\t\t\tport = cfg.Global.VCenterPort\n\t\t\t}\n\t\t\tinsecureFlag := false\n\t\t\t_, insecureTmp, errInsecure := getEnvKeyValue(\"VCENTER_\"+id+\"_INSECURE\", false)\n\t\t\tif errInsecure != nil {\n\t\t\t\tinsecureFlagTmp, errTmp := strconv.ParseBool(insecureTmp)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\tinsecureFlag = insecureFlagTmp\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, datacenters, errDatacenters := getEnvKeyValue(\"VCENTER_\"+id+\"_DATACENTERS\", false)\n\t\t\tif errDatacenters != nil {\n\t\t\t\tdatacenters = cfg.Global.Datacenters\n\t\t\t}\n\t\t\troundtrip := DefaultRoundTripperCount\n\t\t\t_, roundtripTmp, errRoundtrip := getEnvKeyValue(\"VCENTER_\"+id+\"_ROUNDTRIP\", false)\n\t\t\tif errRoundtrip != nil {\n\t\t\t\troundtripFlagTmp, errTmp := strconv.ParseUint(roundtripTmp, 10, 32)\n\t\t\t\tif errTmp == nil {\n\t\t\t\t\troundtrip = uint(roundtripFlagTmp)\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, caFile, errCaFile := getEnvKeyValue(\"VCENTER_\"+id+\"_CAFILE\", false)\n\t\t\tif errCaFile != nil {\n\t\t\t\tcaFile = cfg.Global.CAFile\n\t\t\t}\n\t\t\t_, thumbprint, errThumbprint := getEnvKeyValue(\"VCENTER_\"+id+\"_THUMBPRINT\", false)\n\t\t\tif errThumbprint != nil {\n\t\t\t\tthumbprint = cfg.Global.Thumbprint\n\t\t\t}\n\n\t\t\t_, secretName, secretNameErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAME\", false)\n\t\t\t_, secretNamespace, secretNamespaceErr := getEnvKeyValue(\"VCENTER_\"+id+\"_SECRET_NAMESPACE\", false)\n\n\t\t\tif secretNameErr != nil || secretNamespaceErr != nil {\n\t\t\t\tsecretName = \"\"\n\t\t\t\tsecretNamespace = \"\"\n\t\t\t}\n\t\t\tsecretRef := DefaultCredentialManager\n\t\t\tif secretName != \"\" && secretNamespace != \"\" {\n\t\t\t\tsecretRef = vcenter\n\t\t\t}\n\n\t\t\tiPFamilyPriority := []string{DefaultIPFamily}\n\t\t\t_, ipFamily, errIPFamily := getEnvKeyValue(\"VCENTER_\"+id+\"_IP_FAMILY\", false)\n\t\t\tif errIPFamily != nil {\n\t\t\t\tiPFamilyPriority = []string{ipFamily}\n\t\t\t}\n\n\t\t\t// If server is explicitly set, that means the vcenter value above is the TenantRef\n\t\t\tvcenterIP := vcenter\n\t\t\ttenantRef := vcenter\n\t\t\tif server != \"\" {\n\t\t\t\tvcenterIP = server\n\t\t\t\ttenantRef = vcenter\n\t\t\t}\n\n\t\t\tvar vcc *VirtualCenterConfig\n\t\t\tif cfg.VirtualCenter[tenantRef] != nil {\n\t\t\t\tvcc = cfg.VirtualCenter[tenantRef]\n\t\t\t} else {\n\t\t\t\tvcc = &VirtualCenterConfig{}\n\t\t\t\tcfg.VirtualCenter[tenantRef] = vcc\n\t\t\t}\n\n\t\t\tvcc.User = username\n\t\t\tvcc.Password = password\n\t\t\tvcc.TenantRef = tenantRef\n\t\t\tvcc.VCenterIP = vcenterIP\n\t\t\tvcc.VCenterPort = port\n\t\t\tvcc.InsecureFlag = insecureFlag\n\t\t\tvcc.Datacenters = datacenters\n\t\t\tvcc.RoundTripperCount = roundtrip\n\t\t\tvcc.CAFile = caFile\n\t\t\tvcc.Thumbprint = thumbprint\n\t\t\tvcc.SecretRef = secretRef\n\t\t\tvcc.SecretName = secretName\n\t\t\tvcc.SecretNamespace = secretNamespace\n\t\t\tvcc.IPFamilyPriority = iPFamilyPriority\n\t\t}\n\t}\n\n\treturn nil\n}", "func envOverride(config *DefaultConfig) (*DefaultConfig, error) {\n\t// override UpdateTime\n\tupdateTime := os.Getenv(\"XIGNITE_FEEDER_UPDATE_TIME\")\n\tif updateTime != \"\" {\n\t\tt, err := time.Parse(ctLayout, updateTime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.UpdateTime = t\n\t}\n\n\t// override APIToken\n\tapiToken := os.Getenv(\"XIGNITE_FEEDER_API_TOKEN\")\n\tif apiToken != \"\" {\n\t\tconfig.APIToken = apiToken\n\t}\n\n\t// override NotQuoteSymbolList\n\tnotQuoteStockList := os.Getenv(\"XIGNITE_FEEDER_NOT_QUOTE_STOCK_LIST\")\n\tif notQuoteStockList != \"\" {\n\t\tconfig.NotQuoteStockList = strings.Split(notQuoteStockList, \",\")\n\t}\n\n\treturn config, nil\n}", "func setupEnvConfigViper(environmentFlag string) *viper.Viper {\n\tconfig := viper.New()\n\tconfig.SetConfigName(environmentFlag)\n\tconfig.AddConfigPath(\"./.argo/environments\")\n\tif err := config.ReadInConfig(); err != nil {\n\t\tcolor.Red(\"%s\",err)\n\t\tcolor.Red(\"Error locating or parsing %s env's helm value file (should be ./argo/environments/%s.yaml!\", environmentFlag)\n\t\tos.Exit(1)\n\t}\n\treturn config\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Search config in home directory with name \".json2env\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigName(\".json2env\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}", "func (ec *ExecutionContext) readConfig() error {\n\tvar op errors.Op = \"cli.ExecutionContext.readConfig\"\n\t// need to get existing viper because https://github.com/spf13/viper/issues/233\n\tv := ec.Viper\n\tv.SetEnvPrefix(util.ViperEnvPrefix)\n\tv.SetEnvKeyReplacer(util.ViperEnvReplacer)\n\tv.AutomaticEnv()\n\tv.SetConfigName(\"config\")\n\tv.SetDefault(\"version\", \"1\")\n\tv.SetDefault(\"endpoint\", \"http://localhost:8080\")\n\tv.SetDefault(\"admin_secret\", \"\")\n\tv.SetDefault(\"access_key\", \"\")\n\tv.SetDefault(\"api_paths.query\", \"v1/query\")\n\tv.SetDefault(\"api_paths.v2_query\", \"v2/query\")\n\tv.SetDefault(\"api_paths.v1_metadata\", \"v1/metadata\")\n\tv.SetDefault(\"api_paths.graphql\", \"v1/graphql\")\n\tv.SetDefault(\"api_paths.config\", \"v1alpha1/config\")\n\tv.SetDefault(\"api_paths.pg_dump\", \"v1alpha1/pg_dump\")\n\tv.SetDefault(\"api_paths.version\", \"v1/version\")\n\tv.SetDefault(\"metadata_directory\", DefaultMetadataDirectory)\n\tv.SetDefault(\"migrations_directory\", DefaultMigrationsDirectory)\n\tv.SetDefault(\"seeds_directory\", DefaultSeedsDirectory)\n\tv.SetDefault(\"actions.kind\", \"synchronous\")\n\tv.SetDefault(\"actions.handler_webhook_baseurl\", \"http://localhost:3000\")\n\tv.SetDefault(\"actions.codegen.framework\", \"\")\n\tv.SetDefault(\"actions.codegen.output_dir\", \"\")\n\tv.SetDefault(\"actions.codegen.uri\", \"\")\n\tv.AddConfigPath(ec.ExecutionDirectory)\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"cannot read config from file/env: %w\", err))\n\t}\n\tadminSecret := v.GetString(\"admin_secret\")\n\tif adminSecret == \"\" {\n\t\tadminSecret = v.GetString(\"access_key\")\n\t}\n\n\t// Admin secrets can be specified as a string value of format\n\t// [\"secret1\", \"secret2\"], similar to how the corresponding environment variable\n\t// HASURA_GRAPHQL_ADMIN_SECRETS is configured with the server\n\tadminSecretsList := v.GetString(\"admin_secrets\")\n\tadminSecrets := []string{}\n\tif len(adminSecretsList) > 0 {\n\t\tif err = json.Unmarshal([]byte(adminSecretsList), &adminSecrets); err != nil {\n\t\t\treturn errors.E(op, fmt.Errorf(\"parsing 'admin_secrets' from config.yaml / environment variable HASURA_GRAPHQL_ADMIN_SECRETS failed: expected value of format [\\\"secret1\\\", \\\"secret2\\\"]: %w\", err))\n\t\t}\n\t}\n\n\tec.Config = &Config{\n\t\tVersion: ConfigVersion(v.GetInt(\"version\")),\n\t\tDisableInteractive: v.GetBool(\"disable_interactive\"),\n\t\tServerConfig: ServerConfig{\n\t\t\tEndpoint: v.GetString(\"endpoint\"),\n\t\t\tAdminSecret: adminSecret,\n\t\t\tAdminSecrets: adminSecrets,\n\t\t\tAPIPaths: &ServerAPIPaths{\n\t\t\t\tV1Query: v.GetString(\"api_paths.query\"),\n\t\t\t\tV2Query: v.GetString(\"api_paths.v2_query\"),\n\t\t\t\tV1Metadata: v.GetString(\"api_paths.v1_metadata\"),\n\t\t\t\tGraphQL: v.GetString(\"api_paths.graphql\"),\n\t\t\t\tConfig: v.GetString(\"api_paths.config\"),\n\t\t\t\tPGDump: v.GetString(\"api_paths.pg_dump\"),\n\t\t\t\tVersion: v.GetString(\"api_paths.version\"),\n\t\t\t},\n\t\t\tInsecureSkipTLSVerify: v.GetBool(\"insecure_skip_tls_verify\"),\n\t\t\tCAPath: v.GetString(\"certificate_authority\"),\n\t\t},\n\t\tMetadataDirectory: v.GetString(\"metadata_directory\"),\n\t\tMetadataFile: v.GetString(\"metadata_file\"),\n\t\tMigrationsDirectory: v.GetString(\"migrations_directory\"),\n\t\tSeedsDirectory: v.GetString(\"seeds_directory\"),\n\t\tActionConfig: &types.ActionExecutionConfig{\n\t\t\tKind: v.GetString(\"actions.kind\"),\n\t\t\tHandlerWebhookBaseURL: v.GetString(\"actions.handler_webhook_baseurl\"),\n\t\t\tCodegen: &types.CodegenExecutionConfig{\n\t\t\t\tFramework: v.GetString(\"actions.codegen.framework\"),\n\t\t\t\tOutputDir: v.GetString(\"actions.codegen.output_dir\"),\n\t\t\t\tURI: v.GetString(\"actions.codegen.uri\"),\n\t\t\t},\n\t\t},\n\t}\n\tif !ec.Config.Version.IsValid() {\n\t\treturn errors.E(op, ErrInvalidConfigVersion)\n\t}\n\terr = ec.Config.ServerConfig.ParseEndpoint()\n\tif err != nil {\n\t\treturn errors.E(op, fmt.Errorf(\"unable to parse server endpoint: %w\", err))\n\t}\n\treturn nil\n}", "func initializeConfig() *TestConfig {\n\t_, filename, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\treturn &TestConfig{err: errors.New(\"failed to find filename\")}\n\t}\n\n\ttestDir := filepath.Join(path.Dir(filename), \"..\", \"..\", \"test\")\n\tconfigPath := filepath.Join(testDir, \"config\", \"env.test\")\n\tfixturePath := filepath.Join(testDir, \"fixtures\")\n\tapi, err := app.FromEnvFile(configPath)\n\n\treturn &TestConfig{\n\t\tAPIConfig: api,\n\t\tfixturePath: fixturePath,\n\t\tconfigPath: configPath,\n\t\terr: err,\n\t}\n}", "func (o *InitOptions) createFiles() error {\n\t// create the directory\n\terr := os.MkdirAll(filepath.Dir(o.EC.ExecutionDirectory), os.ModePerm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error creating setup directories\")\n\t}\n\t// set config object\n\tvar config *cli.Config\n\tif o.Version == cli.V1 {\n\t\tconfig = &cli.Config{\n\t\t\tServerConfig: cli.ServerConfig{\n\t\t\t\tEndpoint: \"http://localhost:8080\",\n\t\t\t},\n\t\t}\n\t} else {\n\t\tconfig = &cli.Config{\n\t\t\tVersion: o.Version,\n\t\t\tServerConfig: cli.ServerConfig{\n\t\t\t\tEndpoint: \"http://localhost:8080\",\n\t\t\t},\n\t\t\tMetadataDirectory: \"metadata\",\n\t\t\tActionConfig: &types.ActionExecutionConfig{\n\t\t\t\tKind: \"synchronous\",\n\t\t\t\tHandlerWebhookBaseURL: \"http://localhost:3000\",\n\t\t\t},\n\t\t}\n\t}\n\tif o.Endpoint != \"\" {\n\t\tif _, err := url.ParseRequestURI(o.Endpoint); err != nil {\n\t\t\treturn errors.Wrap(err, \"error validating endpoint URL\")\n\t\t}\n\t\tconfig.ServerConfig.Endpoint = o.Endpoint\n\t}\n\tif o.AdminSecret != \"\" {\n\t\tconfig.ServerConfig.AdminSecret = o.AdminSecret\n\t}\n\n\t// write the config file\n\to.EC.Config = config\n\to.EC.ConfigFile = filepath.Join(o.EC.ExecutionDirectory, \"config.yaml\")\n\terr = o.EC.WriteConfig(nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot write config file\")\n\t}\n\n\t// create migrations directory\n\to.EC.MigrationDir = filepath.Join(o.EC.ExecutionDirectory, cli.DefaultMigrationsDirectory)\n\terr = os.MkdirAll(o.EC.MigrationDir, os.ModePerm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot write migration directory\")\n\t}\n\n\tif config.Version == cli.V2 {\n\t\t// create metadata directory\n\t\to.EC.MetadataDir = filepath.Join(o.EC.ExecutionDirectory, cli.DefaultMetadataDirectory)\n\t\terr = os.MkdirAll(o.EC.MetadataDir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"cannot write migration directory\")\n\t\t}\n\n\t\t// create metadata files\n\t\tplugins := make(metadataTypes.MetadataPlugins, 0)\n\t\tplugins = append(plugins, metadataVersion.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, tables.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, functions.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, querycollections.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, allowlist.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, remoteschemas.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, actions.New(o.EC, o.EC.MetadataDir))\n\t\tplugins = append(plugins, crontriggers.New(o.EC, o.EC.MetadataDir))\n\t\tfor _, plg := range plugins {\n\t\t\terr := plg.CreateFiles()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"cannot create metadata files\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// create seeds directory\n\to.EC.SeedsDirectory = filepath.Join(o.EC.ExecutionDirectory, cli.DefaultSeedsDirectory)\n\terr = os.MkdirAll(o.EC.SeedsDirectory, os.ModePerm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot write seeds directory\")\n\t}\n\treturn nil\n}", "func (r *Reader) getProvidersFromEnv(filePath string) (\n\tproviders []provider.Provider, warnings []string, err error) {\n\ts := os.Getenv(\"CONFIG\")\n\tif s == \"\" {\n\t\treturn nil, nil, nil\n\t}\n\tr.logger.Info(\"reading JSON config from environment variable CONFIG\")\n\tr.logger.Debug(\"config read: \" + s)\n\n\tb := []byte(s)\n\n\tproviders, warnings, err = extractAllSettings(b)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"configuration given: %w\", err)\n\t}\n\n\tbuffer := bytes.NewBuffer(nil)\n\terr = json.Indent(buffer, b, \"\", \" \")\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\tconst mode = fs.FileMode(0600)\n\terr = r.writeFile(filePath, buffer.Bytes(), mode)\n\tif err != nil {\n\t\treturn providers, warnings, fmt.Errorf(\"%w: %w\", errWriteConfigToFile, err)\n\t}\n\n\treturn providers, warnings, nil\n}", "func (engine *ConfigGenerator) Generate(forwarding *logforward.ForwardingSpec) (string, error) {\n\tlogger.DebugObject(\"Generating fluent.conf using %s\", forwarding)\n\t//sanitize here\n\tvar sourceInputLabels []string\n\tvar sourceToPipelineLabels []string\n\tvar pipelineToOutputLabels []string\n\tvar outputLabels []string\n\tvar err error\n\n\tlogTypes, appNs := gatherLogSourceTypes(forwarding.Pipelines)\n\n\tif sourceInputLabels, err = engine.generateSource(logTypes, appNs); err != nil {\n\t\tlogger.Tracef(\"Error generating source blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif sourceToPipelineLabels, err = engine.generateSourceToPipelineLabels(mapSourceTypesToPipelineNames(forwarding.Pipelines)); err != nil {\n\t\tlogger.Tracef(\"Error generating source to pipeline blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tsort.Strings(sourceToPipelineLabels)\n\tif pipelineToOutputLabels, err = engine.generatePipelineToOutputLabels(forwarding.Pipelines); err != nil {\n\t\tlogger.Tracef(\"Error generating pipeline to output labels blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif outputLabels, err = engine.generateOutputLabelBlocks(forwarding.Outputs); err != nil {\n\t\tlogger.Tracef(\"Error generating to output label blocks: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdata := struct {\n\t\tIncludeLegacySecureForward bool\n\t\tIncludeLegacySyslog bool\n\t\tCollectInfraLogs bool\n\t\tCollectAppLogs bool\n\t\tCollectAuditLogs bool\n\t\tSourceInputLabels []string\n\t\tSourceToPipelineLabels []string\n\t\tPipelinesToOutputLabels []string\n\t\tOutputLabels []string\n\t}{\n\t\tengine.includeLegacyForwardConfig,\n\t\tengine.includeLegacySyslogConfig,\n\t\tlogTypes.Has(string(logforward.LogSourceTypeInfra)),\n\t\tlogTypes.Has(string(logforward.LogSourceTypeApp)),\n\t\tlogTypes.Has(string(logforward.LogSourceTypeAudit)),\n\t\tsourceInputLabels,\n\t\tsourceToPipelineLabels,\n\t\tpipelineToOutputLabels,\n\t\toutputLabels,\n\t}\n\tresult, err := engine.Execute(\"fluentConf\", data)\n\tif err != nil {\n\t\tlogger.Tracef(\"Error generating fluentConf\")\n\t\treturn \"\", fmt.Errorf(\"Error processing fluentConf template: %v\", err)\n\t}\n\tlogger.Tracef(\"Successfully generated fluent.conf: %v\", result)\n\treturn result, nil\n}", "func TestDefaultConfig(t *testing.T) {\n\tif os.Getenv(\"BE_CRASHER\") == \"1\" {\n\t\tconfig := config.FromFile(configFile)\n\t\tbootstrap.NewBootstrap(config)\n\t\treturn\n\t}\n\tcmd := exec.Command(os.Args[0], \"-test.run=TestDefaultConfig\")\n\tcmd.Env = append(os.Environ(), \"BE_CRASHER=1\")\n\terr := cmd.Run()\n\tif e, ok := err.(*exec.ExitError); ok && !e.Success() {\n\t\treturn\n\t}\n\tif err != nil {\n\t\tt.Fatalf(\"Couldnt run application with values in config.json, Test exited with status 1, expected 0. Error %s\", err)\n\t}\n}", "func init() {\n\tcurrentDir, _ = pathhelper.GetCurrentExecDir()\n\tconfigFile = path.Join(currentDir, \"config.json\")\n}", "func (cfg *Config) GenerateSampleConfig(dstDir string) error {\n\n\t// get a *Template\n\tat, err := prepareTemplate(\"/templates/config.json.gotmpl\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check the destination file-path and create if required\n\t_, err = os.Stat(dstDir)\n\tif err != nil {\n\t\tos.Mkdir(dstDir, 0755)\n\t}\n\n\tvar tfDir string\n\n\tfor i := 0; i < 2; i++ {\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\ttfDir = dstDir + \"/.dev.config.json\"\n\t\t\tcfg.Env = \"dev\"\n\t\tcase 1:\n\t\t\ttfDir = dstDir + \"/.prd.config.json\"\n\t\t\tcfg.Env = \"prod\"\n\t\tdefault:\n\n\t\t}\n\n\t\t// create the .xxx.config.json file\n\t\tf, err := os.Create(tfDir)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t// set permissions\n\t\terr = f.Chmod(0755)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t// execute the config.json.gotmpl template using new file .xxx.config.json as a target\n\t\terr = at.Execute(f, cfg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"generated:\", tfDir)\n\t}\n\treturn nil\n}", "func SetUpEnvironment(confPath string) error {\n\t// Use a config file\n\tif confPath != \"\" {\n\t\tSetConfigFilePath(confPath)\n\t}\n\n\t// Get config params from environment variables\n\tc, err := getSdkConfigFromEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Url == \"\" {\n\n\t\tconfPath = GetConfigFilePath()\n\t\ts, err := ioutil.ReadFile(confPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(s, &c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Retrieves sensible info from the keyring if one is present\n\t\tConfigFromKeyring(&c)\n\n\t\t// Refresh token if required\n\t\tif refreshed, err := RefreshIfRequired(&c); refreshed {\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"Could not refresh authentication token:\", err)\n\t\t\t}\n\t\t\t// Copy config as IdToken will be cleared\n\t\t\tstoreConfig := c\n\t\t\tConfigToKeyring(&storeConfig)\n\t\t\t// Save config to renew TokenExpireAt\n\t\t\tconfData, _ := json.Marshal(&storeConfig)\n\t\t\tioutil.WriteFile(confPath, confData, 0666)\n\t\t}\n\t}\n\n\t// Store the retrieved parameters in a public static singleton\n\tDefaultConfig = &c\n\n\treturn nil\n}", "func initConfig() {\n\n\tvar (\n\t\tconfigFile string\n\t\tconfigFileEnv string\n\t\tconfigFileEnvPresent bool\n\t\tconfigFileOrigin string\n\t)\n\n\t// If environment variable is set, load its value.\n\tconfigFileEnv, configFileEnvPresent = os.LookupEnv(\"MH_CONFIG\")\n\tif configFileEnvPresent {\n\t\tconfigFile = configFileEnv\n\t\tconfigFileOrigin = \"env\"\n\t}\n\tif configFileFlag != \"\" {\n\t\t// If flag isn't empty, load its value instead.\n\t\tconfigFile = configFileFlag\n\t\tconfigFileOrigin = \"flag\"\n\t}\n\tviper.SetConfigFile(configFile)\n\tviper.SetEnvPrefix(\"mh\") // will be uppercased automatically\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a configFile is found, read it in.\n\terr := viper.ReadInConfig()\n\tif viper.GetBool(\"json\") {\n\t\tlog.SetFormatter(&log.JSONFormatter{})\n\t}\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"configFile\": configFile,\n\t\t\t\"configFileEnv\": configFileEnv,\n\t\t\t\"configFileEnvPresent\": configFileEnvPresent,\n\t\t\t\"configFileFlag\": configFileFlag,\n\t\t\t\"configFileOrigin\": configFileOrigin,\n\t\t\t\"configFileUsed\": viper.ConfigFileUsed(),\n\t\t\t\"err\": err,\n\t\t}).Warnln(\"Failed to load mh config.\",\n\t\t\t\"Please consider exporting environment variable: MH_CONFIG.\")\n\t}\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func initConfig() {\n\t// Find home directory.\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treporter.Error(err)\n\t}\n\n\t// Config directory path\n\tconfigDirPath := filepath.Join(home, configDirName)\n\n\t// Tell viper to look for `.config.toml` in configuration folder\n\tviper.AddConfigPath(configDirPath)\n\tviper.SetConfigType(\"toml\")\n\tviper.SetConfigName(\".config\")\n\n\t// If a config file is found, read it in.\n\tnewConfigFileGenerated := false\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treporter.Warn(\"Cannot find configuration file, generating new one...\")\n\t\t\t// Generate new config file\n\t\t\tconfig.Generate(configDirPath)\n\t\t\tnewConfigFileGenerated = true\n\t\t}\n\t\tif _, ok := err.(viper.UnsupportedConfigError); ok {\n\t\t\treporter.Error(\"Unsupported config file type, expected toml\")\n\t\t}\n\t}\n\n\t// If new config file is generated, read config again\n\tif newConfigFileGenerated {\n\t\tif err := viper.ReadInConfig(); err != nil {\n\t\t\treporter.Error(err)\n\t\t}\n\t}\n}", "func genConfig() ([]byte, error) {\n\t// Using genflags.getConfig() instead of config.New() because\n\t// it will include any defaults we have on the command line such\n\t// as default plugin selection. We didn't want to wire this into\n\t// the `config` package, but it will be a default value the CLI\n\t// users expect.\n\tc := genflags.resolveConfig()\n\tb, err := json.Marshal(c)\n\treturn b, errors.Wrap(err, \"unable to marshal configuration\")\n}", "func (a *App) Generator(data makr.Data) (*makr.Generator, error) {\n\tg := makr.New()\n\tg.Add(makr.NewCommand(makr.GoGet(\"golang.org/x/tools/cmd/goimports\", \"-u\")))\n\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/golang/dep/cmd/dep\", \"-u\")))\n\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/motemen/gore\", \"-u\")))\n\n\tfiles, err := generators.Find(filepath.Join(generators.TemplatesPath, \"newapp\"))\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tfor _, f := range files {\n\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t}\n\trr, err := refresh.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tg.Add(rr)\n\n\tif data[\"ciProvider\"] == \"travis\" {\n\t\tg.Add(makr.NewFile(\".travis.yml\", nTravis))\n\t} else if data[\"ciProvider\"] == \"gitlab-ci\" {\n\t\tif _, ok := data[\"withPop\"]; ok {\n\t\t\tif data[\"dbType\"] == \"postgres\" {\n\t\t\t\tdata[\"testDbUrl\"] = \"postgres://postgres:postgres@postgres:5432/\" + data[\"name\"].(string) + \"_test?sslmode=disable\"\n\t\t\t} else if data[\"dbType\"] == \"mysql\" {\n\t\t\t\tdata[\"testDbUrl\"] = \"mysql://root:root@mysql:3306/\" + data[\"name\"].(string) + \"_test\"\n\t\t\t} else {\n\t\t\t\tdata[\"testDbUrl\"] = \"\"\n\t\t\t}\n\t\t\tg.Add(makr.NewFile(\".gitlab-ci.yml\", nGitlabCi))\n\t\t} else {\n\t\t\tg.Add(makr.NewFile(\".gitlab-ci.yml\", nGitlabCiNoPop))\n\t\t}\n\t}\n\n\tif !a.API {\n\t\tif a.SkipWebpack {\n\t\t\twg, err := standard.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, errors.WithStack(err)\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t} else if a.WithReact {\n\t\t\twg, err := react.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, err\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t} else {\n\t\t\twg, err := webpack.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, errors.WithStack(err)\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t}\n\t}\n\tif !a.SkipPop {\n\t\tg.Add(newSodaGenerator())\n\t}\n\tif a.API {\n\t\tg.Add(makr.Func{\n\t\t\tRunner: func(path string, data makr.Data) error {\n\t\t\t\treturn os.RemoveAll(filepath.Join(path, \"templates\"))\n\t\t\t},\n\t\t})\n\t\tg.Add(makr.Func{\n\t\t\tRunner: func(path string, data makr.Data) error {\n\t\t\t\treturn os.RemoveAll(filepath.Join(path, \"locales\"))\n\t\t\t},\n\t\t})\n\t}\n\tif a.Docker != \"none\" {\n\t\tdg, err := docker.New()\n\t\tif err != nil {\n\t\t\treturn g, errors.WithStack(err)\n\t\t}\n\t\tg.Add(dg)\n\t}\n\tg.Add(makr.NewCommand(a.goGet()))\n\n\tif _, err := exec.LookPath(\"git\"); err == nil {\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"init\")))\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"add\", \".\")))\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"commit\", \"-m\", \"Initial Commit\")))\n\t}\n\n\treturn g, nil\n}", "func getConfig(ctx context.Context, cfg *CmdConfig) <-chan *RegionEnv {\n\tenvStream := make(chan *RegionEnv)\n\tgo func() {\n\t\tdefer log.Debug(\"Closing getConfig channel\")\n\t\tdefer close(envStream)\n\n\t\tfor _, region := range strings.Fields(cfg.Regions) {\n\t\t\tserviceInstances := make(map[string][]*catalogv1beta1.ServiceInstance)\n\t\t\tserviceBindings := make(map[string][]*catalogv1beta1.ServiceBinding)\n\t\t\t// Create an environment for this region and populate it with information from the config files.\n\t\t\tenvironment := RegionEnv{\n\t\t\t\tRegion: region,\n\t\t\t\tCfg: cfg,\n\t\t\t\tContext: ctx,\n\t\t\t\tServiceInstances: serviceInstances,\n\t\t\t\tServiceBindings: serviceBindings,\n\t\t\t}\n\n\t\t\treader, readerError := getReader(cfg.ConfigType)\n\t\t\tif readerError != nil {\n\t\t\t\tbadEnv := RegionEnv{Errors: []error{readerError}}\n\t\t\t\tenvStream <- &badEnv\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// getEnv adds values for the deployment specific configmap and secret.\n\t\t\tenvironment.ClusterSettings = map[string]string{}\n\t\t\treader.getEnv(&environment)\n\t\t\treader.parse(&environment)\n\t\t\tenvironment.identifySecrets()\n\t\t\tlog.Infof(\"Created region specific configuration for %s.\", region)\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlog.Info(\"Received Done\")\n\t\t\t\treturn\n\t\t\tcase envStream <- &environment:\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn envStream\n}", "func (c *configData) init() {\n\tconst filename = \".workflow.yml\"\n\n\tc.Global = viper.New()\n\tc.Local = viper.New()\n\n\t// c.Local.SetConfigFile(\n\t// \tpath.Join(git.RootDir(), filename),\n\t// )\n\n\tc.Global.SetConfigFile(\n\t\tpath.Join(currentUser.HomeDir, filename),\n\t)\n\n\t// TODO: configs := []*viper.Viper{c.Local, c.Global}\n\tconfigs := []*viper.Viper{c.Global}\n\tfor _, v := range configs {\n\t\t_, _ = file.Touch(v.ConfigFileUsed())\n\t\tfailIfError(v.ReadInConfig())\n\t}\n\n\tfailIfError(c.validate())\n\tfailIfError(c.update())\n\tc.initJira()\n}", "func GenerateEnvoyConfig() *EnvoyConfig {\n\treturn &EnvoyConfig{\n\t\t&Node{\n\t\t\tCluster: \"example\",\n\t\t\tID: \"node-1\",\n\t\t},\n\t\t&DynamicResources{\n\t\t\tCDSConfig: &ConfigSource{\n\t\t\t\tPath: \"/tmp/cds.yaml\",\n\t\t\t},\n\t\t\tLDSConfig: &ConfigSource{\n\t\t\t\tPath: \"/tmp/lds.yaml\",\n\t\t\t},\n\t\t},\n\t\t&Admin{\n\t\t\tAccessLogPath: \"/dev/null\",\n\t\t\tAdress: &Adress{\n\t\t\t\tSocketAdress: &SocketAdress{\n\t\t\t\t\tAdress: \"0.0.0.0\",\n\t\t\t\t\tPortValue: 19000,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func GenerateConfig(w http.ResponseWriter, r *http.Request) {\n\terr, auth := basicAuth(r)\n\n\tif err != nil {\n\t\tutils.Log.Info().Err(err)\n\t\tutils.Log.Info().Msg(err.Error())\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tio.WriteString(w, \"Basic Auth: Invalid credentials\")\n\n\t}\n\n\ttoken, err := baseGenerateToken(*auth)\n\tif err == nil {\n\t\tutils.Log.Info().Msgf(\"Granting token for user %v\", auth.Username)\n\t} else {\n\t\tutils.Log.Error().Msgf(\"Granting token fail for user %v\", auth.Username)\n\t}\n\n\tif err != nil {\n\t\tutils.Log.Info().Err(err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tconfig := &types.KubeConfig{\n\t\tApiVersion: \"v1\",\n\t\tKind: \"Config\",\n\t\tClusters: []types.KubeConfigCluster{\n\t\t\t{\n\t\t\t\tName: \"kubernetes\",\n\t\t\t\tCluster: types.KubeConfigClusterData{\n\t\t\t\t\tServer: utils.Config.PublicApiServerURL,\n\t\t\t\t\tCertificateData: utils.Config.KubeCa,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCurrentContext: \"kubernetes\" + \"-\" + auth.Username,\n\t\tContexts: []types.KubeConfigContext{\n\t\t\t{\n\t\t\t\tName: \"kubernetes\" + \"-\" + auth.Username,\n\t\t\t\tContext: types.KubeConfigContextData{\n\t\t\t\t\tCluster: \"kubernetes\",\n\t\t\t\t\tUser: auth.Username,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tUsers: []types.KubeConfigUser{\n\t\t\t{\n\t\t\t\tUser: types.KubeConfigUserToken{Token: *token},\n\t\t\t\tName: auth.Username},\n\t\t},\n\t}\n\n\tyml, err := yaml.Marshal(config)\n\n\tutils.Log.Error().Err(err)\n\tw.WriteHeader(http.StatusCreated)\n\tw.Header().Set(\"Content-Type\", \"text/x-yaml; charset=utf-8\")\n\tw.Write(yml)\n\n}", "func PrepareConfig(cmd *cobra.Command, metadata *config.StepData, stepName string, options interface{}, openFile func(s string, t map[string]string) (io.ReadCloser, error)) error {\n\n\tlog.SetFormatter(GeneralConfig.LogFormat)\n\n\tinitStageName(true)\n\n\tfilters := metadata.GetParameterFilters()\n\n\t// add telemetry parameter \"collectTelemetryData\" to ALL, GENERAL and PARAMETER filters\n\tfilters.All = append(filters.All, \"collectTelemetryData\")\n\tfilters.General = append(filters.General, \"collectTelemetryData\")\n\tfilters.Parameters = append(filters.Parameters, \"collectTelemetryData\")\n\n\tenvParams := metadata.GetResourceParameters(GeneralConfig.EnvRootPath, \"commonPipelineEnvironment\")\n\treportingEnvParams := config.ReportingParameters.GetResourceParameters(GeneralConfig.EnvRootPath, \"commonPipelineEnvironment\")\n\tresourceParams := mergeResourceParameters(envParams, reportingEnvParams)\n\n\tflagValues := config.AvailableFlagValues(cmd, &filters)\n\n\tvar myConfig config.Config\n\tvar stepConfig config.StepConfig\n\n\t// add vault credentials so that configuration can be fetched from vault\n\tif GeneralConfig.VaultRoleID == \"\" {\n\t\tGeneralConfig.VaultRoleID = os.Getenv(\"PIPER_vaultAppRoleID\")\n\t}\n\tif GeneralConfig.VaultRoleSecretID == \"\" {\n\t\tGeneralConfig.VaultRoleSecretID = os.Getenv(\"PIPER_vaultAppRoleSecretID\")\n\t}\n\tif GeneralConfig.VaultToken == \"\" {\n\t\tGeneralConfig.VaultToken = os.Getenv(\"PIPER_vaultToken\")\n\t}\n\tmyConfig.SetVaultCredentials(GeneralConfig.VaultRoleID, GeneralConfig.VaultRoleSecretID, GeneralConfig.VaultToken)\n\n\tif len(GeneralConfig.StepConfigJSON) != 0 {\n\t\t// ignore config & defaults in favor of passed stepConfigJSON\n\t\tstepConfig = config.GetStepConfigWithJSON(flagValues, GeneralConfig.StepConfigJSON, filters)\n\t\tlog.Entry().Infof(\"Project config: passed via JSON\")\n\t\tlog.Entry().Infof(\"Project defaults: passed via JSON\")\n\t} else {\n\t\t// use config & defaults\n\t\tvar customConfig io.ReadCloser\n\t\tvar err error\n\t\t//accept that config file and defaults cannot be loaded since both are not mandatory here\n\t\t{\n\t\t\tprojectConfigFile := getProjectConfigFile(GeneralConfig.CustomConfig)\n\t\t\tif exists, err := piperutils.FileExists(projectConfigFile); exists {\n\t\t\t\tlog.Entry().Debugf(\"Project config: '%s'\", projectConfigFile)\n\t\t\t\tif customConfig, err = openFile(projectConfigFile, GeneralConfig.GitHubAccessTokens); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Cannot read '%s'\", projectConfigFile)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Entry().Infof(\"Project config: NONE ('%s' does not exist)\", projectConfigFile)\n\t\t\t\tcustomConfig = nil\n\t\t\t}\n\t\t}\n\t\tvar defaultConfig []io.ReadCloser\n\t\tif len(GeneralConfig.DefaultConfig) == 0 {\n\t\t\tlog.Entry().Info(\"Project defaults: NONE\")\n\t\t}\n\t\tfor _, projectDefaultFile := range GeneralConfig.DefaultConfig {\n\t\t\tfc, err := openFile(projectDefaultFile, GeneralConfig.GitHubAccessTokens)\n\t\t\t// only create error for non-default values\n\t\t\tif err != nil {\n\t\t\t\tif projectDefaultFile != \".pipeline/defaults.yaml\" {\n\t\t\t\t\tlog.Entry().Debugf(\"Project defaults: '%s'\", projectDefaultFile)\n\t\t\t\t\treturn errors.Wrapf(err, \"Cannot read '%s'\", projectDefaultFile)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Entry().Debugf(\"Project defaults: '%s'\", projectDefaultFile)\n\t\t\t\tdefaultConfig = append(defaultConfig, fc)\n\t\t\t}\n\t\t}\n\t\tstepConfig, err = myConfig.GetStepConfig(flagValues, GeneralConfig.ParametersJSON, customConfig, defaultConfig, GeneralConfig.IgnoreCustomDefaults, filters, *metadata, resourceParams, GeneralConfig.StageName, stepName)\n\t\tif verbose, ok := stepConfig.Config[\"verbose\"].(bool); ok && verbose {\n\t\t\tlog.SetVerbose(verbose)\n\t\t\tGeneralConfig.Verbose = verbose\n\t\t} else if !ok && stepConfig.Config[\"verbose\"] != nil {\n\t\t\tlog.Entry().Warnf(\"invalid value for parameter verbose: '%v'\", stepConfig.Config[\"verbose\"])\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"retrieving step configuration failed\")\n\t\t}\n\t}\n\n\tif fmt.Sprintf(\"%v\", stepConfig.Config[\"collectTelemetryData\"]) == \"false\" {\n\t\tGeneralConfig.NoTelemetry = true\n\t}\n\n\tstepConfig.Config = checkTypes(stepConfig.Config, options)\n\tconfJSON, _ := json.Marshal(stepConfig.Config)\n\t_ = json.Unmarshal(confJSON, &options)\n\n\tconfig.MarkFlagsWithValue(cmd, stepConfig)\n\n\tretrieveHookConfig(stepConfig.HookConfig, &GeneralConfig.HookConfig)\n\n\tif GeneralConfig.GCPJsonKeyFilePath == \"\" {\n\t\tGeneralConfig.GCPJsonKeyFilePath, _ = stepConfig.Config[\"gcpJsonKeyFilePath\"].(string)\n\t}\n\tif GeneralConfig.GCSFolderPath == \"\" {\n\t\tGeneralConfig.GCSFolderPath, _ = stepConfig.Config[\"gcsFolderPath\"].(string)\n\t}\n\tif GeneralConfig.GCSBucketId == \"\" {\n\t\tGeneralConfig.GCSBucketId, _ = stepConfig.Config[\"gcsBucketId\"].(string)\n\t}\n\tif GeneralConfig.GCSSubFolder == \"\" {\n\t\tGeneralConfig.GCSSubFolder, _ = stepConfig.Config[\"gcsSubFolder\"].(string)\n\t}\n\treturn nil\n}", "func InitConfigFactory(f string, force bool) {\n\n\tif !force && APIConfig != nil {\n\t\treturn\n\t}\n\n\tcontent, err := ioutil.ReadFile(f)\n\tcheckErr(err)\n\n\tAPIConfig = &Config{}\n\n\terr = yaml.Unmarshal([]byte(content), &APIConfig)\n\tcheckErr(err)\n\tlogger.GNBLog.Infof(\"Successfully load gNB API module configuration %s\", f)\n}", "func Environ() (Config, error) {\n\tcfg := Config{}\n\terr := envconfig.Process(\"\", &cfg)\n\tdefaultAddress(&cfg)\n\tdefaultProxy(&cfg)\n\tdefaultRunner(&cfg)\n\tdefaultSession(&cfg)\n\tdefaultCallback(&cfg)\n\tconfigureGithub(&cfg)\n\tif err := kubernetesServiceConflict(&cfg); err != nil {\n\t\treturn cfg, err\n\t}\n\treturn cfg, err\n}", "func GenerateDotEnvFile(variables map[string]string) io.Reader {\n\tvar s string\n\n\tfor name, value := range variables {\n\t\ts += fmt.Sprintf(\"%s=%s\\n\", name, value)\n\t}\n\n\treturn strings.NewReader(s)\n}", "func (cfg *Conf) overrideEnvConf() {\n\tif os.Getenv(\"SMGMG_BK_API_KEY\") != \"\" {\n\t\tcfg.ApiKey = os.Getenv(\"SMGMG_BK_API_KEY\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_API_SECRET\") != \"\" {\n\t\tcfg.ApiSecret = os.Getenv(\"SMGMG_BK_API_SECRET\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_USER_TOKEN\") != \"\" {\n\t\tcfg.UserToken = os.Getenv(\"SMGMG_BK_USER_TOKEN\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_USER_SECRET\") != \"\" {\n\t\tcfg.UserSecret = os.Getenv(\"SMGMG_BK_USER_SECRET\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_DESTINATION\") != \"\" {\n\t\tcfg.Destination = os.Getenv(\"SMGMG_BK_DESTINATION\")\n\t}\n\n\tif os.Getenv(\"SMGMG_BK_FILE_NAMES\") != \"\" {\n\t\tcfg.Filenames = os.Getenv(\"SMGMG_BK_FILE_NAMES\")\n\t}\n}", "func (sm *ShardMaster) makeConfig(){\n\tf, err := os.OpenFile(sm.configFile, os.O_RDONLY, 0666)\n\tif os.IsNotExist(err){\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tvar config JSONConfig\n\t\terr = json.Unmarshal(scanner.Bytes(), &config)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tsm.addToConfigs(config)\n\t}\n}", "func NewConfigs(configs []*RawConfig, remoteEnv string, stdOut io.Writer, stdErr io.Writer) (*Configs, error) {\n\tif stdOut == nil {\n\t\tstdOut = os.Stdout\n\t}\n\tif stdErr == nil {\n\t\tstdErr = os.Stderr\n\t}\n\n\tconfs := &Configs{\n\t\tRemoteEnv: remoteEnv,\n\t\tFiles: []*File{},\n\t\tStdOut: stdOut,\n\t\tStdErr: stdErr,\n\t}\n\tosEnvs := ParseOSEnvs(os.Environ())\n\t// parentFile here is the highest priority ron.yaml file.\n\tvar parentFile *File\n\tfor _, config := range configs {\n\t\tvar targets map[string]*Target\n\t\tif err := yaml.Unmarshal([]byte(config.Targets), &targets); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar remotes Remotes\n\t\tif err := yaml.Unmarshal([]byte(config.Remotes), &remotes); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// initialize io for each target.\n\t\tfor name, target := range targets {\n\t\t\ttarget.W = stdOut\n\t\t\ttarget.WErr = stdErr\n\t\t\tif target.Name == \"\" {\n\t\t\t\ttarget.Name = name\n\t\t\t}\n\t\t\ttarget.targetConfigs = confs\n\t\t}\n\n\t\tf := &File{\n\t\t\trawConfig: config,\n\t\t\tFilepath: config.Filepath,\n\t\t\tTargets: targets,\n\t\t\tRemotes: remotes,\n\t\t}\n\t\tfor _, t := range targets {\n\t\t\tt.File = f\n\t\t}\n\t\te, err := NewEnv(parentFile, config, osEnvs, stdOut)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.Env = e\n\t\tif parentFile != nil {\n\t\t\tparentFile.Env.MergeTo(f.Env)\n\t\t}\n\t\tconfs.Files = append(confs.Files, f)\n\t\tif strings.HasSuffix(config.Filepath, ConfigFileName) {\n\t\t\tparentFile = f\n\t\t}\n\t}\n\n\tif remoteEnv != \"\" {\n\t\t// find any remote hosts if set.\n\t\tfilePrefix, env := splitTarget(remoteEnv)\n\t\tfor _, tf := range confs.Files {\n\t\t\tif filePrefix != \"\" && tf.Basename() != filePrefix {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif r, ok := tf.Remotes[env]; ok {\n\t\t\t\tconfs.RemoteHosts = r\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn confs, nil\n}", "func GetConfigData(f string, mergeEnv bool) (interface{}, error) {\n\tvar conf interface{}\n\t// First load any env data from files\n\tlogDebug.Printf(\"Loading config file:%s\\n\", f)\n\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading file '%s':%s\", f, err)\n\t}\n\tlogInfo.Printf(\"Loaded config data from %s\", f)\n\t// Allow templating of config data (e.g. env overrides of chart values):\n\tk8api := NewK8ApiNoop()\n\trendered, _, err := Render(k8api, string(b), EnvToMap())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error trying to render config data file '%s':%s\",\n\t\t\tf,\n\t\t\terr)\n\t}\n\n\t// Load yaml\n\tif err := yaml.Unmarshal([]byte(rendered), &conf); err != nil {\n\t\treturn nil, err\n\t}\n\t// Update any values which DON't exist from environment\n\tif mergeEnv && reflect.TypeOf(conf).Kind() == reflect.Map {\n\t\tconfTyped := conf.(map[interface{}]interface{})\n\t\tfor k, v := range EnvToMap() {\n\t\t\tif _, ok := confTyped[k]; !ok {\n\t\t\t\t// Value NOT found - update map:\n\t\t\t\tconfTyped[k] = v\n\t\t\t\tlogDebug.Printf(\"updated key %s from environment\", k)\n\t\t\t}\n\t\t}\n\t\t// Replace the referenced data with the strongly typed reference\n\t\tconf = confTyped\n\t}\n\treturn conf, nil\n}", "func (c *Config) createConfigFile(filename chezmoi.RelPath, data []byte) ([]byte, error) {\n\tfuncMap := make(template.FuncMap)\n\tchezmoi.RecursiveMerge(funcMap, c.templateFuncs)\n\tchezmoi.RecursiveMerge(funcMap, map[string]interface{}{\n\t\t\"promptBool\": c.promptBool,\n\t\t\"promptInt\": c.promptInt,\n\t\t\"promptString\": c.promptString,\n\t\t\"stdinIsATTY\": c.stdinIsATTY,\n\t\t\"writeToStdout\": c.writeToStdout,\n\t})\n\n\tt, err := template.New(string(filename)).Funcs(funcMap).Parse(string(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsb := strings.Builder{}\n\ttemplateData := c.defaultTemplateData()\n\tif c.init.data {\n\t\tchezmoi.RecursiveMerge(templateData, c.Data)\n\t}\n\tif err = t.Execute(&sb, templateData); err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(sb.String()), nil\n}", "func CreateEnvFileFromConfig(configs []operator.Configuration) error {\n\tfor _, config := range configs {\n\t\tvar value string\n\n\t\tif config.ValueIsBase64 {\n\t\t\tdecoded, err := Base64Decode(config.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvalue = decoded\n\t\t} else {\n\t\t\tvalue = config.Value\n\t\t}\n\n\t\tenvStr := fmt.Sprintf(\"export %s=\\\"%s\\\"\", config.Key, value)\n\t\terr := AppendEnvFile(envStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Init(env string) {\n\tvar err error\n\tconfig = viper.New()\n\tconfig.SetConfigType(\"yaml\")\n\tconfig.SetConfigName(env)\n\tif env != ENV_PRODUCTION {\n\t\tconfig.AddConfigPath(\"../src/config/\")\n\t\tconfig.AddConfigPath(\"src/config/\")\n\t} else {\n\t\tconfig.AddConfigPath(\".\")\n\t}\n\terr = config.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(\"error on parsing configuration file\", err)\n\t}\n}", "func NewCfnEnvironment_Override(c CfnEnvironment, scope awscdk.Construct, id *string, props *CfnEnvironmentProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_appconfig.CfnEnvironment\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func initConfig() {\n\t// System Config File\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\tviper.SetConfigName(\"config.yaml\")\n\n\t}\n\t// Get Env\n\tviper.AutomaticEnv()\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tlog.Log(\"msg\", \"Using config file:\"+viper.ConfigFileUsed())\n\t}\n\n\t// Offerings file\n\toffers = viper.New()\n\tif err := checkOfferFile(offerFile, offers); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func DefaultServiceConfigFromEnv() Server {\n\tconfigOnce.Do(func() {\n\t\tconfig = Server{\n\t\t\tDatabase: Database{\n\t\t\t\tHost: util.GetEnv(\"PGHOST\", \"postgres\"),\n\t\t\t\tPort: util.GetEnvAsInt(\"PGPORT\", 5432),\n\t\t\t\tDatabase: util.GetEnv(\"PGDATABASE\", \"development\"),\n\t\t\t\tUsername: util.GetEnv(\"PGUSER\", \"dbuser\"),\n\t\t\t\tPassword: util.GetEnv(\"PGPASSWORD\", \"\"),\n\t\t\t\tAdditionalParams: map[string]string{\n\t\t\t\t\t\"sslmode\": util.GetEnv(\"PGSSLMODE\", \"disable\"),\n\t\t\t\t},\n\t\t\t\tMaxOpenConns: util.GetEnvAsInt(\"DB_MAX_OPEN_CONNS\", runtime.NumCPU()*2),\n\t\t\t\tMaxIdleConns: util.GetEnvAsInt(\"DB_MAX_IDLE_CONNS\", 1),\n\t\t\t\tConnMaxLifetime: time.Second * time.Duration(util.GetEnvAsInt(\"DB_CONN_MAX_LIFETIME_SEC\", 60)),\n\t\t\t},\n\t\t\tEcho: EchoServer{\n\t\t\t\tDebug: util.GetEnvAsBool(\"SERVER_ECHO_DEBUG\", false),\n\t\t\t\tListenAddress: util.GetEnv(\"SERVER_ECHO_LISTEN_ADDRESS\", \":8080\"),\n\t\t\t\tHideInternalServerErrorDetails: util.GetEnvAsBool(\"SERVER_ECHO_HIDE_INTERNAL_SERVER_ERROR_DETAILS\", true),\n\t\t\t\tBaseURL: util.GetEnv(\"SERVER_ECHO_BASE_URL\", \"http://localhost:8080\"),\n\t\t\t\tEnableCORSMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_CORS_MIDDLEWARE\", true),\n\t\t\t\tEnableLoggerMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_LOGGER_MIDDLEWARE\", true),\n\t\t\t\tEnableRecoverMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_RECOVER_MIDDLEWARE\", true),\n\t\t\t\tEnableRequestIDMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_REQUEST_ID_MIDDLEWARE\", true),\n\t\t\t\tEnableTrailingSlashMiddleware: util.GetEnvAsBool(\"SERVER_ECHO_ENABLE_TRAILING_SLASH_MIDDLEWARE\", true),\n\t\t\t},\n\t\t\tPaths: PathsServer{\n\t\t\t\t// Please ALWAYS work with ABSOLUTE (ABS) paths from ENV_VARS (however you may resolve a project-relative to absolute for the default value)\n\t\t\t\tAPIBaseDirAbs: util.GetEnv(\"SERVER_PATHS_API_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/api\")), // /app/api (swagger.yml)\n\t\t\t\tMntBaseDirAbs: util.GetEnv(\"SERVER_PATHS_MNT_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/assets/mnt\")), // /app/assets/mnt (user-generated content)\n\t\t\t},\n\t\t\tAuth: AuthServer{\n\t\t\t\tAccessTokenValidity: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_ACCESS_TOKEN_VALIDITY\", 86400)),\n\t\t\t\tPasswordResetTokenValidity: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_PASSWORD_RESET_TOKEN_VALIDITY\", 900)),\n\t\t\t\tDefaultUserScopes: util.GetEnvAsStringArr(\"SERVER_AUTH_DEFAULT_USER_SCOPES\", []string{\"app\"}),\n\t\t\t\tLastAuthenticatedAtThreshold: time.Second * time.Duration(util.GetEnvAsInt(\"SERVER_AUTH_LAST_AUTHENTICATED_AT_THRESHOLD\", 900)),\n\t\t\t},\n\t\t\tManagement: ManagementServer{\n\t\t\t\tSecret: util.GetMgmtSecret(\"SERVER_MANAGEMENT_SECRET\"),\n\t\t\t},\n\t\t\tMailer: Mailer{\n\t\t\t\tDefaultSender: util.GetEnv(\"SERVER_MAILER_DEFAULT_SENDER\", \"[email protected]\"),\n\t\t\t\tSend: util.GetEnvAsBool(\"SERVER_MAILER_SEND\", true),\n\t\t\t\tWebTemplatesEmailBaseDirAbs: util.GetEnv(\"SERVER_MAILER_WEB_TEMPLATES_EMAIL_BASE_DIR_ABS\", filepath.Join(util.GetProjectRootDir(), \"/web/templates/email\")), // /app/web/templates/email\n\t\t\t\tTransporter: util.GetEnvEnum(\"SERVER_MAILER_TRANSPORTER\", MailerTransporterMock.String(), []string{MailerTransporterSMTP.String(), MailerTransporterMock.String()}),\n\t\t\t},\n\t\t\tSMTP: transport.SMTPMailTransportConfig{\n\t\t\t\tHost: util.GetEnv(\"SERVER_SMTP_HOST\", \"mailhog\"),\n\t\t\t\tPort: util.GetEnvAsInt(\"SERVER_SMTP_PORT\", 1025),\n\t\t\t\tUsername: util.GetEnv(\"SERVER_SMTP_USERNAME\", \"\"),\n\t\t\t\tPassword: util.GetEnv(\"SERVER_SMTP_PASSWORD\", \"\"),\n\t\t\t\tAuthType: transport.SMTPAuthTypeFromString(util.GetEnv(\"SERVER_SMTP_AUTH_TYPE\", transport.SMTPAuthTypeNone.String())),\n\t\t\t\tUseTLS: util.GetEnvAsBool(\"SERVER_SMTP_USE_TLS\", false),\n\t\t\t\tTLSConfig: nil,\n\t\t\t},\n\t\t\tFrontend: FrontendServer{\n\t\t\t\tBaseURL: util.GetEnv(\"SERVER_FRONTEND_BASE_URL\", \"http://localhost:3000\"),\n\t\t\t\tPasswordResetEndpoint: util.GetEnv(\"SERVER_FRONTEND_PASSWORD_RESET_ENDPOINT\", \"/set-new-password\"),\n\t\t\t},\n\t\t\tLogger: LoggerServer{\n\t\t\t\tLevel: util.LogLevelFromString(util.GetEnv(\"SERVER_LOGGER_LEVEL\", zerolog.DebugLevel.String())),\n\t\t\t\tRequestLevel: util.LogLevelFromString(util.GetEnv(\"SERVER_LOGGER_REQUEST_LEVEL\", zerolog.DebugLevel.String())),\n\t\t\t\tLogRequestBody: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_BODY\", false),\n\t\t\t\tLogRequestHeader: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_HEADER\", false),\n\t\t\t\tLogRequestQuery: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_REQUEST_QUERY\", false),\n\t\t\t\tLogResponseBody: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_RESPONSE_BODY\", false),\n\t\t\t\tLogResponseHeader: util.GetEnvAsBool(\"SERVER_LOGGER_LOG_RESPONSE_HEADER\", false),\n\t\t\t\tPrettyPrintConsole: util.GetEnvAsBool(\"SERVER_LOGGER_PRETTY_PRINT_CONSOLE\", false),\n\t\t\t},\n\t\t\tPush: PushService{\n\t\t\t\tUseFCMProvider: util.GetEnvAsBool(\"SERVER_PUSH_USE_FCM\", false),\n\t\t\t\tUseMockProvider: util.GetEnvAsBool(\"SERVER_PUSH_USE_MOCK\", true),\n\t\t\t},\n\t\t\tFCMConfig: provider.FCMConfig{\n\t\t\t\tGoogleApplicationCredentials: util.GetEnv(\"GOOGLE_APPLICATION_CREDENTIALS\", \"\"),\n\t\t\t\tProjectID: util.GetEnv(\"SERVER_FCM_PROJECT_ID\", \"no-fcm-project-id-set\"),\n\t\t\t\tValidateOnly: util.GetEnvAsBool(\"SERVER_FCM_VALIDATE_ONLY\", true),\n\t\t\t},\n\t\t}\n\n\t})\n\n\treturn config\n}", "func New(file ...string) *Config {\n\tname := DefaultConfigFile\n\tif len(file) > 0 {\n\t\tname = file[0]\n\t} else {\n\t\t// Custom default configuration file name from command line or environment.\n\t\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \"\" {\n\t\t\tname = customFile\n\t\t}\n\t}\n\tc := &Config{\n\t\tdefaultName: name,\n\t\tsearchPaths: garray.NewStrArray(true),\n\t\tjsonMap: gmap.NewStrAnyMap(true),\n\t}\n\t// Customized dir path from env/cmd.\n\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \"\" {\n\t\tif gfile.Exists(customPath) {\n\t\t\t_ = c.SetPath(customPath)\n\t\t} else {\n\t\t\tif errorPrint() {\n\t\t\t\tglog.Errorf(\"[gcfg] Configuration directory path does not exist: %s\", customPath)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dir path of working dir.\n\t\tif err := c.AddPath(gfile.Pwd()); err != nil {\n\t\t\tintlog.Error(context.TODO(), err)\n\t\t}\n\n\t\t// Dir path of main package.\n\t\tif mainPath := gfile.MainPkgPath(); mainPath != \"\" && gfile.Exists(mainPath) {\n\t\t\tif err := c.AddPath(mainPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\n\t\t// Dir path of binary.\n\t\tif selfPath := gfile.SelfDir(); selfPath != \"\" && gfile.Exists(selfPath) {\n\t\t\tif err := c.AddPath(selfPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}", "func GenerateKubeconfig(restConfig *rest.Config) (clientcmdapi.Config, error) {\n\tconst defaultID = \"default\"\n\n\tvar (\n\t\tcaData = restConfig.TLSClientConfig.CAData\n\t\tcertData = restConfig.TLSClientConfig.CertData\n\t\tkeyData = restConfig.TLSClientConfig.KeyData\n\n\t\tbearerToken = restConfig.BearerToken\n\t)\n\tif len(restConfig.TLSClientConfig.CAFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.CAFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read ca from %q: %w\", restConfig.TLSClientConfig.CAFile, err)\n\t\t}\n\t\tcaData = data\n\t}\n\tif len(restConfig.TLSClientConfig.CertFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.CertFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read cert from %q: %w\", restConfig.TLSClientConfig.CertFile, err)\n\t\t}\n\t\tcertData = data\n\t}\n\tif len(restConfig.TLSClientConfig.KeyFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.TLSClientConfig.KeyFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read key from %q: %w\", restConfig.TLSClientConfig.KeyFile, err)\n\t\t}\n\t\tkeyData = data\n\t}\n\tif len(restConfig.BearerTokenFile) != 0 {\n\t\tdata, err := ioutil.ReadFile(restConfig.BearerTokenFile)\n\t\tif err != nil {\n\t\t\treturn clientcmdapi.Config{}, fmt.Errorf(\"unable to read bearer token from %q: %w\", restConfig.BearerTokenFile, err)\n\t\t}\n\t\tbearerToken = string(data)\n\t}\n\n\tcfg := clientcmdapi.Config{\n\t\tAPIVersion: \"v1\",\n\t\tKind: \"Config\",\n\t\tCurrentContext: defaultID,\n\t\tContexts: map[string]*clientcmdapi.Context{\n\t\t\tdefaultID: {\n\t\t\t\tCluster: defaultID,\n\t\t\t\tAuthInfo: defaultID,\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{\n\t\t\tdefaultID: {\n\t\t\t\tToken: bearerToken,\n\n\t\t\t\tUsername: restConfig.Username,\n\t\t\t\tPassword: restConfig.Password,\n\n\t\t\t\tClientCertificateData: certData,\n\t\t\t\tClientKeyData: keyData,\n\t\t\t},\n\t\t},\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\tdefaultID: {\n\t\t\t\tServer: restConfig.Host + restConfig.APIPath,\n\t\t\t\tCertificateAuthorityData: caData,\n\t\t\t\tInsecureSkipTLSVerify: restConfig.Insecure,\n\t\t\t},\n\t\t},\n\t}\n\treturn cfg, nil\n}", "func createEnv(kubeServiceConfig KubeObjects, regionEnvStream <-chan *RegionEnv) <-chan *RegionEnv {\n\tenvKubernetesStream := make(chan *RegionEnv)\n\t// The secrets and config map take their name from the deployment.\n\t//deployment := kubeServiceConfig.Deployment.(*appsv1.Deployment)\n\tdeploymentName := kubeServiceConfig.parentObject().GetName()\n\tgo func() {\n\t\tdefer log.Debug(\"Closing createEnv channel\")\n\t\tdefer close(envKubernetesStream)\n\t\tfor regionEnv := range regionEnvStream {\n\t\t\tvar clientConfig *restclient.Config\n\t\t\tvar kubeConfigErr error\n\n\t\t\t// Check for errors in the stream\n\t\t\tif len(regionEnv.Errors) > 0 {\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on previous errors\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := regionEnv.validateSecretPath(deploymentName); err != nil {\n\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, err)\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Infof(\"Modifying region specific Kubernetes structs for %s.\", regionEnv.Region)\n\n\t\t\tif len(kubeServiceConfig.ClusterConfigs.Clusters) < 1 {\n\t\t\t\t// Follow kubectl convention.\n\t\t\t\tkubeConfigFile := setFromEnvStr(\"KUBECONFIG\", filepath.Join(os.Getenv(\"HOME\"), \".kube\", \"config\"))\n\t\t\t\tlog.Infof(\"Using kubeconfig file %s\", kubeConfigFile)\n\t\t\t\t// Region name must be the same as the kubernetes context name.\n\t\t\t\tclientConfig, kubeConfigErr = buildConfigFromFlags(regionEnv.Region, kubeConfigFile)\n\t\t\t\tif kubeConfigErr != nil {\n\t\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, kubeConfigErr)\n\t\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\t\tlog.Info(\"Exiting on kubeconfig construction errors\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tok := false\n\t\t\t\tclientConfig, ok = kubeServiceConfig.ClusterConfigs.RegionMap[regionEnv.Region]\n\t\t\t\tif !ok {\n\t\t\t\t\tkubeConfigErr = fmt.Errorf(\n\t\t\t\t\t\t\"config for region %s not found in %s\",\n\t\t\t\t\t\tregionEnv.Region,\n\t\t\t\t\t\tclusterConfigFile,\n\t\t\t\t\t)\n\t\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, kubeConfigErr)\n\t\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\t\tlog.Info(\"Exiting on missing config in vault.\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclientset, clientsetErr := kubernetes.NewForConfig(clientConfig)\n\t\t\tif clientsetErr != nil {\n\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, clientsetErr)\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on clientset creation error.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tregionEnv.Clientset = clientset\n\t\t\tistioClientset, clientsetErr := istioversioned.NewForConfig(clientConfig)\n\t\t\tif clientsetErr != nil {\n\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, clientsetErr)\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on istio clientset creation error.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tregionEnv.IstioClientset = istioClientset\n\t\t\tcatalogClientset, clientsetErr := catalogclientset.NewForConfig(clientConfig)\n\t\t\tif clientsetErr != nil {\n\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, clientsetErr)\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on catalog clientset creation error.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tregionEnv.CatalogClientset = catalogClientset\n\t\t\tcontourClientset, clientsetErr := contourversioned.NewForConfig(clientConfig)\n\t\t\tif clientsetErr != nil {\n\t\t\t\tregionEnv.Errors = append(regionEnv.Errors, clientsetErr)\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on contour clientset creation error.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tregionEnv.ContourClientset = contourClientset\n\n\t\t\t// Retrieve cluster specific porter2k8s settings from \"porter2k8s\" configmap.\n\t\t\tregionEnv.porter2k8sConfigMap()\n\t\t\tlog.Infof(\"Cluster settings %+v\", regionEnv.ClusterSettings)\n\n\t\t\t// Load regionEnv.Secrets of Kind \"porter2k8s\" into the region's cluster settings\n\t\t\tfor _, secret := range regionEnv.Secrets {\n\t\t\t\tif secret.Kind == \"porter2k8s\" {\n\t\t\t\t\tregionEnv.ClusterSettings[secret.Name] = secret.Value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Inject the logging sidecar if necessary before it gets copied to the regions\n\t\t\tif loggingSidecarInjectionRequired(regionEnv.ClusterSettings) {\n\t\t\t\tloggingSidecarInjectionSucceeded := regionEnv.addLoggingSidecarContainer(kubeServiceConfig)\n\t\t\t\tif !loggingSidecarInjectionSucceeded {\n\t\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\t\tlog.Info(\"Exiting on logging sidecar injection error.\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Each RegionEnv needs its own copy of the kubernetes objects, since they are modified with region\n\t\t\t// specific settings.\n\t\t\tregionEnv.ConfigMap = kubeServiceConfig.ConfigMap.DeepCopy()\n\t\t\tregionEnv.Deployment = kubeServiceConfig.Deployment.DeepCopy()\n\t\t\tregionEnv.Job = kubeServiceConfig.Job.DeepCopy()\n\t\t\tregionEnv.Gateway = kubeServiceConfig.Gateway.DeepCopy()\n\t\t\tregionEnv.HPAutoscaler = kubeServiceConfig.HPAutoscaler.DeepCopy()\n\t\t\tregionEnv.Ingress = kubeServiceConfig.Ingress.DeepCopy()\n\t\t\tregionEnv.PodDisruptionBudget = kubeServiceConfig.PodDisruptionBudget.DeepCopy()\n\t\t\tregionEnv.Service = kubeServiceConfig.Service.DeepCopy()\n\t\t\tregionEnv.ServiceAccount = kubeServiceConfig.ServiceAccount.DeepCopy()\n\t\t\tregionEnv.VirtualService = kubeServiceConfig.VirtualService.DeepCopy()\n\t\t\tregionEnv.IngressRouteList = kubeServiceConfig.IngressRouteList.DeepCopy()\n\t\t\tregionEnv.NamedSecrets = kubeServiceConfig.NamedSecrets.DeepCopy()\n\n\t\t\t// More than one service instance or binding are allowed.\n\t\t\tfor cloudKey, serviceInstances := range kubeServiceConfig.ServiceInstances {\n\t\t\t\tfor _, serviceInstance := range serviceInstances {\n\t\t\t\t\tregionEnv.ServiceInstances[cloudKey] = append(\n\t\t\t\t\t\tregionEnv.ServiceInstances[cloudKey],\n\t\t\t\t\t\tserviceInstance.DeepCopy(),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor cloudKey, serviceBindings := range kubeServiceConfig.ServiceBindings {\n\t\t\t\tfor _, serviceBinding := range serviceBindings {\n\t\t\t\t\tregionEnv.ServiceBindings[cloudKey] = append(\n\t\t\t\t\t\tregionEnv.ServiceBindings[cloudKey],\n\t\t\t\t\t\tserviceBinding.DeepCopy(),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconfigMapCreateSucceeded := regionEnv.createConfigMap(deploymentName)\n\t\t\tif !configMapCreateSucceeded {\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on configmap creation error.\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsecretCreateSucceeded := regionEnv.createSecret(deploymentName)\n\t\t\tif !secretCreateSucceeded {\n\t\t\t\tenvKubernetesStream <- regionEnv\n\t\t\t\tlog.Info(\"Exiting on secret creation failure.\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-regionEnv.Context.Done():\n\t\t\t\tlog.Info(\"Received Done\")\n\t\t\t\treturn\n\t\t\tcase envKubernetesStream <- regionEnv:\n\t\t\t}\n\t\t}\n\t}()\n\treturn envKubernetesStream\n}", "func (s server) generateConfig(w http.ResponseWriter, r *http.Request) {\n\tbodyBytes, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\ts.logger.WithError(err).Error(\"Unable to read request body\")\n\t\treturn\n\t}\n\n\tvar config initConfig\n\ts.logger.Debugf(\"Unmarshalled config as: %s\", string(bodyBytes))\n\terr = json.Unmarshal(bodyBytes, &config)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\ts.logger.WithError(err).Error(\"Unable to marshal request body\")\n\t\treturn\n\t}\n\n\tgithubUser := r.Header.Get(\"github_user\")\n\t// since we might be interacting with git, grab one of the checked out o/release repos and assign it to the current\n\t// user. we'll hold on to this until all git interactions are complete to prevent weirdness resulting from multiple users\n\t// dealing with the same working copy.\n\trepo, err := s.rm.retrieveAndLockAvailable(githubUser)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\ts.logger.WithError(err).Error(\"unable to get available repo\")\n\t\t_, _ = w.Write([]byte(\"Unable to retrieve a copy of the o/release repo to use. This probably just means that all of them are in use. Please try again in a few seconds.\"))\n\t\treturn\n\t}\n\n\treleaseRepo := repo.path\n\tdefer s.rm.returnInUse(repo)\n\n\t// if we're only converting the initConfig, then we won't commit any changes against the local working copy or create a pull request.\n\tif conversionOnly, err := strconv.ParseBool(r.URL.Query().Get(\"conversionOnly\")); err == nil && conversionOnly {\n\t\tgeneratedConfig, err := createCIOperatorConfig(config, releaseRepo, false)\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\ts.logger.WithError(err).Error(\"could not generate new CI Operator configuration\")\n\t\t\treturn\n\t\t}\n\t\tmarshalled, err := yaml.Marshal(generatedConfig)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\ts.logger.WithError(err).Error(\"could not marshal CI Operator configuration\")\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tif _, err := w.Write(marshalled); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\ts.logger.WithError(err).Error(\"Could not write CI Operator configuration response\")\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\texists := configExists(config.Org, config.Repo, releaseRepo)\n\tif exists {\n\t\tw.WriteHeader(http.StatusConflict)\n\t\t_, _ = fmt.Fprintf(w, \"Config already exists for org: %s and repo: %s\", config.Org, config.Repo)\n\t\treturn\n\t}\n\n\tif err := updateProwConfig(config, releaseRepo); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"could not update Prow configuration\")\n\t\treturn\n\t}\n\n\tif err := updatePluginConfig(config, releaseRepo); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"could not update Prow plugin configuration\")\n\t\treturn\n\t}\n\n\tif _, err := createCIOperatorConfig(config, releaseRepo, true); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"could not generate new CI Operator configuration\")\n\t\treturn\n\t}\n\n\terr = generateJobs(s.logger)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"failed to generate jobs\")\n\t\treturn\n\t}\n\n\tcreatePR, _ := strconv.ParseBool(r.URL.Query().Get(\"generatePR\"))\n\tbranch, err := pushChanges(repo, s.githubOptions, config.Org, config.Repo, githubUser, r.Header.Get(\"access_token\"), createPR)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"could not push changes\")\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write([]byte(fmt.Sprintf(\"https://github.com/%s/release/pull/new/%s\", githubUser, branch)))\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\ts.logger.WithError(err).Error(\"error occurred while writing response\")\n\t\treturn\n\t}\n}", "func TestGenerateComposefileEnv(t *testing.T) {\n\tcomposefile := filepath.Join(generateComposeBaseDir, \"env\", \"docker-compose.yml\")\n\tdockerfile := filepath.ToSlash(filepath.Join(generateComposeBaseDir, \"env\", \"env\", \"Dockerfile\"))\n\tenvFile := filepath.Join(generateComposeBaseDir, \"env\", \".env\")\n\tflags := []string{fmt.Sprintf(\"--compose-files=%s\", composefile), fmt.Sprintf(\"--env-file=%s\", envFile)}\n\ttOs := []generateTestObject{\n\t\t{\n\t\t\tfilePath: filepath.ToSlash(composefile),\n\t\t\twantImages: []generate.ComposefileImage{\n\t\t\t\t{Image: generate.Image{Name: \"busybox\", Tag: \"latest\"}, ServiceName: \"svc\", Dockerfile: dockerfile},\n\t\t\t},\n\t\t\ttestFn: checkGenerateComposefile,\n\t\t},\n\t}\n\ttestGenerate(t, flags, tOs)\n}", "func initConfig() {\n\tif configFlag != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(configFlag)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".puppet-environment\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".puppet-environment\")\n\t}\n\n\tviper.AutomaticEnv()\n\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\t// Bind config options to corresponding flags\n\tviper.BindPFlag(\"environments-config\", rootCmd.PersistentFlags().Lookup(\"environments-config\"))\n\tviper.SetDefault(\"environments-config\", \"/etc/puppetlabs/puppet/environments.yaml\")\n\n\tviper.BindPFlag(\"environments-root\", rootCmd.PersistentFlags().Lookup(\"environments-root\"))\n\tviper.BindPFlag(\"r10k-config\", rootCmd.PersistentFlags().Lookup(\"r10k-config\"))\n\tif codeManagerConfigured() {\n\t\t// Default to using config locations assuming Code Manager is in use\n\t\tviper.SetDefault(\"r10k-config\", \"/opt/puppetlabs/server/data/code-manager/r10k.yaml\")\n\t\tviper.SetDefault(\"environments-root\", \"/etc/puppetlabs/code-staging/environments\")\n\t} else {\n\t\t// Default to using config locations assuming no Code Manager\n\t\tviper.SetDefault(\"r10k-config\", \"/etc/puppetlabs/r10k/r10k.yaml\")\n\t\tviper.SetDefault(\"environments-root\", \"/etc/puppetlabs/code/environments\")\n\t}\n\n\t// Determine the absolute path to r10k.yaml and set it in the r10k package.\n\tif path, err := filepath.Abs(viper.GetString(\"r10k-config\")); err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tr10k.SetConfigPath(path)\n\t}\n}", "func initConfig() *domain.ApplicationConfig {\n\tconfigPath := util.GetEnv(envConfigPath, defaultConfigPath)\n\tprefix := util.GetEnv(envConfigPrefix, defaultConfigPrefix)\n\tcfg, err := util.ReadConfig(configPath, prefix)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn cfg\n}", "func initConfig() {\n\tviper.SetConfigFile(bootstrap.Arg.CfgFile)\n\tviper.AutomaticEnv() // read in environment variables that match\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}", "func (c *ProcessorConfig) PopulateFromEnv() error {\n\tenvEnvVar := fmt.Sprintf(\"%v_ENV\", strings.ToUpper(envVarPrefixProcessor))\n\terr := cconfig.PopulateFromDotEnv(envEnvVar)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = envconfig.Process(envVarPrefixProcessor, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.CronConfig != \"\" {\n\t\terr = c.validateCronConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = c.validateAPIURL()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.populatePersisterType()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.validateParameterizerDefaultValues()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.validateGovernmentParameterDefaultValues()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.validatePersister()\n}", "func GenerateEnvVars(application *model.Application, resourceDir string, appValues *templates.Application) error {\n\tappEnvVars := make(map[string]string, 0)\n\n\tfor _, appRes := range application.Resources {\n\t\t//elasticsearch-user:sit\n\t\tresDetails := strings.Split(appRes, sep)\n\t\tif len(resDetails) < 2 {\n\t\t\teMsg := fmt.Sprintf(\"application resource %s has missing template type, eg: cassandra/test1\", resDetails)\n\t\t\treturn errors.New(eMsg)\n\t\t}\n\t\tname := resDetails[0]\n\t\tenvType := resDetails[1]\n\t\tresource := &model.Resource{}\n\t\terr := GetResource(name, &resource, resourceDir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmatchEnvType := false\n\t\tfor _, resTemplate := range resource.Spec.ResourceTemplate {\n\t\t\t//Only using the context\n\t\t\tif resTemplate.Name == envType {\n\t\t\t\taddToEnvVars(name, appEnvVars, resTemplate.Element)\n\n\t\t\t\tif len(resTemplate.Infra) > 0 {\n\t\t\t\t\tinfra := strings.Split(resTemplate.Infra, sep)\n\t\t\t\t\tif len(infra) < 2 {\n\t\t\t\t\t\teMsg := fmt.Sprintf(\"resource infrastructure %s has missing template type, eg: cassandra-a/test\", infra)\n\t\t\t\t\t\treturn errors.New(eMsg)\n\t\t\t\t\t}\n\t\t\t\t\tinfraName := infra[0]\n\t\t\t\t\tinfraEnv := infra[1]\n\t\t\t\t\tinfrastructure := &model.Infrastructure{}\n\t\t\t\t\tGetInfrastructure(infraName, &infrastructure, resourceDir)\n\t\t\t\t\tmatchInfra := false\n\t\t\t\t\tfor _, infraTemplate := range infrastructure.Spec.Template {\n\t\t\t\t\t\tif infraEnv == infraTemplate.Name {\n\t\t\t\t\t\t\taddToEnvVars(name, appEnvVars, infraTemplate.Attributes)\n\t\t\t\t\t\t\tmatchInfra = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif matchInfra == false {\n\t\t\t\t\t\tlog.Print(fmt.Sprintf(\"[WARN] could not find matching infra for env type %s of %s\", infraEnv, resTemplate.Infra))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmatchEnvType = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif matchEnvType == false {\n\t\t\tlog.Print(fmt.Sprintf(\"[WARN] could not find matching env type %s of app %s\", envType, application.Name))\n\t\t}\n\t}\n\tappValues.EnvVars = appEnvVars\n\treturn nil\n}", "func createTmpConfigInFileSystem(rawJSON string) (func(), error) {\n\tconfigJSONFile, err := os.CreateTemp(os.TempDir(), \"configJSON-\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create file %v: %v\", configJSONFile.Name(), err)\n\t}\n\t_, err = configJSONFile.Write(json.RawMessage(rawJSON))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot write marshalled JSON: %v\", err)\n\t}\n\toldObservabilityConfigFile := envconfig.ObservabilityConfigFile\n\tenvconfig.ObservabilityConfigFile = configJSONFile.Name()\n\treturn func() {\n\t\tconfigJSONFile.Close()\n\t\tenvconfig.ObservabilityConfigFile = oldObservabilityConfigFile\n\t}, nil\n}", "func initConfig() {\n\tconfigSuffix := \"\"\n\tswitch viper.Get(\"APP_ENV\") {\n\tcase \"development\":\n\t\tconfigSuffix = \".development\"\n\t\tbreak\n\tdefault:\n\t\tbreak\n\t}\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.AddConfigPath(viper.Get(\"ROOM_CALC_CONFIG_DIRECTORY\").(string))\n\tviper.SetConfigName(\"gutils.config\" + configSuffix)\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Println(\"Can't read config:\", err)\n\t\tos.Exit(1)\n\t}\n}", "func (_m *Environment) SetConfigFile(_a0 string) {\n\t_m.Called(_a0)\n}", "func (a *App) GenerateConfig(c *ChangeRequest) ([]byte, error) {\n\tvar err error\n\tbuf := bytes.NewBuffer([]byte{})\n\tif err = a.Template.Execute(buf, c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), err\n}", "func GenerateConfigFileDiff(filePath string, context *Context) error {\n\treturn generateConfigFileFromTemplate(filePath, defaultEnvDiffConfig, context)\n}", "func getConfigFile() ([]byte, error) {\n\tif len(configFile) != 0 {\n\t\treturn configFile, nil\n\t}\n\tenvConf := os.Getenv(\"IGOR_CONFIG\")\n\tif envConf != \"\" {\n\t\treturn []byte(envConf), nil\n\t}\n\tfilename, _ := filepath.Abs(\"./config.json\")\n\tif _, err := os.Stat(filename); err != nil {\n\t\tjsonConfig = false\n\t\tfilename, _ = filepath.Abs(\"./config.yml\")\n\t}\n\tconfigFile, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn configFile, err\n\t}\n\treturn configFile, nil\n}", "func KubeEnvironmentProfileGenerator() gopter.Gen {\n\tif kubeEnvironmentProfileGenerator != nil {\n\t\treturn kubeEnvironmentProfileGenerator\n\t}\n\n\tgenerators := make(map[string]gopter.Gen)\n\tkubeEnvironmentProfileGenerator = gen.Struct(reflect.TypeOf(KubeEnvironmentProfile{}), generators)\n\n\treturn kubeEnvironmentProfileGenerator\n}", "func getDefaultEnv(t *testing.T) *routingEnv {\n\n\t//Build a config string\n\tconfigString := \"{\\\"token_password\\\": \\\"RvUP*b7fj9JPJ0*OQ9FlCW%Gg7vNTJWfvV7aQf@u9gWuYQ!S@e9SegAYjh!G%V7btMuGC8g29$qOw\\\"}\"\n\n\t//Define a memory repo\n\tuserRepo := users.NewRepoMemory()\n\n\t//Make a basic\n\tpassHelper := passwords.NewBasicHelper(configString)\n\n\t//Make a user helper\n\thelper := users.NewUserHelper(userRepo, nil, passHelper)\n\n\t//Add some default users\n\tuserOne := users.BasicUser{}\n\tuserOne.SetEmail(\"[email protected]\")\n\tuserOne.SetPassword(passHelper.HashPassword(\"123456\"))\n\t_, err := userRepo.AddUser(&userOne)\n\n\tuserTwo := users.BasicUser{}\n\tuserTwo.SetEmail(\"[email protected]\")\n\tuserTwo.SetPassword(passHelper.HashPassword(\"789012\"))\n\t_, err = userRepo.AddUser(&userTwo)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t//Define a new router repo\n\t//We also need to handle requests about users,\n\tuserHandler := users.NewHandler(helper, false)\n\n\t//Define the router, by in the routes specific to this project, and others\n\trouter := routing.NewRouter(nil, nil, nil, userHandler)\n\n\t//Add in middleware/filter that respons to CORS\n\trouter.Use(middleware.MakeCORSMiddlewareFunc()) //Make sure to add the cross site permission first\n\n\t//Add in middleware/filter that checks for user passwords\n\trouter.Use(middleware.MakeJwtMiddlewareFunc(router, userRepo, nil, passHelper))\n\n\t//Define the routing env\n\tenv := routingEnv{\n\t\trouter: router,\n\t}\n\n\treturn &env\n\n}", "func initKubeConfig(t *testing.T) {\n\tdirectoryKubeConfig := \"/tmp/.kube\"\n\tdefaultKubeConfigPath = directoryKubeConfig + \"/config\"\n\n\terr := os.MkdirAll(directoryKubeConfig, os.ModePerm)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfile, err := os.Create(defaultKubeConfigPath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tdir, _ := os.Getwd()\n\tconfigFile := dir + \"/../../../internal/test/forwarder/kubernetes/config\"\n\n\tfrom, err := os.OpenFile(configFile, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer from.Close()\n\n\t_, err = io.Copy(file, from)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func PrepareEnv(c *Config) (undo func() error, err error) {\n\tvar (\n\t\tnop = func() error { return nil }\n\t\tpath = filepath.Join(c.Target, \"runtime.go\")\n\t)\n\tout, err := os.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nop, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tfi, err := parser.ParseFile(token.NewFileSet(), path, out, parser.ImportsOnly)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Targeted package doesn't import the schema.\n\tif len(fi.Imports) == 0 {\n\t\treturn nop, nil\n\t}\n\tif err := os.WriteFile(path, append([]byte(\"// +build tools\\n\"), out...), 0644); err != nil {\n\t\treturn nil, err\n\t}\n\treturn func() error { return os.WriteFile(path, out, 0644) }, nil\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tsetDefaultValues()\n\n\t// Check whether the user has specified the WUM_UC_HOME environment variable.\n\tWUMUCHome = os.Getenv(constant.WUM_UC_HOME)\n\tif WUMUCHome == \"\" {\n\t\t// User has not specified WUM_UC_HOME.\n\t\t// Get the home directory of the current user.\n\t\thomeDirPath, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tutil.HandleErrorAndExit(err, \"Cannot determine the current user's home directory.\")\n\t\t}\n\t\tWUMUCHome = filepath.Join(homeDirPath, constant.WUMUC_HOME_DIR_NAME)\n\t\tlogger.Debug(fmt.Sprintf(\"wum-uc home directory path: %s\", WUMUCHome))\n\t\tutil.SetWUMUCLocalRepo(WUMUCHome)\n\t}\n\tviper.Set(constant.WUM_UC_HOME, WUMUCHome)\n\tutil.LoadWUMUCConfig(WUMUCHome)\n\n\tviper.SetConfigName(\"config\") // name of config file (without extension)\n\tviper.AddConfigPath(\".\")\n\tviper.AddConfigPath(\"$HOME/.wum-uc\")\n\t//viper.AutomaticEnv()\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tlogger.Debug(fmt.Sprintf(\"Config file found: %v\", viper.ConfigFileUsed()))\n\t} else {\n\t\tlogger.Debug(\"Config file not found.\")\n\t}\n\n\tlogger.Debug(fmt.Sprintf(\"PATH_SEPARATOR: %s\", constant.PATH_SEPARATOR))\n\tlogger.Debug(\"Config Values: ---------------------------\")\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.CHECK_MD5_DISABLED, viper.GetString(constant.CHECK_MD5_DISABLED)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_MANDATORY,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_MANDATORY)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_OPTIONAL,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_OPTIONAL)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.RESOURCE_FILES_SKIP,\n\t\tviper.GetStringSlice(constant.RESOURCE_FILES_SKIP)))\n\tlogger.Debug(fmt.Sprintf(\"%s: %s\", constant.PLATFORM_VERSIONS,\n\t\tviper.GetStringMapString(constant.PLATFORM_VERSIONS)))\n\tlogger.Debug(\"-----------------------------------------\")\n}", "func InitCfg() error {\n\tfilePath := \"/var/bcs/bcs.conf\"\n\tfile, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = codec.DecJson(file, &cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse %s. decode error: %v\", string(file), err)\n\t}\n\n\tkeyPwd := static.ClientCertPwd\n\tif cfg.CustomCertFile != \"\" && cfg.CustomKeyFile != \"\" && cfg.CustomCAFile != \"\" {\n\t\tcfg.CAFile = cfg.CustomCAFile\n\t\tcfg.CertFile = cfg.CustomCertFile\n\t\tcfg.KeyFile = cfg.CustomKeyFile\n\t\tkeyPwd = cfg.CustomKeyPwd\n\t}\n\n\tif cfg.CertFile != \"\" && cfg.KeyFile != \"\" && cfg.CAFile != \"\" {\n\t\tif cfg.clientSSL, err = ssl.ClientTslConfVerity(cfg.CAFile, cfg.CertFile, cfg.KeyFile, keyPwd); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to set client tls: %v\", err)\n\t\t}\n\t}\n\n\tif !strings.Contains(cfg.ApiHost, \"http\") {\n\t\tif cfg.clientSSL != nil {\n\t\t\tcfg.ApiHost = fmt.Sprintf(\"https://%s\", cfg.ApiHost)\n\t\t} else {\n\t\t\tcfg.ApiHost = fmt.Sprintf(\"http://%s\", cfg.ApiHost)\n\t\t}\n\t}\n\n\tDebugPrintf(\"api address: %s\\n\", cfg.ApiHost)\n\n\treturn nil\n}", "func initConfig() {\n\t// Find home directory.\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Search config in home directory or current directory with name \".ydc\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.AddConfigPath(\".\")\n\t\tviper.SetConfigName(\".ydc\")\n\t}\n\n\tviper.SetEnvPrefix(\"ydc\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"_\", \".\"))\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\tviper.SetDefault(\"workspace\", path.Join(home, \".ydcd\"))\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}", "func TestMakeConfig(t *testing.T) {\n\tfor _, testCase := range tt.CreateTTMakeConf() {\n\t\tt.Run(testCase.Name, func(t *testing.T) {\n\t\t\tos.Setenv(ConfEnvVar, testCase.EnvVar)\n\t\t\tconf, err := config.MakeConfig()\n\t\t\tif err != nil ||\n\t\t\t\t(testCase.IsDev && conf.Parameters.Env != \"dev\") ||\n\t\t\t\t(testCase.IsProd && conf.Parameters.Env != \"prod\") {\n\t\t\t\tt.Errorf(\"expected loading config for %v environment, got error: %v\", testCase.EnvVar, err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (c *Config) GenerateConfig(path string) {\n\n\tc = &Config{\n\t\tCertificate: \"cert.pem\",\n\t\tCertificateKey: \"cert.key\",\n\t\tWWWHost: \":9000\",\n\t\tWWWRoot: \"www\",\n\t\tTag: \"/chat\",\n\t\tTLS: false,\n\t\tVerbose: true,\n\t\tEscapeData: true,\n\t}\n\n\tb, _ := json.MarshalIndent(c, \"\", \"\\t\")\n\tioutil.WriteFile(*conf, b, 0644)\n\n}", "func initConfig() {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(-1)\n\t}\n\tsep := fmt.Sprintf(\"%c\", os.PathSeparator)\n\tif !strings.HasSuffix(wd, sep) {\n\t\twd += sep\n\t}\n\n\tconfFile = wd + \"gbb.json\"\n}", "func setUp() {\n\tdefaultData := map[string]string{\n\t\t\"key1\": \"value1\",\n\t\t\"key2\": \"value2\",\n\t\t\"key3\": \"value3\",\n\t}\n\tjsonData, _ := json.Marshal(defaultData)\n\terr := ioutil.WriteFile(JsonTestPath, jsonData, 0644)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func initConfig() {\n\t// Find home directory.\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tlogger.Fatal(err.Error())\n\t}\n\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Search config in home directory with name \".ngecli\" (without extension).\n\t\tviper.AddConfigPath(path.Join(home, \".ngecli\"))\n\t\tviper.AddConfigPath(\".\")\n\t\tviper.SetConfigName(\"config\")\n\t}\n\n\tviper.SetEnvPrefix(\"ngecli\")\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\nREAD_CONFIG:\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t} else {\n\t\tfmt.Println(\"No config file found, creating one...\")\n\n\t\tconfDir := path.Join(home, \".ngecli\")\n\t\tif _, err := os.Stat(confDir); os.IsNotExist(err) {\n\t\t\tos.Mkdir(confDir, os.ModePerm)\n\t\t}\n\n\t\terr = viper.WriteConfigAs(path.Join(confDir, \"config.yaml\"))\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err.Error())\n\t\t}\n\n\t\tgoto READ_CONFIG\n\t}\n}", "func InitConfig(file string) {\n\traw, err := ioutil.ReadFile(file)\n\n\tif err != nil {\n\t\t// log to printf because logging is unavailable at this time\n\t\tfmt.Fprintf(os.Stderr, \"Unable to open configuration file: %s\", file)\n\t\tos.Exit(1)\n\t}\n\n\terr = json.Unmarshal(raw, &AppConfig)\n\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, \"Error reading configuration file\")\n\t\tos.Exit(1)\n\t}\n}", "func initConfig() {\n\tif !debug {\n\t\tlog.AllowLevel(\"debug\")\n\t}\n\n\tconfig = &registrar.Config{}\n\tconfigPath, err := os.UserConfigDir()\n\tif err != nil {\n\t\t// TODO handle this\n\t\tpanic(\"cannot retrieve the user configuration directory\")\n\t}\n\tdefaultCfgPath := path.Join(configPath, \"cosmos\", \"registry\")\n\tafero.NewOsFs().MkdirAll(defaultCfgPath, 0700)\n\n\tviper.SetConfigType(\"yaml\")\n\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\tviper.AddConfigPath(defaultCfgPath)\n\t\tviper.SetConfigName(\"config\")\n\t}\n\n\t// set the workspace folder\n\tcfgFilePath := viper.ConfigFileUsed()\n\tif cfgFilePath == \"\" {\n\t\tcfgFilePath = path.Join(defaultCfgPath, \"config.yaml\")\n\t}\n\t//now read in the config\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tviper.Unmarshal(config)\n\t\tlogger.Debug(\"Using config file at \", \"config\", viper.ConfigFileUsed())\n\t} else {\n\t\tswitch err.(type) {\n\t\tcase viper.ConfigFileNotFoundError:\n\t\t\tif noInteraction {\n\t\t\t\tprintln(\"config file not found\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tif err = interactiveSetup(); err != nil {\n\t\t\t\tprintln(\"unexpected error \", err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tviper.Unmarshal(config)\n\t\t\tprintln(\"\\nThe configuration is:\")\n\t\t\tprompts.PrettyMap(viper.AllSettings())\n\t\t\tprintln()\n\t\t\tif ok := prompts.Confirm(false, \"save the configuration?\"); !ok {\n\t\t\t\tprintln(\"aborting, run the command again to change the configuration\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\n\t\t\tif err = viper.WriteConfigAs(cfgFilePath); err != nil {\n\t\t\t\tprintln(\"aborting, error writing the configuration file:\", err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tprintln(\"config file saved in \", cfgFilePath)\n\n\t\tdefault:\n\t\t\tprintln(\"the configuration file appers corrupted: \", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\t// set the config workspace folder\n\tconfig.Workspace = path.Dir(cfgFilePath)\n}", "func (c *Configuration) FromEnv() {\n\tif api := getOSPrefixEnv(\"API\"); api != nil {\n\t\tc.APIListener = *api\n\t}\n\n\tif httpListener := getOSPrefixEnv(\"HTTP\"); httpListener != nil {\n\t\tc.HTTPListener = *httpListener\n\t}\n\n\tif httpsListener := getOSPrefixEnv(\"HTTPS\"); httpsListener != nil {\n\t\tc.HTTPSListener = *httpsListener\n\t}\n\n\tif dbEndpoint := getOSPrefixEnv(\"DB_ENDPOINT\"); dbEndpoint != nil {\n\t\tc.DynamoDB.Endpoint = *dbEndpoint\n\t}\n\n\tif dbRegion := getOSPrefixEnv(\"DB_REGION\"); dbRegion != nil {\n\t\tc.DynamoDB.Region = *dbRegion\n\t}\n\n\tif dbKey := getOSPrefixEnv(\"DB_KEY\"); dbKey != nil {\n\t\tif dbSecret := getOSPrefixEnv(\"DB_SECRET\"); dbSecret != nil {\n\t\t\tc.DynamoDB.Key = *dbKey\n\t\t\tc.DynamoDB.Secret = *dbSecret\n\t\t}\n\t}\n\n\tif dbBootstrap := getOSPrefixEnv(\"BOOTSTRAP\"); dbBootstrap != nil {\n\t\tc.Bootstrap = len(*dbBootstrap) > 0 && *dbBootstrap != \"0\"\n\t}\n\n\tif logLevel := getOSPrefixEnv(\"LOG_LEVEL\"); logLevel != nil {\n\t\tc.LogLevel = *logLevel\n\t}\n\n\tif logFormatter := getOSPrefixEnv(\"LOG_FORMATTER\"); logFormatter != nil {\n\t\tc.LogFormatter = *logFormatter\n\t}\n}", "func TestGetConfigInfoWithoutIndexdOrMDSCreds(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"Expecting getConfigInfo to panic since Indexd and Metadata Service creds were not present in CONFIG_FILE\")\n\t\t}\n\t}()\n\n\tjsonConfigInfo :=\n\t\t`\n\t{}\n\t`\n\terr := os.Setenv(\"CONFIG_FILE\", jsonConfigInfo)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgetConfigInfo()\n}", "func (config *configuration) getEnvVariables() error {\n\t// method 1: Decode json file\n\tfile, err := os.Open(confFile)\n\tif err != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Open config file error.\", err)\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoderErr := decoder.Decode(&config)\n\tif decoderErr != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Decode config file error.\", decoderErr)\n\t\treturn decoderErr\n\t}\n\n\t// method 2: Unmarshal json file\n\t// jsonData, err := ioutil.ReadFile(confFile)\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// unmarshalErr := json.Unmarshal(jsonData, &config)\n\t// if unmarshalErr != nil {\n\t// \treturn unmarshalErr\n\t// }\n\treturn nil\n}", "func initConfig(lo *logrus.Logger, cfgDefault string, envPrefix string) (*koanf.Koanf, error) {\n\tvar (\n\t\tko = koanf.New(\".\")\n\t\tf = flag.NewFlagSet(\"front\", flag.ContinueOnError)\n\t)\n\n\t// Configure Flags.\n\tf.Usage = func() {\n\t\tfmt.Println(f.FlagUsages())\n\t\tos.Exit(0)\n\t}\n\n\t// Register `--config` flag.\n\tcfgPath := f.String(\"config\", cfgDefault, \"Path to a config file to load.\")\n\n\t// Parse and Load Flags.\n\terr := f.Parse(os.Args[1:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load the config files from the path provided.\n\tlo.WithField(\"path\", *cfgPath).Info(\"attempting to load config from file\")\n\n\terr = ko.Load(file.Provider(*cfgPath), toml.Parser())\n\tif err != nil {\n\t\t// If the default config is not present, print a warning and continue reading the values from env.\n\t\tif *cfgPath == cfgDefault {\n\t\t\tlo.WithError(err).Warn(\"unable to open sample config file\")\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlo.Info(\"attempting to read config from env vars\")\n\t// Load environment variables if the key is given\n\t// and merge into the loaded config.\n\tif envPrefix != \"\" {\n\t\terr = ko.Load(env.Provider(envPrefix, \".\", func(s string) string {\n\t\t\treturn strings.Replace(strings.ToLower(\n\t\t\t\tstrings.TrimPrefix(s, envPrefix)), \"__\", \".\", -1)\n\t\t}), nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn ko, nil\n}", "func initConfig() {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\ttdPath := path.Join(home, \".td\")\n\tif _, err := os.Stat(tdPath); os.IsNotExist(err) {\n\t\tos.MkdirAll(tdPath, os.ModePerm)\n\t}\n\n\tviper.AddConfigPath(tdPath)\n\tviper.Set(\"tdPath\", tdPath)\n\tviper.SetConfigName(\".config\")\n\tviper.AutomaticEnv()\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tviper.WriteConfigAs(path.Join(tdPath, \".config.json\"))\n\t}\n\n\tviper.SetDefault(\"boards_file\", path.Join(tdPath, \"boards.json\"))\n\tviper.SetDefault(\"current_board\", \"default\")\n}", "func EnvConfigFile() string {\n\treturn os.Getenv(ConfigFileEnvKey)\n}", "func Init(configFile string) {\n\tinitializer := configInitializer{\n\t\tCommon: newDefaultCommonConfig(),\n\t\tServer: newDefaultServerConfig(),\n\t\tClient: newDefaultClientConfig(),\n\t}\n\n\tif configFile == \"\" {\n\t\tconfigFile = \"./cfg/dtail.json\"\n\t}\n\n\tif _, err := os.Stat(configFile); !os.IsNotExist(err) {\n\t\tinitializer.parseConfig(configFile)\n\t}\n\n\t// Assign pointers to global variables, so that we can access the\n\t// configuration from any place of the program.\n\tCommon = initializer.Common\n\tServer = initializer.Server\n\tClient = initializer.Client\n\n\tif Server.MapreduceLogFormat == \"\" {\n\t\tServer.MapreduceLogFormat = \"default\"\n\t}\n}", "func (cfg *Config) makeEnv(c context.Context, e *vpython.Environment) (*Env, error) {\n\t// We MUST have a package loader.\n\tif cfg.Loader == nil {\n\t\treturn nil, errors.New(\"no package loader provided\")\n\t}\n\n\t// Resolve our base directory, if one is not supplied.\n\tif cfg.BaseDir == \"\" {\n\t\t// Use one in a temporary directory.\n\t\tcfg.BaseDir = filepath.Join(os.TempDir(), \"vpython\")\n\t\tlogging.Debugf(c, \"Using tempdir-relative environment root: %s\", cfg.BaseDir)\n\t}\n\tif err := filesystem.AbsPath(&cfg.BaseDir); err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to resolve absolute path of base directory\").Err()\n\t}\n\n\t// Enforce maximum path length.\n\tif cfg.MaxScriptPathLen > 0 {\n\t\tif longestPath := longestGeneratedScriptPath(cfg.BaseDir); longestPath != \"\" {\n\t\t\tlongestPathLen := utf8.RuneCountInString(longestPath)\n\t\t\tif longestPathLen > cfg.MaxScriptPathLen {\n\t\t\t\treturn nil, errors.Reason(\n\t\t\t\t\t\"expected deepest path length (%d) exceeds threshold (%d)\",\n\t\t\t\t\tlongestPathLen, cfg.MaxScriptPathLen,\n\t\t\t\t).InternalReason(\"longestPath(%q)\", longestPath).Err()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Construct a new, independent Environment for this Env.\n\te = e.Clone()\n\tif cfg.Spec != nil {\n\t\te.Spec = cfg.Spec.Clone()\n\t}\n\tif err := spec.NormalizeEnvironment(e); err != nil {\n\t\treturn nil, errors.Annotate(err, \"invalid environment\").Err()\n\t}\n\n\t// If the environment doesn't specify a VirtualEnv package (expected), use\n\t// our default.\n\tif e.Spec.Virtualenv == nil {\n\t\te.Spec.Virtualenv = &cfg.Package\n\t}\n\n\tif err := cfg.Loader.Resolve(c, e); err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to resolve packages\").Err()\n\t}\n\n\tif err := cfg.resolvePythonInterpreter(c, e.Spec); err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to resolve system Python interpreter\").Err()\n\t}\n\te.Runtime.Path = cfg.si.Python\n\te.Runtime.Version = e.Spec.PythonVersion\n\n\tvar err error\n\tif e.Runtime.Hash, err = cfg.si.Hash(); err != nil {\n\t\treturn nil, err\n\t}\n\tlogging.Debugf(c, \"Resolved system Python runtime (%s @ %s): %s\",\n\t\te.Runtime.Version, e.Runtime.Hash, e.Runtime.Path)\n\n\t// Ensure that our base directory exists.\n\tif err := filesystem.MakeDirs(cfg.BaseDir); err != nil {\n\t\treturn nil, errors.Annotate(err, \"could not create environment root: %s\", cfg.BaseDir).Err()\n\t}\n\n\t// Generate our environment name based on the deterministic hash of its\n\t// fully-resolved specification.\n\tenvName := cfg.OverrideName\n\tif envName == \"\" {\n\t\tenvName = cfg.envNameForSpec(e.Spec, e.Runtime)\n\t}\n\tenv := cfg.envForName(envName, e)\n\treturn env, nil\n}", "func genExitConfig(fname string) (cfg *exitConfig) {\n cfg = new(exitConfig)\n cfg.Exit = genDefaultExitNet()\n cfg.Exits = []exitNetConfig{}\n return\n}", "func ReadConfigFile(configFile string) {\n\tfileBytes, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to load configuration file %s\", configFile)\n\t\tpanic(err)\n\t}\n\n\tif hasJSONPrefix(fileBytes) {\n\t\terr = json.Unmarshal(fileBytes, &Config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\terr = yaml.Unmarshal(fileBytes, &Config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t// Next section allows env variable overwrites config file value\n\tfields := reflect.TypeOf(Config)\n\t// pointer to struct\n\tvalues := reflect.ValueOf(&Config)\n\t// struct\n\tst := values.Elem()\n\tfor i := 0; i < fields.NumField(); i++ {\n\t\tfield := fields.Field(i).Name\n\t\tf := st.FieldByName(field)\n\n\t\tif f.Kind() == reflect.String {\n\t\t\tenvV := os.Getenv(field)\n\t\t\tif len(envV) > 0 && f.IsValid() && f.CanSet() {\n\t\t\t\tf.SetString(strings.TrimSuffix(envV, \"\\n\")) // ensure no \\n at the end of line that was introduced by loading k8s secrete file\n\t\t\t}\n\t\t\tos.Setenv(field, f.String())\n\t\t}\n\t}\n\n\tif IsPulsarJWTEnabled() {\n\t\tSuperRoles = []string{}\n\t\tfor _, v := range strings.Split(Config.SuperRoles, \",\") {\n\t\t\tSuperRoles = append(SuperRoles, strings.TrimSpace(v))\n\t\t}\n\t} else {\n\t\tSuperRoles = []string{DummySuperRole}\n\t}\n\n\tlog.Infof(\"configuration loaded is %v\", Config)\n}", "func initConfig() error {\n\tb, err := envsubst.ReadFileRestricted(cfgFile, true, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to read the file\")\n\t}\n\tviper.SetConfigType(strings.TrimPrefix(filepath.Ext(cfgFile), \".\"))\n\terr = viper.ReadConfig(bytes.NewBuffer(b))\n\treturn errors.Wrap(err, \"failed to unmarshal the initial map of configs\")\n}", "func initConfig() {\n\n\tsetUpLogs()\n\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Switch to default program path\n\t\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconfdir := fmt.Sprintf(\"%s/conf\", dir)\n\t\t// we came from bin directory\n\t\tconfdir1 := fmt.Sprintf(\"%s/../conf\", dir)\n\t\t// Search yaml config file in program path with name \"gotsx.yaml\".\n\t\tviper.AddConfigPath(confdir)\n\t\tviper.AddConfigPath(confdir1)\n\t\tviper.AddConfigPath(dir)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\"gotsx\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\tcfgFileNotFound = true\n\t\t\tfmt.Println(\"Config file not found\")\n\t\t} else {\n\t\t\tLog.Debug(\"Something look strange\")\n\t\t\tLog.Debugf(\"error: %v\\n\", err)\n\t\t}\n\t} else {\n\t\tLog.Debugf(\"Using config file: %s\\n\", viper.ConfigFileUsed())\n\t}\n\n\tmanageDefault()\n}", "func createMainConfig(file *string, paths *string, basename *string) *viper.Viper {\n\tconfig := viper.New()\n\n\tconfig.SetEnvPrefix(utils.ConfigPrefix) // Env vars start with 'SLA_'\n\tconfig.AutomaticEnv()\n\tconfig.SetDefault(utils.CheckPeriodPropertyName, utils.DefaultCheckPeriod)\n\tconfig.SetDefault(utils.RepositoryTypePropertyName, utils.DefaultRepositoryType)\n\tconfig.SetDefault(utils.ExternalIDsPropertyName, utils.DefaultExternalIDs)\n\n\tif *file != \"\" {\n\t\tconfig.SetConfigFile(*file)\n\t} else {\n\t\tconfig.SetConfigName(*basename)\n\t\tfor _, path := range strings.Split(*paths, \":\") {\n\t\t\tconfig.AddConfigPath(path)\n\t\t}\n\t}\n\n\terrConfig := config.ReadInConfig()\n\tif errConfig != nil {\n\t\tlog.Println(\"Can't find configuration file: \" + errConfig.Error())\n\t\tlog.Println(\"Using defaults\")\n\t}\n\treturn config\n}", "func create_Config() {\n\tconf, _ := os.Create(ConfigFileName)\n\tdefer conf.Close();\n\n\tfmt.Print(\"Creating new config.json file\");\n\tfmt.Println(\"Eventbrite Configuration:\");\n\tfmt.Printf(\"Event ID: \"); fmt.Scan(Config.Event.Event_id);\n\tfmt.Printf(\"Oathtoken: \"); fmt.Scan(Config.Event.Oathtoken);\n\tfmt.Print(\"Misc Configuration: \");\n\tfmt.Printf(\"Img Dir: \"); fmt.Scan(Config.Img_dir);\n\tfmt.Printf(\"Max Spots: \"); fmt.Scan(Config.Max_Spots);\n\tstr, _ := json.Marshal(Config);\n\t_, err := conf.Write(str);\n\t\n\tif err != nil {\n\t\tfmt.Println(err);\n\t}\n\t\n}", "func initConfig() {\n\tlog.SetHandler(text.New(os.Stderr))\n\tif debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\tviper.SetEnvPrefix(\"ecs\")\n\tviper.AutomaticEnv() // read in environment variables that match\n\tif cfgFile != \"\" || environment != \"\" {\n\t\t// Use config file from the flag. cfgFile takes precedence over environment\n\t\tif cfgFile != \"\" {\n\t\t\tviper.SetConfigFile(cfgFile)\n\t\t} else {\n\t\t\tif cfg, err := findConfigByEnvironment(environment); err != nil {\n\t\t\t\tlog.WithError(err).Fatal(\"Can't find the config\")\n\t\t\t} else {\n\t\t\t\tviper.SetConfigFile(cfg)\n\t\t\t}\n\t\t}\n\t\t// If a config file is found, read it in.\n\t\tif err := viper.ReadInConfig(); err == nil {\n\t\t\tlog.Infof(\"Using config file: %s\", viper.ConfigFileUsed())\n\t\t} else {\n\t\t\tlog.WithError(err).Fatal(\"Had some errors while parsing the config\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n}", "func File(env string) {\n\tfmt.Println(\"begin\")\n\tfile, err := ioutil.ReadFile(\"config/\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Configuraiton '%s' file not found\", \"config/\"+env+\".json\")\n\t\treturn\n\t}\n\tdata := json.Parse(file)\n\tcontext.Instance().Set(\"host\", data.GetString(\"host\"))\n\tcontext.Instance().Set(\"port\", data.GetString(\"port\"))\n\tcontext.Instance().Set(\"user\", data.GetString(\"user\"))\n\tcontext.Instance().Set(\"password\", data.GetString(\"password\"))\n\tcontext.Instance().Set(\"database\", data.GetString(\"database\"))\n}" ]
[ "0.6162562", "0.59296834", "0.5718468", "0.56433964", "0.56100684", "0.5589865", "0.5389433", "0.5334706", "0.5301187", "0.52670103", "0.5165857", "0.5123443", "0.51066464", "0.50811946", "0.5077389", "0.5075376", "0.50733215", "0.50587666", "0.50569767", "0.5054178", "0.5047169", "0.5013352", "0.49767455", "0.49696913", "0.4964096", "0.49522388", "0.49480557", "0.49427462", "0.49308568", "0.49251625", "0.49158752", "0.49070907", "0.49012148", "0.48884442", "0.48712248", "0.48694187", "0.48674756", "0.48638263", "0.48560908", "0.4851706", "0.48493287", "0.48437545", "0.48386806", "0.4829832", "0.48289576", "0.4828609", "0.48230305", "0.4822741", "0.48172686", "0.48143592", "0.4813931", "0.48108524", "0.48078996", "0.47978964", "0.47941026", "0.47903427", "0.47747472", "0.47742143", "0.47732937", "0.476659", "0.47644442", "0.4755989", "0.4752335", "0.47514728", "0.47457016", "0.474319", "0.4738825", "0.47374612", "0.47291073", "0.4727287", "0.4725833", "0.47242987", "0.4717962", "0.471329", "0.4713028", "0.47052464", "0.47025776", "0.47014144", "0.4699321", "0.4695544", "0.46948153", "0.4694275", "0.46940157", "0.4690811", "0.46899173", "0.46895432", "0.46876904", "0.46823695", "0.46806487", "0.46800196", "0.4677468", "0.4677292", "0.46726263", "0.46724173", "0.4671423", "0.46714136", "0.46713954", "0.4671294", "0.46652007", "0.46632767" ]
0.7855235
0
NewMiddleware return a new instance of a basic HTTP middleware.
func NewMiddleware(limiter *ratelimit.Limiter, getID IDHandler, onIDError ErrorHandler) *Middleware { middleware := &Middleware{ Limiter: limiter, GetID: getID, OnIDError: onIDError, } return middleware }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMiddleware() Middleware {\n\treturn Middleware{}\n}", "func New(middlewares ...Middleware) Middleware {\n\treturn Middleware(func(handler http.Handler) http.Handler {\n\t\treturn handler\n\t}).Use(middlewares...)\n}", "func NewMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlogger := WithContext(r.Context())\n\n\t\tlogger.Infow(\"Started request\",\n\t\t\t\"method\", r.Method,\n\t\t\t\"path\", r.URL.Path,\n\t\t)\n\n\t\t// reverse proxy replaces original request with target request, so keep original one\n\t\toriginalURL := &url.URL{}\n\t\t*originalURL = *r.URL\n\n\t\tlogger = logger.With(\n\t\t\t\"method\", r.Method,\n\t\t\t\"host\", r.Host,\n\t\t\t\"request\", r.RequestURI,\n\t\t\t\"remote-addr\", r.RemoteAddr,\n\t\t\t\"referer\", r.Referer(),\n\t\t\t\"user-agent\", r.UserAgent(),\n\t\t)\n\n\t\tm := httpsnoop.CaptureMetrics(handler, w, r)\n\n\t\tlogger = logger.With(\n\t\t\t\"code\", m.Code,\n\t\t\t\"duration\", int(m.Duration/time.Millisecond),\n\t\t\t\"duration-fmt\", m.Duration.String(),\n\t\t)\n\n\t\tlogger.Info(\"Completed handling request\")\n\t})\n}", "func New(options ...Option) *Middleware {\n\tres := Middleware{\n\t\tprefix: \"\",\n\t\tmaxBodySize: 1024,\n\t\tflags: []Flag{All},\n\t\tlog: stdBackend{},\n\t}\n\tfor _, opt := range options {\n\t\topt(&res)\n\t}\n\treturn &res\n}", "func (a *Agent) NewMiddleware(options MiddlewareOptions) func(http.Handler) http.Handler {\n\treturn func(handler http.Handler) http.Handler {\n\t\treturn a.NewHandler(handler, options)\n\t}\n}", "func NewMiddleware(config *Config) (*Middleware, error) {\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmux := http.NewServeMux()\n\tconfig.mux = mux\n\n\tm := &Middleware{\n\t\tConfig: config,\n\t}\n\tmux.HandleFunc(m.CallbackPath, m.authorizeCallback)\n\tmux.HandleFunc(\"/\", m.defaultHandler)\n\n\treturn m, nil\n}", "func NewMiddleware(l *zap.Logger) func(next http.Handler) http.Handler {\n\treturn loggerMiddleware{l}.Handler\n}", "func NewMiddleware(appname string, license string) (*NewRelicMiddleware, error) {\n\tapp, err := newrelic.NewApplication(newrelic.NewConfig(appname, license))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NewRelicMiddleware{app, makeTransactionName}, nil\n}", "func New(fs ...MiddlewareFunc) Router {\n\tglobalMiddleware := transformMiddlewareFunc(fs...)\n\n\tr := &router{\n\t\ttree: mux.NewTree(),\n\t\tglobalMiddleware: globalMiddleware,\n\t}\n\n\tr.handler = globalMiddleware.Compose(http.HandlerFunc(r.serveHTTP)).(http.Handler)\n\n\treturn r\n}", "func NewMiddleware(listeners ...ClientEventCallback) *Middleware {\n\treturn &Middleware{\n\t\tcurrentEvent: server.UndefinedEvent(),\n\t\tlisteners: listeners,\n\t}\n}", "func NewMiddleware(appname string, license string) (*NewRelicMiddleware, error) {\n\tnrcfg := newrelic.NewConfig(appname, license)\n\tnrcfg.ErrorCollector.IgnoreStatusCodes = []int{\n\t\thttp.StatusNotFound,\n\t\thttp.StatusBadRequest,\n\t\thttp.StatusUnprocessableEntity,\n\t}\n\n\tapp, err := newrelic.NewApplication(nrcfg)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &NewRelicMiddleware{app, makeTransactionName}, nil\n}", "func NewMiddleware(backend TokenIntrospecter) *Middleware {\n\treturn &Middleware{Backend: backend}\n}", "func NewMiddleware(directorURL string) *middleware {\n\treturn &middleware{\n\t\tdirectorURL: directorURL,\n\t}\n}", "func New() echo.MiddlewareFunc {\n\treturn NewWithLogger(logrus.StandardLogger())\n}", "func New() echo.MiddlewareFunc {\n\treturn NewWithLogger(logrus.StandardLogger())\n}", "func New(next http.Handler, requestFilters []RequestFilter,\n\tresponseFilters []ResponseFilter, mode ProtectionMode) Middleware {\n\treturn Middleware{\n\t\tNext: next,\n\t\tRequestFilters: requestFilters,\n\t\tResponseFilters: responseFilters,\n\t\tMode: mode,\n\t\tError: BasicError,\n\t\tNow: time.Now,\n\t\tLogger: func(s string) { os.Stderr.WriteString(s) },\n\t}\n}", "func NewMiddleware(uri, prefix string) *Middleware {\n\tc, err := g2s.Dial(\"udp\", uri)\n\tif err != nil {\n\t\tlog.Println(\"No statsd server on %s\", uri)\n\t\tc = nopClient{}\n\t}\n\treturn &Middleware{client: c, prefix: prefix}\n}", "func NewMiddleware(ctx Context, command string) (Middleware, error) {\n\tif command == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tctx.Logger = ctx.Logger.With().\n\t\tStr(LoggerKeyComponent, \"middleware\").\n\t\tStr(\"command\", command).\n\t\tLogger()\n\n\tcmd := exec.CommandContext(ctx.StdContext, command)\n\tcmd.Stderr = &logWrapper{\n\t\tl: ctx.Logger,\n\t}\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get stdin pipe: %w\", err)\n\t}\n\n\tctx.Logger.Debug().Msg(\"stdin pipe retrieved\")\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get stdout pipe: %w\", err)\n\t}\n\n\tctx.Logger.Debug().Msg(\"stdout pipe retrieved\")\n\n\treturn &mware{\n\t\tcmd: cmd,\n\t\tstdin: stdin,\n\t\tstdout: stdout,\n\t}, nil\n}", "func NewMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif acceptedMethods[r.Method] {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t} else {\n\t\t\tmetrics.RejectedRequestsCount.Inc()\n\t\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\t}\n\t})\n}", "func New(cfg Config, reg prometheus.Registerer) Middleware {\n\t// If no registerer then set the default one.\n\tif reg == nil {\n\t\treg = prometheus.DefaultRegisterer\n\t}\n\n\t// Validate the configuration.\n\tcfg.validate()\n\n\t// Create our middleware with all the configuration options.\n\tm := &middleware{\n\t\thttpRequestHistogram: prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tNamespace: cfg.Prefix,\n\t\t\tSubsystem: \"http\",\n\t\t\tName: \"request_duration_seconds\",\n\t\t\tHelp: \"The latency of the HTTP requests.\",\n\t\t\tBuckets: cfg.Buckets,\n\t\t}, []string{\"handler\", \"method\", \"code\"}),\n\n\t\tcfg: cfg,\n\t\treg: reg,\n\t}\n\n\t// Register all the middleware metrics on prometheus registerer.\n\tm.registerMetrics()\n\n\treturn m\n}", "func NewMiddleware(cfgr config.Configer, b *Buffer) middleware {\n\treturn middleware{\n\t\tConfiger: cfgr,\n\t\tBuffer: b,\n\t}\n}", "func NewMiddleware(gcpProjectID string, logger *zap.Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tt := newTraceFromTraceContext(gcpProjectID, r.Header.Get(\"X-Cloud-Trace-Context\"))\n\t\t\tzapFields := append(\n\t\t\t\tzapdriver.TraceContext(t.TraceID, t.SpanID, true, t.ProjectID),\n\t\t\t\tzap.String(\"ip\", r.Header.Get(\"X-Forwarded-For\")),\n\t\t\t)\n\t\t\tctx := ctxzap.ToContext(r.Context(), logger.With(zapFields...))\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func NewMiddleware(service services.Keys) Middleware {\n\n\treturn &middlewareStruct{\n\t\tservice: service,\n\t}\n}", "func New(next http.Handler, httpsPort int) http.Handler {\n\treturn &forceHTTPSMiddleware{next: next, httpsPort: httpsPort}\n}", "func NewMiddleware(projectFolder *string) *Middleware {\n\treturn &Middleware{\n\t\tprojectFolder: *projectFolder,\n\t}\n}", "func New() iris2.HandlerFunc {\n\tl := &authMiddleware{}\n\treturn l.Serve\n}", "func NewDefault() Middleware {\n\treturn New(Config{}, nil)\n}", "func New(middleware ...Handler) *Server {\n\tdebugPrintWARNINGNew()\n\tserv := &Server{\n\t\trouter: make(tree.Trees, 0, 9),\n\t\tnotFound: []Handler{default404Handler},\n\t\tnoMethod: []Handler{default405Handler},\n\t\tmiddleware: middleware,\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: false,\n\t\tMaxMultipartMemory: defaultMultipartMemory,\n\t}\n\n\tserv.pool.New = func() interface{} {\n\t\treturn serv.allocateContext()\n\t}\n\treturn serv\n}", "func NewMiddleware(creds *secrets.BasicAuthCredentials) es.CommandHandlerMiddleware {\n\treturn func(handler es.CommandHandler) es.CommandHandler {\n\t\treturn es.CommandHandlerFunc(func(ctx context.Context, cmd es.Command) error {\n\t\t\tcur, err := secrets.AuthFromContext(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !creds.Equals(cur) {\n\t\t\t\treturn ErrInvalidCredentials\n\t\t\t}\n\n\t\t\treturn handler.HandleCommand(ctx, cmd)\n\t\t})\n\t}\n}", "func NewMiddleware(router *mux.Router, options ...FuncOption) *Middleware {\n\tm := &Middleware{\n\t\toutput: os.Stdout,\n\t\toptions: Options{\n\t\t\tLogging: true,\n\t\t},\n\t\trouter: router,\n\t}\n\n\tfor _, opt := range options {\n\t\topt(m)\n\t}\n\n\tm.RegisterHook(m.loggingProcessor)\n\treturn m\n}", "func New(config *Config, next http.RoundTripper) http.RoundTripper {\n\t// Need to delay fetching auth settings until env vars have had a chance to propagate\n\tif authSettings == nil {\n\t\tauthSettings = awsds.ReadAuthSettingsFromEnvironmentVariables()\n\t}\n\n\treturn RoundTripperFunc(func(r *http.Request) (*http.Response, error) {\n\t\tif next == nil {\n\t\t\tnext = http.DefaultTransport\n\t\t}\n\t\treturn (&middleware{\n\t\t\tconfig: config,\n\t\t\tnext: next,\n\t\t}).exec(r)\n\t})\n}", "func NewMiddleware(writer Writer, minOutSeverity string) *Middleware {\n\tmos := NewSeverity(minOutSeverity)\n\treturn &Middleware{\n\t\tWriter: writer,\n\t\tMinOutSeverity: mos,\n\t}\n}", "func New(addHeader bool, headerName string) (*BackendHeaderMiddleware, error) {\n\treturn &BackendHeaderMiddleware{AddHeader: addHeader, HeaderName: headerName}, nil\n}", "func New(mws ...Middleware) *Router {\n\tr := &Router{\n\t\tparent: nil,\n\t\thostrm: newHostMatcher(),\n\t\tmiddlewares: Middlewares{},\n\t\tnamedMiddlewares: make(map[string]Middlewares),\n\t\tpool: newCtxPool(),\n\t}\n\tr.Use(mws...)\n\tr.Configure(\n\t\tWithLogger(lionLogger),\n\t\tWithServer(&http.Server{\n\t\t\tReadTimeout: 5 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t}),\n\t)\n\treturn r\n}", "func NewMiddleware(limiter *limiter.Limiter, options ...Option) *Middleware {\n\tmiddleware := &Middleware{\n\t\tLimiter: limiter,\n\t\tOnError: DefaultErrorHandler,\n\t\tOnLimitReached: DefaultLimitReachedHandler,\n\t\tKeyGetter: DefaultKeyGetter(limiter),\n\t\tExcludedKey: nil,\n\t}\n\n\tfor _, option := range options {\n\t\toption.apply(middleware)\n\t}\n\n\treturn middleware\n}", "func NewMiddleware(limiter *limiter.Limiter, options ...Option) gin.HandlerFunc {\n\tmiddleware := &Middleware{\n\t\tLimiter: limiter,\n\t\tOnError: DefaultErrorHandler,\n\t\tOnLimitReached: DefaultLimitReachedHandler,\n\t\tKeyGetter: DefaultKeyGetter,\n\t\tExcludedKey: nil,\n\t}\n\n\tfor _, option := range options {\n\t\toption.apply(middleware)\n\t}\n\n\treturn func(ctx *gin.Context) {\n\t\tmiddleware.Handle(ctx)\n\t}\n}", "func NewMiddleware(opts ...Option) *Middleware {\n\tm := &Middleware{\n\t\tclock: clock.New(),\n\t\tsuidCookieSettings: &http.Cookie{\n\t\t\tName: \"suid\",\n\t\t\tSecure: false, // allow on HTTP.\n\t\t\tHttpOnly: true,\n\t\t\tSameSite: http.SameSiteLaxMode,\n\t\t},\n\t\tduidCookieSettings: &http.Cookie{\n\t\t\tName: \"duid\",\n\t\t\tMaxAge: 60 * 60 * 24 * 180,\n\t\t\tSecure: false, // allow on HTTP.\n\t\t\tHttpOnly: true,\n\t\t\tSameSite: http.SameSiteLaxMode,\n\t\t},\n\t\tusuidCookieSettings: &http.Cookie{\n\t\t\tName: \"usuid\",\n\t\t\tSecure: true, // only allow on HTTPS.\n\t\t\tHttpOnly: true,\n\t\t\tSameSite: http.SameSiteLaxMode,\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.applyTo(m)\n\t}\n\treturn m\n}", "func New() mux.MiddlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func New(opts ...Option) http.Handler {\n\tr := new(router)\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\topt(r)\n\t}\n\n\thttp.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 32\n\n\trt := mux.NewRouter().StrictSlash(true)\n\tfor _, route := range r.routes {\n\t\tfor _, mw := range r.middlewares {\n\t\t\troute.HandlerFunc = mw.Wrap(route.HandlerFunc)\n\t\t}\n\n\t\trt.Handle(route.Pattern,\n\t\t\tr.routing(route.Name, route.Pattern,\n\t\t\t\troute.Methods, route.HandlerFunc)).Name(route.Name)\n\t}\n\n\treturn rt\n}", "func NewMiddleWare(\n\tcustomClaimsFactory CustomClaimsFactory,\n\tvalidFunction CustomClaimsValidateFunction,\n) *Middleware {\n\treturn &Middleware{\n\t\t// todo: customize signing algorithm\n\t\tSigningAlgorithm: \"HS256\",\n\t\tJWTHeaderKey: \"Authorization\",\n\t\tJWTHeaderPrefixWithSplitChar: \"Bearer \",\n\t\tSigningKeyString: GetSignKey(),\n\t\tSigningKey: []byte(GetSignKey()),\n\t\tcustomClaimsFactory: customClaimsFactory,\n\t\tvalidFunction: validFunction,\n\t\t// MaxRefresh: default zero\n\t}\n}", "func New(debug bool) *ErrorMiddleware {\n\treturn &ErrorMiddleware{Debug:debug,GenericError:DefaultGenericError}\n}", "func NewMidlleware(logger *zap.Logger, config dependency.ConfigGetter) mux.MiddlewareFunc {\n\treturn func(handler http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\tfields := []zap.Field{\n\t\t\t\tzap.String(\"method\", r.Method),\n\t\t\t\tzap.String(\"host\", r.Host),\n\t\t\t\tzap.String(\"path\", path(r)),\n\t\t\t\tzap.String(\"protocol\", r.Proto),\n\t\t\t\tzap.Int64(\"request.content-length\", r.ContentLength),\n\t\t\t}\n\t\t\tfields = append(fields, requestHeaders(r, config.GetStringSlice(\"excluded-headers\"))...)\n\t\t\tfields = append(fields, queryParams(r)...)\n\t\t\tresponseLogger := NewResponseLogger(rw)\n\t\t\thandler.ServeHTTP(responseLogger, r)\n\t\t\tfields = append(fields, zap.Int(\"status-code\", responseLogger.Status))\n\t\t\tfields = append(fields, responseHeaders(responseLogger.Header())...)\n\t\t\tlogger.Info(\"request log\", fields...)\n\t\t})\n\t}\n}", "func NewMiddleware(appStoreRepo repo.AppStoreRepo,\n\trkeClusterRepo repo.RKEClusterRepository,\n\tcustomClusterRepo repo.CustomClusterRepository) *Middleware {\n\treturn &Middleware{\n\t\tappStoreRepo: appStoreRepo,\n\t\trkeClusterRepo: rkeClusterRepo,\n\t\tcustomClusterRepo: customClusterRepo,\n\t}\n}", "func New(opt ...session.Option) echo.MiddlewareFunc {\n\treturn NewWithConfig(DefaultConfig, opt...)\n}", "func New(h handlers.Handler, l *zap.SugaredLogger) Router {\n\tr := chi.NewRouter()\n\n\tr.Mount(\"/\", newIndexRouter(h))\n\n\tr.NotFound(h.NotFound)\n\tr.MethodNotAllowed(h.MethodNotAllowed)\n\n\trouter := &router{\n\t\tHandler: r,\n\t\tlogger: l,\n\t}\n\n\trouter.Handler = middleware.Log(router.Handler, router.logger)\n\n\treturn router\n}", "func newTracingMiddleware(tracer opentracing.Tracer) linkManagerMiddleware {\n\treturn func(next om.LinkManager) om.LinkManager {\n\t\treturn tracingMiddleware{next, tracer}\n\t}\n}", "func New(config ...Config) fiber.Handler {\n\t// Set default config\n\tcfg = configDefault(config...)\n\n\t// Return new handler\n\treturn func(c *fiber.Ctx) error {\n\t\t// Don't execute middleware if Next returns true\n\t\tif cfg.Next != nil && cfg.Next(c) {\n\t\t\treturn c.Next()\n\t\t}\n\n\t\t// validate request before continuing to next handler\n\t\tok, err := validateRequest(c)\n\t\tif !ok {\n\t\t\treturn fiber.NewError(fiber.StatusForbidden, err.Error())\n\t\t}\n\n\t\t// Continue stack\n\t\treturn c.Next()\n\t}\n}", "func New(ctx context.Context, next http.Handler, config dynamic.Headers, name string) (http.Handler, error) {\n\t// HeaderMiddleware -> SecureMiddleWare -> next\n\tlogger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))\n\tlogger.Debug(\"Creating middleware\")\n\n\thasSecureHeaders := config.HasSecureHeadersDefined()\n\thasCustomHeaders := config.HasCustomHeadersDefined()\n\thasCorsHeaders := config.HasCorsHeadersDefined()\n\n\tif !hasSecureHeaders && !hasCustomHeaders && !hasCorsHeaders {\n\t\treturn nil, errors.New(\"headers configuration not valid\")\n\t}\n\n\tvar handler http.Handler\n\tnextHandler := next\n\n\tif hasSecureHeaders {\n\t\tlogger.Debug(\"Setting up secureHeaders from %v\", config)\n\t\thandler = newSecure(next, config)\n\t\tnextHandler = handler\n\t}\n\n\tif hasCustomHeaders || hasCorsHeaders {\n\t\tlogger.Debug(\"Setting up customHeaders/Cors from %v\", config)\n\t\thandler = NewHeader(nextHandler, config)\n\t}\n\n\treturn &headers{\n\t\thandler: handler,\n\t\tname: name,\n\t}, nil\n}", "func NewTraceMiddleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn traceMiddleware(next)\n\t}\n}", "func NewAPIMiddleware(handler http.Handler) *APIMiddleware {\n\treturn &APIMiddleware{handler: handler}\n}", "func New(middleware []Middleware) ApiService {\n\tvar svc ApiService = NewBasicApiService()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func New(cfg *config.Config, cache cache.Cacher, tr *http.Transport) *HttpHandler {\n\treturn &HttpHandler{handler.Handler{cache, cfg, tr}}\n}", "func New() *web.Mux {\n\tmux := web.New()\n\tmux.Get(\"/api/hello\", handler.HelloWorld)\n\tmux.Get(\"/api/hello/:name\", handler.HelloName)\n\treturn mux\n}", "func newCorsMiddleware() func(http.Handler) http.Handler {\n\treturn cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"OPTIONS\", \"HEAD\"},\n\t\tAllowedHeaders: []string{\"Authorization\", \"X-Auth-Key\", \"X-Auth-Secret\", \"Content-Type\", \"X-Requested-With\"},\n\t\t// Debug: true,\n\t}).Handler\n}", "func New(options ...Options) *JWTMiddleware {\n\n\tvar opts Options\n\tif len(options) == 0 {\n\t\topts = Options{}\n\t} else {\n\t\topts = options[0]\n\t}\n\n\tif opts.UserProperty == \"\" {\n\t\topts.UserProperty = \"user\"\n\t}\n\n\tif opts.ErrorHandler == nil {\n\t\topts.ErrorHandler = OnError\n\t}\n\n\tif opts.Extractor == nil {\n\t\topts.Extractor = FromAuthHeader\n\t}\n\tif opts.Store == nil {\n\t\tdefaultStore, _ := NewBadgerDBStore(\".\")\n\t\topts.Store = defaultStore\n\t}\n\treturn &JWTMiddleware{\n\t\tOptions: opts,\n\t}\n}", "func New() *Router {\n\treturn &Router{\n\t\troutes: make(map[route]http.Handler),\n\t}\n}", "func (l *Logger) Middleware(next http.Handler) http.Handler {\n\treturn httpHandler{\n\t\tlogger: l,\n\t\tnext: next,\n\t}\n}", "func Middleware(option BasicAuthOption) *BasicAuthMiddleware {\n\treturn &BasicAuthMiddleware{option: option}\n}", "func Middleware(next http.Handler) http.Handler {\n\t// requests that go through it.\n\treturn nethttp.Middleware(opentracing.GlobalTracer(),\n\t\tnext,\n\t\tnethttp.OperationNameFunc(func(r *http.Request) string {\n\t\t\treturn \"HTTP \" + r.Method + \" \" + r.URL.String()\n\t\t}))\n}", "func New(middlewares ...Middleware) Chain {\n\treturn Chain(middlewares)\n}", "func NewRouter() *mux.Router {\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\trouter.Use(CommonMiddleWare)\n\n\tfor _, route := range routes {\n\t\tvar handler http.Handler\n\t\tlog.Println(route.Name)\n\t\thandler = route.HandlerFunc\n\n\t\trouter.\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(handler)\n\t}\n\treturn router\n}", "func New() *Mux {\n\tm := &Mux{\n\t\tRedirectWWW: false,\n\t\tFileHandler: fileHandler,\n\t\tErrorHandler: errHandler,\n\t\tcache: make(map[string]Route, MaxCacheEntries),\n\t}\n\n\treturn m\n}", "func NewRouter() *mux.Router {\n\tr := mux.NewRouter().StrictSlash(true)\n\n\tr.PathPrefix(staticDir).Handler(http.StripPrefix(staticDir, http.FileServer(http.Dir(\".\"+staticDir))))\n\tr.Methods(\"GET\").Path(\"/health\").Name(\"Health\").Handler(Health())\n\tr.Use(Middleware)\n\n\treturn r\n}", "func New() (*Router, error) {\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/ping\", generichandler.NewPingPongHandler())\n\tmux.Handle(\"/\", http.NotFoundHandler())\n\treturn &Router{mux}, nil\n}", "func New(mws ...MiddlewareFunc) *http.Client {\n\tclient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t\tTransport: http.DefaultTransport,\n\t}\n\twithMiddleware(client, mws...)\n\treturn client\n}", "func New(s *service.Service) http.Handler {\n\th := handler{s}\n\tapi := way.NewRouter()\n\tapi.HandleFunc(\"POST\", \"/\", h.twillioHandler)\n\tapi.HandleFunc(\"POST\", \"/passcodes\", h.generatePasswords)\n\tapi.HandleFunc(\"GET\", \"/passcodes\", h.getPasscodes)\n\t// api.HandleFunc(\"POST\", \"/passcode/validate\", h.validatePasscode)\n\treturn api\n}", "func NewHTTP(opts HTTPOptions, mux FuncHandler) *HTTP {\n\taddr := opts.Addr.String()\n\terrorLogger := log.New(loggerFromExternalLogger{Print: opts.Loggers.ServerEvent}, \"\", 0)\n\n\tif !opts.Disable.LivenessProbe {\n\t\terrorLogger.Print(\"liveness probe is ENABLED\")\n\t\tmux.HandleFunc(opts.LivenessProbe.Path, handlers.GetHTTPReadinessProbe(opts.ReadinessProbe.Handlers))\n\t}\n\n\tif !opts.Disable.ReadinessProbe {\n\t\terrorLogger.Print(\"readiness probe is ENABLED\")\n\t\tmux.HandleFunc(opts.ReadinessProbe.Path, handlers.GetHTTPLivenessProbe(opts.ReadinessProbe.Handlers))\n\t}\n\n\tif !opts.Disable.Metrics {\n\t\terrorLogger.Print(\"metrics is ENABLED\")\n\t\tmux.HandleFunc(opts.Metrics.Path, handlers.GetHTTPMetrics())\n\t}\n\n\tif !opts.Disable.Version {\n\t\terrorLogger.Print(\"version is ENABLED\")\n\t\tmux.HandleFunc(opts.Version.Path, handlers.GetHTTPVersion(opts.Version.Value))\n\t}\n\n\thandler := http.Handler(mux)\n\n\tmiddlewares := middleware.Middlewares{}\n\tif opts.Middlewares != nil && len(opts.Middlewares) > 0 {\n\t\tmiddlewares = append(middlewares, opts.Middlewares...)\n\t}\n\tif !opts.Disable.CORS {\n\t\terrorLogger.Print(\"cross-origin resource sharing is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewCORS(opts.CORS))\n\t}\n\tif !opts.Disable.RequestLogger {\n\t\terrorLogger.Print(\"request logging is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewRequestLogger(middleware.RequestLoggerConfiguration{Log: opts.Loggers.Request}))\n\t}\n\tif !opts.Disable.RequestIdentifier {\n\t\terrorLogger.Print(\"request identification is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewRequestIdentifier(middleware.RequestIdentifierConfiguration{}))\n\t}\n\tfor i := 0; i < len(middlewares); i++ {\n\t\tapply := middlewares[i]\n\t\thandler = apply(handler)\n\t}\n\ts := HTTP{\n\t\tOptions: &opts,\n\t\tServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: handler,\n\t\t\tErrorLog: errorLogger,\n\t\t\tIdleTimeout: opts.Timeouts.Idle,\n\t\t\tMaxHeaderBytes: opts.Limit.HeaderBytes,\n\t\t\tReadTimeout: opts.Timeouts.Read,\n\t\t\tReadHeaderTimeout: opts.Timeouts.ReadHeader,\n\t\t\tWriteTimeout: opts.Timeouts.Write,\n\t\t},\n\t}\n\treturn &s\n}", "func NewBasic(config Config, log logr.Logger) http.HandlerFunc {\n\treturn basic(config, log)\n}", "func New(this *Handler) *Handler {\n\ta := &API{Cfg: this.Cfg, Interactor: this.Interactor}\n\troutes(a).Register()\n\treturn this\n}", "func New(config *Settings, api *web.API) *Server {\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\tfor _, controller := range api.Controllers {\n\t\tfor _, route := range controller.Routes() {\n\t\t\tfor _, filter := range api.Filters {\n\t\t\t\tif matches(filter, route.Endpoint) {\n\t\t\t\t\troute.Handler = attachFilter(route.Handler, filter)\n\t\t\t\t}\n\t\t\t}\n\t\t\trouter.HandleFunc(route.Endpoint.Path, route.Handler).Methods(route.Endpoint.Method)\n\t\t}\n\t}\n\n\treturn &Server{\n\t\tRouter: router,\n\t\tConfig: config,\n\t}\n}", "func Middleware(\n\tenv *Env,\n) func(http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn middleware{h, env}\n\t}\n}", "func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {\n\treturn func(handle http.HandlerFunc) http.HandlerFunc {\n\t\treturn handler(handle).ServeHTTP\n\t}\n}", "func New() *Router {\n\treturn &Router{\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: true,\n\t\tHandleMethodNotAllowed: true,\n\t\tHandleOPTIONS: true,\n\t}\n}", "func New(middleware []Middleware) AddService {\n\tvar svc AddService = NewBasicAddService()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func (s *AppServer) new(w http.ResponseWriter, r *http.Request, params *AppParams, handlers []Middleware) *Context {\n\t// adjust request id\n\trequestId := r.Header.Get(s.requestId)\n\tif requestId == \"\" {\n\t\trequestId = NewObjectId().Hex()\n\n\t\t// inject request header with new request id\n\t\tr.Header.Set(s.requestId, requestId)\n\t}\n\tw.Header().Set(s.requestId, requestId)\n\n\tctx := s.pool.Get().(*Context)\n\tctx.Request = r\n\tctx.Response = &ctx.writer\n\tctx.Params = params\n\tctx.Logger = s.logger.New(requestId)\n\tctx.settings = nil\n\tctx.frozenSettings = nil\n\tctx.writer.reset(w)\n\tctx.handlers = handlers\n\tctx.index = -1\n\tctx.startedAt = time.Now()\n\tctx.downAfter = ctx.startedAt.Add(s.slowdown)\n\n\treturn ctx\n}", "func New() Server {\n\trouter := chi.NewRouter()\n\n\trouter.Use(middleware.Timeout(3 * time.Second))\n\trouter.Use(middleware.Logger)\n\trouter.Use(middleware.Recoverer)\n\trouter.Use(middleware.RealIP)\n\trouter.Use(middleware.RequestID)\n\trouter.Use(middleware.Throttle(1000))\n\trouter.Use(middleware.NoCache)\n\trouter.Use(middleware.SetHeader(\"Content-Type\", \"application/json\"))\n\n\treturn &server{Router: router}\n}", "func New(logger *zap.Logger) *HTTP {\n\th := &HTTP{\n\t\tlogger: logger,\n\t\tcreateClientFunc: createHTTPClient,\n\t}\n\n\treturn h\n}", "func New(authenticator auth.Authenticator) clevergo.MiddlewareFunc {\n\treturn func(next clevergo.Handle) clevergo.Handle {\n\t\treturn func(c *clevergo.Context) error {\n\t\t\tidentity, err := authenticator.Authenticate(c.Request, c.Response)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tauthenticator.Challenge(c.Request, c.Response)\n\t\t\t} else {\n\t\t\t\tc.WithValue(auth.IdentityKey, identity)\n\t\t\t}\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func Middleware(t *elasticapm.Tracer) mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn &apmhttp.Handler{\n\t\t\tHandler: h,\n\t\t\tRecovery: apmhttp.NewTraceRecovery(t),\n\t\t\tRequestName: routeRequestName,\n\t\t\tTracer: t,\n\t\t}\n\t}\n}", "func New(h HandlerFunc) lambda.Handler {\n\treturn NewWithConfig(Config{}, h)\n}", "func newRouter() *mux.Router {\n r := mux.NewRouter()\n r.HandleFunc(\"/api/v1/hello\", handlerHello).Methods(\"GET\")\n r.HandleFunc(\"/ws-echo\", handlerWS)\n return r\n}", "func newHTTPHandler(\n\tusePrometheus, usePProf bool,\n\treg *prometheus.Registry,\n) *httpHandler {\n\tmux := http.NewServeMux()\n\n\th := &httpHandler{\n\t\th: mux,\n\t}\n\n\t// Optionally enable Prometheus and pprof support.\n\tif usePrometheus {\n\t\tmux.Handle(\"/metrics\", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))\n\t}\n\n\tif usePProf {\n\t\tmux.HandleFunc(\"/debug/pprof/\", pprof.Index)\n\t\tmux.HandleFunc(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\t\tmux.HandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\t\tmux.HandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\t\tmux.HandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n\t}\n\n\treturn h\n}", "func Default() Middleware {\n\treturn defaultMiddleware\n}", "func New(sigs chan os.Signal) *Server {\n\ts := &Server{mux: http.NewServeMux(), sigs: sigs}\n\n\tif s.logger == nil {\n\t\ts.logger = log.New(os.Stdout, \"\", 0)\n\t}\n\n\ts.db = store.NewStore()\n\n\ts.mux.HandleFunc(\"/\", s.latencyMiddleware(s.index))\n\ts.mux.HandleFunc(\"/hash/\", s.latencyMiddleware(s.hash))\n\ts.mux.HandleFunc(\"/shutdown/\", s.latencyMiddleware(s.shutdown))\n\ts.mux.HandleFunc(\"/stats/\", s.stats)\n\n\treturn s\n}", "func New(handler http.Handler) *Request {\n\tapiTest := &APITest{}\n\n\trequest := &Request{apiTest: apiTest}\n\tresponse := &Response{apiTest: apiTest}\n\tapiTest.request = request\n\tapiTest.response = response\n\tapiTest.handler = handler\n\n\treturn apiTest.request\n}", "func ToMiddleware(classicMiddleware func(http.HandlerFunc) http.HandlerFunc) Middleware {\n\treturn func(c Container, next Handler) {\n\t\tclassicMiddleware(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tnext(c)\n\t\t})(c.GetResponseWriter(), c.GetRequest())\n\t}\n}", "func New() *Server {\n\tws := &Server{}\n\tws.controls = make([]control.Control, 0)\n\tws.middleware = make([]middle.Handler, 0)\n\tws.staticFiles = make(map[string]string)\n\tws.router = mux.NewRouter()\n\n\thttp.Handle(\"/\", ws.router)\n\treturn ws\n}", "func NewBasicAuthMiddleware() goa.Middleware {\n\treturn func(h goa.Handler) goa.Handler {\n\t\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\t\t// Retrieve and log basic auth info\n\t\t\tuser, pass, ok := req.BasicAuth()\n\t\t\t// A real app would do something more interesting here\n\t\t\tif !ok {\n\t\t\t\tgoa.LogInfo(ctx, \"failed basic auth\")\n\t\t\t\treturn ErrUnauthorized(\"missing auth\")\n\t\t\t}\n\n\t\t\t// Proceed\n\t\t\tgoa.LogInfo(ctx, \"basic\", \"user\", user, \"pass\", pass)\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t}\n}", "func Middleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func NewMiddlewareWrapper(logger Logger, metrics Metrics, corsOptions *CORSOptions, globals ServiceGlobals) MiddlewareWrapper {\n\tm := &middlewareWrapperImpl{\n\t\tlogger: logger,\n\t\tmetrics: metrics,\n\t\tglobals: globals,\n\t}\n\tm.corsOptions = m.mergeCORSOptions(corsOptions)\n\treturn m\n}", "func New() *Handler {\n\tp := &Handler{}\n\tp.reverseProxy = &httputil.ReverseProxy{\n\t\tTransport: &http.Transport{\n\t\t\tDial: func(network, address string) (net.Conn, error) {\n\t\t\t\treturn p.dial(context.TODO(), address)\n\t\t\t},\n\t\t},\n\t\tDirector: func(*http.Request) {\n\t\t\t// Do nothing, the request is self-sufficient\n\t\t},\n\t}\n\treturn p\n}", "func NewMiddlewareContext(writer http.ResponseWriter, request *http.Request) *MiddlewareContext {\n\tcontext := &MiddlewareContext{Request: request, ResponceWriter: writer}\n\n\treturn context\n}", "func New() *Router {\n\treturn NewMux(muxCreator{})\n}", "func New(sto store.Service) *server {\n\ts := &server{sto: sto}\n\n\trouter := mux.NewRouter()\n\n\trouter.Handle(\"/todo\", allowedMethods(\n\t\t[]string{\"OPTIONS\", \"GET\", \"POST\"},\n\t\thandlers.MethodHandler{\n\t\t\t\"GET\": http.HandlerFunc(s.getTodos),\n\t\t\t\"POST\": http.HandlerFunc(s.createTodo),\n\t\t}))\n\n\trouter.Handle(\"/todo/{id}\", idMiddleware(allowedMethods(\n\t\t[]string{\"OPTIONS\", \"GET\", \"PUT\", \"PATCH\", \"DELETE\"},\n\t\thandlers.MethodHandler{\n\t\t\t\"GET\": http.HandlerFunc(s.getTodo),\n\t\t\t\"PUT\": http.HandlerFunc(s.putTodo),\n\t\t\t\"PATCH\": http.HandlerFunc(s.patchTodo),\n\t\t\t\"DELETE\": http.HandlerFunc(s.deleteTodo),\n\t\t})))\n\n\ts.handler = limitBody(defaultHeaders(router))\n\n\treturn s\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}", "func setupGlobalMiddleware(handler http.Handler) http.Handler {\n\treturn handler\n}" ]
[ "0.7941445", "0.7738533", "0.7497486", "0.73819786", "0.737548", "0.7353219", "0.72677", "0.7236142", "0.7231312", "0.71885943", "0.7128706", "0.7123077", "0.711678", "0.71036077", "0.71036077", "0.70856845", "0.70026326", "0.69975793", "0.6988252", "0.69750315", "0.6922467", "0.69151264", "0.6881805", "0.68805313", "0.6848419", "0.6840707", "0.6773401", "0.6760449", "0.6744403", "0.67369", "0.67264944", "0.670277", "0.66621906", "0.66312915", "0.6614165", "0.660956", "0.65909404", "0.6575845", "0.64797264", "0.6476307", "0.6473418", "0.6387824", "0.63693106", "0.6234574", "0.62322414", "0.62276644", "0.6157172", "0.61548334", "0.6149008", "0.6138877", "0.61244696", "0.6118399", "0.6057105", "0.6033351", "0.60220337", "0.60145736", "0.5990547", "0.59734184", "0.5946888", "0.5909745", "0.5901891", "0.58905154", "0.58880836", "0.5879073", "0.5876206", "0.5875254", "0.586138", "0.5842401", "0.582709", "0.5821483", "0.58189774", "0.5817166", "0.58122396", "0.5808342", "0.5798288", "0.5794047", "0.57924086", "0.5783269", "0.57547617", "0.5753336", "0.57478154", "0.5739455", "0.5733717", "0.5718668", "0.57064116", "0.5705183", "0.570008", "0.56972104", "0.5688685", "0.56856024", "0.5681184", "0.5679382", "0.5668539", "0.5665922", "0.5665462", "0.5665462", "0.5665462", "0.5665462", "0.5665462", "0.5665462" ]
0.7177547
10
Handler handles a HTTP request.
func (middleware *Middleware) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key, err := middleware.GetID(r) if err != nil { middleware.OnIDError(w, r, err) return } lr, err := middleware.Limiter.RecordRequest(r.Context(), key) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(lr.Limit, 10)) w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(lr.Remaining, 10)) w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(lr.SecondsRemaining(), 10)) if lr.LimitReached { w.WriteHeader(http.StatusTooManyRequests) return } h.ServeHTTP(w, r) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Route) HTTPHandler(ctx *Context, done Next) {\n\tthis.dispatch(ctx, done)\n}", "func handle(req typhon.Request, service, path string) typhon.Response {\n\turl := fmt.Sprintf(requestFormat, service, path)\n\n\tslog.Trace(req, \"Handling parsed URL: %v\", url)\n\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:80\", service))\n\tif err != nil {\n\t\tslog.Error(req, \"Unable to connect to %s: %v\", service, err)\n\t\treturn typhon.Response{Error: terrors.NotFound(\"service\", fmt.Sprintf(\"Unable to connect to %v\", service), nil)}\n\t}\n\tdefer conn.Close()\n\n\treq.Host = service\n\treq.URL.Scheme = \"http\"\n\treq.URL.Path = \"/\" + strings.TrimPrefix(path, \"/\")\n\treq.URL.Host = service\n\n\treturn req.Send().Response()\n}", "func (res *Resource) HandleRequest(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodGet && r.Method != http.MethodHead {\n\t\thandleMethodNotAllowed(w, r)\n\t\treturn\n\t}\n\n\treader := bytes.NewReader(res.Content)\n\thttp.ServeContent(w, r, res.FileName, res.ModTime, reader)\n}", "func HttpHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:])\n\tlog.Printf(\"handling... %s\", r.URL.Path[1:])\n}", "func handleRequest(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\thandleGetRequest(w, r)\n\t\treturn\n\tcase \"POST\":\n\t\thandlePost(w, r)\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\tw.Write([]byte(\"HTTP methos not allowed.\"))\n\t\treturn\n\t}\n}", "func (h *Handler) handleRequest(w http.ResponseWriter, r *http.Request) {\n\tmethod := r.Method\n\th.handleCommon(w, r, method)\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\thandler.Submit(w, r)\n}", "func httpHandler(w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\treq := json.GetRPCRequestFromJSON(string(b))\n\trespBody, statusCode := handler(req)\n\tw.WriteHeader(statusCode)\n\tw.Write([]byte(respBody))\n}", "func (p *Server) handle(resp *http.Response) {\n\n\tdefer resp.Body.Close()\n\n\treqId := resp.Header.Get(\"Reqid\")\n\tif reqId == \"\" {\n\t\tlog.Warn(\"unidisvr: Reqid not found\")\n\t\treturn\n\t}\n\n\tb := bufio.NewReader(resp.Body)\n\treq, err := http.ReadRequest(b)\n\tif err != nil {\n\t\tlog.Warn(\"unidisvr: ReadRequest failed -\", p.Addr, p.BaseUrl, err)\n\t\treturn\n\t}\n\n\tw := newResponseWriter(p.BaseUrl, reqId)\n\tp.Handler.ServeHTTP(w, req)\n\terr = w.Done()\n\tif err != nil {\n\t\tlog.Warn(\"unidisvr: ServeHTTP failed -\", p.Addr, p.BaseUrl, err)\n\t}\n}", "func (c *Client) HandleRequest(req *http.Request) (res *http.Response, err error) {\n\treq.URL.Path = \"/api/v\" + c.APIVersion + req.URL.Path\n\n\t// Fill out Host and Scheme if it is empty\n\tif req.URL.Host == \"\" {\n\t\treq.URL.Host = c.URLHost\n\t}\n\tif req.URL.Scheme == \"\" {\n\t\treq.URL.Scheme = c.URLScheme\n\t}\n\tif req.Header.Get(\"User-Agent\") == \"\" {\n\t\treq.Header.Set(\"User-Agent\", c.UserAgent)\n\t}\n\tif req.Header.Get(\"Authorization\") == \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bot \"+c.Token)\n\t}\n\n\tres, err = c.HTTP.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\terr = errors.New(\"Invalid token passed\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (p *stats) Handles(req *comm.Request) (res bool) {\n\treturn\n}", "func handleHTTPRequest(mux *http.ServeMux, url string, handler http.HandlerFunc) {\n\tmux.HandleFunc(url, func(w http.ResponseWriter, req *http.Request) {\n\t\thandler(w, req)\n\t})\n}", "func handleRequest(request *http.Request, t http.RoundTripper) (rsp *http.Response) {\n\tvar err error\n\n\tif rsp, err = t.RoundTrip(request); err != nil {\n\t\tlog.Println(\"Request failed:\", err)\n\t}\n\n\treturn\n}", "func (h HTTPHandlerFunc) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn h(c, fc)\n}", "func (p Service) Handler(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tif strings.HasSuffix(r.URL.Path, \"/login\") {\n\t\tp.loginHandler(w, r)\n\t\treturn\n\t}\n\tif strings.HasSuffix(r.URL.Path, \"/callback\") {\n\t\tp.authHandler(w, r)\n\t\treturn\n\t}\n\tif strings.HasSuffix(r.URL.Path, \"/logout\") {\n\t\tp.LogoutHandler(w, r)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusNotFound)\n}", "func (h *EventHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) {\n\tchannelKey := request.Host\n\n\tif request.URL.Path != \"/\" {\n\t\tchannelRef, err := channel.ParseChannelFromPath(request.URL.Path)\n\t\tif err != nil {\n\t\t\th.logger.Error(\"unable to retrieve channel from path\")\n\t\t\tresponse.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tchannelKey = fmt.Sprintf(\"%s/%s\", channelRef.Namespace, channelRef.Name)\n\t}\n\n\tfh := h.GetChannelHandler(channelKey)\n\tif fh == nil {\n\t\th.logger.Info(\"Unable to find a handler for request\", zap.String(\"channelKey\", channelKey))\n\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfh.ServeHTTP(response, request)\n}", "func (s *AppServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.logger.Debugf(`processing %s \"%s\"`, r.Method, s.filterParameters(r.URL))\n\n\t// rate limit\n\tif s.throttle != nil {\n\t\t<-s.throttle.C\n\t}\n\n\ts.handler.ServeHTTP(w, r)\n}", "func Handler(w http.ResponseWriter, r *http.Request, pd utils.Parameters) (template.HTML, bool) {\n\tsplitURL := strings.Split(r.URL.Path, \"/\")\n\tif len(splitURL) < 4 {\n\t\treturn pathTTemplate(w, r, pd)\n\t}\n\tif splitURL[4] == \"noop\" {\n\t\treturn template.HTML(\"NOOP\"), false\n\t}\n\tvar inputs string\n\tswitch splitURL[2] {\n\tcase \"body\":\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn template.HTML(err.Error()), false\n\t\t}\n\t\t//the request body should only have the user input\n\t\tinputs, err = url.QueryUnescape(string(b)) //Couldn't find whether POST request inputs get sanitizied ALWAYS.\n\t\tsplitInput := strings.Split(inputs, \"input=\")\n\t\tinputs = splitInput[1]\n\t\tif err != nil {\n\t\t\treturn template.HTML(err.Error()), false\n\t\t}\n\tcase \"headers\":\n\t\tinputs = r.Header[\"Input\"][0]\n\tcase \"query\":\n\t\tinputs = r.URL.Query().Get(\"input\")\n\tdefault:\n\t\treturn template.HTML(\"INVALID URL\"), false\n\t}\n\tswitch splitURL[3] {\n\tcase \"ioutil.ReadFile\":\n\t\treturn readFileHandler(w, r, splitURL[4], inputs)\n\tcase \"ioutil.WriteFile\":\n\t\treturn writeFileHandler(w, r, splitURL[4], inputs)\n\tdefault: //should be an error instead\n\t\treturn template.HTML(\"INVALID URL\"), false\n\t}\n}", "func Handle(c Checker, pattern string, h http.Handler) {\n\thttp.Handle(pattern, NewHandler(c, h))\n}", "func handlerICon(w http.ResponseWriter, r *http.Request) {}", "func (a Application) Handler(event json.RawMessage, ctx *apex.Context) (interface{}, error) {\n\tlog.Println(string(event))\n\treq, err := ParseRequest(a.ID, bytes.NewReader(event))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := NewResponse()\n\n\tswitch req.Type() {\n\tcase \"LaunchRequest\":\n\t\tif a.LaunchHandler != nil {\n\t\t\ta.LaunchHandler(req, res)\n\t\t}\n\tcase \"IntentRequest\":\n\t\tif a.IntentHandler != nil {\n\t\t\ta.IntentHandler(req, res)\n\t\t}\n\tcase \"SessionEndedRequest\":\n\t\tif a.SessionEndedHandler != nil {\n\t\t\ta.SessionEndedHandler(req, res)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"invalid request type\")\n\t}\n\n\treturn res, nil\n}", "func requestHandler(res http.ResponseWriter, req *http.Request) {\n\n\t// Configure CORS setting\n\tutilities.ConfigureCors(&res)\n\n\t// configure logging\n\tlogger := lg.CreateLogger()\n\n\t// dependency inject firestore client\n\tfsc := fs.GetClient()\n\n\tvar user string\n\n\t// extract query parameters\n\tquery := req.URL.Query()\n\tparamCount := len(req.URL.Query())\n\n\tteam := query[\"team\"][0]\n\tif paramCount > 1 {\n\t\tuser = query[\"user\"][0]\n\t}\n\n\t// switch logic via HTTP request verb\n\tswitch req.Method {\n\tcase \"GET\":\n\t\tif paramCount == 1 {\n\t\t\tscore := TeamSentiment(team, fsc)\n\t\t\ttmp := fmt.Sprintf(\"%.4f\", score)\n\t\t\tfmt.Fprint(res, fmt.Sprintf(tmp))\n\t\t} else {\n\t\t\tscore := IndividualSentiment(team, user, fsc)\n\t\t\ttmp := fmt.Sprintf(\"%.4f\", score)\n\t\t\tfmt.Fprint(res, fmt.Sprintf(tmp))\n\t\t}\n\tcase \"OPTIONS\":\n\t\treturn\n\tdefault:\n\t\tres.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprint(res, \"Unknown API endpoint\")\n\t\terr := fmt.Errorf(\"method %s for %s not supported\", req.Method, req.URL)\n\t\tlogger.Infof(\"sentiment API error: %v\", err.Error())\n\t}\n}", "func RequestHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tvar page []byte\n\tvar err error\n\tfmt.Println(\"loading\", r.URL.Path)\n\tif r.URL.Path != \"/\" {\n\t\tpath := strings.TrimLeft(r.URL.Path, \"/\")\n\t\tpage, err = ioutil.ReadFile(path)\n\t} else {\n\t\tpage, err = ioutil.ReadFile(\"view-browser.html\")\n\t}\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Write(page)\n}", "func (h LogHandler) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn logHandle(HTTPHandlerFunc(h), c, fc)\n}", "func (host *Host) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif host.ErrorHandler == nil {\n\t\thost.ErrorHandler = func(err error) interface{} {\n\t\t\treturn err.Error()\n\t\t}\n\t}\n\tif r.Body != nil {\n\t\tdefer r.Body.Close()\n\t}\n\tcollection := host.handlers[strings.ToUpper(r.Method)]\n\tif collection == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(http.StatusText(http.StatusNotFound)))\n\t\treturn\n\t}\n\tpath := r.URL.Path\n\tif host.conf.UserLowerLetter {\n\t\tpath = strings.ToLower(path)\n\t}\n\thandler, args := collection.Search(r.URL.Path)\n\tif handler == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tw.Write([]byte(http.StatusText(http.StatusNotFound)))\n\t\treturn\n\t}\n\tctx := &Context{\n\t\tw: w,\n\t\tr: r,\n\t\tDeserializer: Serializers[strings.Split(r.Header.Get(\"Content-Type\"), \";\")[0]],\n\t\terrorCollector: host.ErrorHandler,\n\t}\n\thandler.(httpHandler)(ctx, args...)\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\trequest := &Request{id: atomic.AddUint64(&counter, 1), response: w, request: req}\n\n\trequests <- request\n\n\tfor {\n\t\tselect {\n\t\tcase result := <-results:\n\t\t\tlogger.Println(result)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Core) handleRequest(fctx *fasthttp.RequestCtx) {\n\tctx := c.assignCtx(fctx)\n\tdefer c.releaseCtx(ctx)\n\tif ctx.methodINT == -1 {\n\t\tctx.Status(StatusBadRequest).SendString(\"Invalid http method\")\n\t\treturn\n\t}\n\n\tstart := time.Now()\n\t// Delegate next to handle the request\n\t// Find match in stack\n\tmatch, err := c.next(ctx)\n\tif err != nil {\n\t\t_ = ctx.SendStatus(StatusInternalServerError)\n\t}\n\t// Generate ETag if enabled\n\tif match && c.ETag {\n\t\tsetETag(ctx, false)\n\t}\n\tif c.Debug {\n\t\td := time.Since(start)\n\t\t// d := time.Now().Sub(start).String()\n\t\tLog.D(\"%s %s %d %s\\n\", ctx.method, ctx.path, ctx.Response.StatusCode(), d)\n\t}\n}", "func (network *Network) HTTPhandler(w http.ResponseWriter, r *http.Request){\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tbody, error := ioutil.ReadAll(r.Body) // Read Request\n\t\tdefer r.Body.Close() // Always CLOSE.\n\t\t// Check for errors or if body is empty.\n\t\tif error != nil || removeQuotationMarks(string(body)) == \"\" {\n\t\t\thttp.Error(w, \"ERROR\", http.StatusBadRequest)\n\t\t\tfmt.Println(\"Error when POST\")\n\t\t} else{\n\t\t\t// Same as in Cli.go Store\n\t\t\thashedFileString := NewKademliaIDFromData(string(body))\n\t\t\tnetwork.Store([]byte(body),hashedFileString)\n\t\t\thashSuffix := hashedFileString.String()\n\n\t\t\tmessage := map[string]string{ hashSuffix: string(body)} // JSON DATA FORMAT\n\t\t\tjsonValue,_ := json.Marshal(message)\n\n\t\t\tw.Header().Set(\"Location\", URLprefix+hashSuffix)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusCreated)\t// Status 201 as detailed\n\n\t\t\tw.Write(jsonValue)\n\t\t\tfmt.Println(\"HTTP Data Written. Hash = \", hashSuffix )\n\t\t}\n\tcase \"GET\":\n\t\t// Checks if there is something after the prefix. /objects/XXXXXXXXXXXXXX\n\t\tURLcomponents := strings.Split(r.URL.Path, \"/\")\t// [ \"\", \"objects\", \"hash\" ]\n\t\thashValue := URLcomponents[2]\n\t\t// Check if there is a hashvalue of correct size.\n\t\tif(len(hashValue) != 40){\n\t\t\thttp.Error(w, \"ERROR\", http.StatusLengthRequired)\n\t\t\tfmt.Println(\"Error when GET \", hashValue, \" is not of correct length. (40)\")\n\t\t}else{\n\t\t\t\t// Same as in Cli.go Get\n\t\t\t\thash := NewKademliaID(hashValue)\n\t\t\t\tdata, nodes := network.DataLookup(hash)\n\t\t\t\tif data != nil {\n\t\t\t\t\t// If data is not nil, send OK status and write.\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(data)\n\t\t\t\t\tfmt.Println(\"HTTP Data Read. Input was = \", string(data) )\n\t\t\t\t} else if len(nodes) > 0{\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNotFound)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP (Length)\")\n\t\t\t\t} else {\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNoContent)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP\")\n\t\t\t\t}\n\t\t}\n\tdefault:\n\t\thttp.Error(w, \"Wrong. Use POST or GET\", http.StatusMethodNotAllowed)\n\t}\n}", "func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)", "func (h *Handler) ServeHTTP(response http.ResponseWriter, request *http.Request) {\n\tif request.ContentLength > int64(h.Service.MaxRequestLength) {\n\t\tresponse.WriteHeader(http.StatusRequestEntityTooLarge)\n\t\treturn\n\t}\n\tif request.Method == \"GET\" {\n\t\tif h.clientAccessPolicyXMLHandler(response, request) ||\n\t\t\th.crossDomainXMLHandler(response, request) {\n\t\t\treturn\n\t\t}\n\t\tif !h.GET {\n\t\t\tresponse.WriteHeader(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t}\n\tdata, err := readAll(request.Body, request.ContentLength)\n\tif err != nil {\n\t\th.onError(response, request, err)\n\t}\n\tif err = request.Body.Close(); err != nil {\n\t\th.onError(response, request, err)\n\t}\n\tserviceContext := h.getServiceContext(response, request)\n\tctx := core.WithContext(request.Context(), serviceContext)\n\tresult, err := h.Service.Handle(ctx, data)\n\tif err != nil {\n\t\th.onError(response, request, err)\n\t}\n\tresponse.Header().Set(\"Content-Length\", strconv.Itoa(len(result)))\n\th.sendHeader(serviceContext, response, request)\n\t_, err = response.Write(result)\n\tif err != nil {\n\t\th.onError(response, request, err)\n\t}\n}", "func Handler(config *config.ProxyConfig, cli *http.Client) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tproxyReq, reqSize, err := createRequest(r, config)\n\t\tif err != nil {\n\t\t\tHandleError(w, r, err.Error(), config.PrintLogs)\n\t\t\treturn\n\t\t}\n\n\t\trs, err := cli.Do(proxyReq)\n\t\tif err != nil {\n\t\t\tHandleError(w, r, fmt.Sprintf(\"[%s] error performing request to target: \"+err.Error(), config.ProxyName), config.PrintLogs)\n\t\t\treturn\n\t\t}\n\n\t\trsSize, err := writeResponse(w, rs, config)\n\t\tif err != nil {\n\t\t\tHandleError(w, r, err.Error(), config.PrintLogs)\n\t\t\treturn\n\t\t}\n\n\t\tif config.PrintLogs {\n\t\t\tPrintLog(start, reqSize, rsSize, r, config.CompactLogs)\n\t\t}\n\t})\n}", "func (app *App) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\thandler(app.DB, w, r)\r\n\t}\r\n}", "func (fh *FileHandle) Handle(w http.ResponseWriter, r *http.Request, ps Params) {\n\tr.URL.Path = ps.ByName(\"filepath\")\n\tr.RequestURI = r.URL.String()\n\n\tfh.handler.ServeHTTP(w, r)\n}", "func handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/movies\", getAllMoviesSortedDetails)\n\tlog.Fatal(http.ListenAndServe(\":8081\", nil))\n}", "func HttpHandler(store *Store) HttpHandlerFunc {\r\n\treturn func(rw http.ResponseWriter, r *http.Request) {\r\n\t\tif r.Method == \"GET\" {\r\n\t\t\thandleListDishes(store, rw)\r\n\t\t} else if r.Method == \"POST\" {\r\n\t\t\thandleOrderCreate(r, rw, store)\r\n\t\t} else {\r\n\t\t\trw.WriteHeader(http.StatusMethodNotAllowed)\r\n\t\t}\r\n\t}\r\n}", "func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tpanic(fmt.Sprintf(\"httpx: ServeHTTP called on %v\", h))\n}", "func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tpanic(fmt.Sprintf(\"httpx: ServeHTTP called on %v\", h))\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\t// Collect request parameters to add them to the entry HTTP span. We also need to make\n\t// sure that a proper span kind is set for the entry span, so that Instana could combine\n\t// it and its children into a call.\n\topts := []opentracing.StartSpanOption{\n\t\text.SpanKindRPCServer,\n\t\topentracing.Tags{\n\t\t\t\"http.host\": req.Host,\n\t\t\t\"http.method\": req.Method,\n\t\t\t\"http.protocol\": req.URL.Scheme,\n\t\t\t\"http.path\": req.URL.Path,\n\t\t},\n\t}\n\n\t// Check if there is an ongoing trace context provided with request and use\n\t// it as a parent for our entry span to ensure continuation.\n\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t)\n\tif err != nil {\n\t\topts = append(opts, ext.RPCServerOption(wireContext))\n\t}\n\n\t// Start the entry span adding collected tags and optional parent. The span name here\n\t// matters, as it allows Instana backend to classify the call as an HTTP one.\n\tspan := opentracing.GlobalTracer().StartSpan(\"g.http\", opts...)\n\tdefer span.Finish()\n\n\ttime.Sleep(300 * time.Millisecond)\n\tw.Write([]byte(\"Hello, world!\\n\"))\n}", "func handleRequest(pc net.PacketConn, addr net.Addr, pr *PacketRequest, connectionSvc *ConnectionService) {\n\tif pr.Op == OpRRQ { // Read Request\n\t\tLogReadRequest(pr.Filename)\n\t\tdata, err := connectionSvc.openRead(addr.String(), pr.Filename)\n\t\tif err != nil {\n\t\t\tLogFileNotFound(pr.Filename)\n\t\t\tsendResponse(pc, addr, &PacketError{0x1, \"File not found (error opening file read)\"})\n\t\t} else {\n\t\t\tsendResponse(pc, addr, &PacketData{0x1, data})\n\t\t}\n\t} else if pr.Op == OpWRQ { // Write Request\n\t\tLogWriteRequest(pr.Filename)\n\t\tconnectionSvc.openWrite(addr.String(), pr.Filename)\n\t\tsendResponse(pc, addr, &PacketAck{0})\n\t}\n}", "func HandlePostRequest(w http.ResponseWriter, r *http.Request) {\n\n}", "func index_handler(w http.ResponseWriter, r *http.Request){ \n // the w parameter is of the http.ResponseWriter type\n // it's *http.Request, we're reading through the value of the request. \n\n // let's just put some text on the screen.\n fmt.Fprintf(w, \"Whoa, go is neat!\")\n }", "func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tm.verifyHandler(w, r)\n\t\treturn\n\t}\n\n\tvar rec Receive\n\n\t// consume a *copy* of the request body\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(body))\n\n\terr := json.Unmarshal(body, &rec)\n\tif err != nil {\n\t\terr = xerrors.Errorf(\"could not decode response: %w\", err)\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"could not decode response:\", err)\n\t\trespond(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif rec.Object != \"page\" {\n\t\tfmt.Println(\"Object is not page, undefined behaviour. Got\", rec.Object)\n\t\trespond(w, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tif m.verify {\n\t\tif err := m.checkIntegrity(r); err != nil {\n\t\t\tfmt.Println(\"could not verify request:\", err)\n\t\t\trespond(w, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t}\n\n\tm.dispatch(rec)\n\n\trespond(w, http.StatusAccepted) // We do not return any meaningful response immediately so it should be 202\n}", "func (h AppServer) Handler (w http.ResponseWriter, r *http.Request) {\n\twasHandled := false\n\turlPath := r.URL.Path\n\tl := len(urlPath)\n\tif l > 0 {\n\t\tif urlPath[l-1:l] != \"/\" {\n\t\t\t// tack on a trailing slash\n\t\t\turlPath = urlPath + \"/\"\n\t\t}\n\t\tfmt.Println(\"appServer handler path=\", urlPath)\n\t\t\n\t\tfor p := range h.Handlers {\n\t\t\tif len(urlPath) >= len(p) &&\turlPath[:len(p)] == p {\n\t\t\t\twasHandled = true\n\t\t\t\tphf := h.Handlers[p]\n\t\t\t\tDispatchMethod(phf, w, r)\n\t\t\t} \n\t\t}\n\t}\n\tif !wasHandled {\n\t\t// not specific handler, assume it's a file\n\t\tif h.FileServerInst != nil {\n\t\t\tDispatchMethod(h.FileServerInst, w, r)\n\t\t} else {\n\t\t\thttp.Error(w, \"File not Found\", http.StatusNotFound)\n\t\t}\n\t}\n\n}", "func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\n\n\tserver := os.Getenv(\"SERVER\")\n\n\t//Get the path parameter that was sent\n\tpath := request.Path\n\n\turl := \"http://\" + server + path\n\tresp, err := http.Get(url)\n if err != nil {\n\t\tlog.Fatalln(err)\n }\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n if err != nil {\n\t\tlog.Fatalln(err)\n }\n\n\n\t//Generate message that want to be sent as body\n\t//message := fmt.Sprintf(\" { \\\"Message\\\" : \\\"Hello %s \\\" } \", url)\n\n\t//Returning response with AWS Lambda Proxy Response\n\treturn events.APIGatewayProxyResponse{Body: string(body), StatusCode: 200}, nil\n}", "func (importer *BaseRequestImporter) HandleRequest(resp http.ResponseWriter, req *http.Request) {\n\tbody, _ := ioutil.ReadAll(req.Body)\n\tmeshData, status, respData, err := importer.handleQuery(body, req.URL.Path, req.URL.Query())\n\tif err == nil {\n\t\tif len(meshData) > 0 {\n\t\t\timporter.mergeImportedMeshData(meshData)\n\t\t}\n\t} else {\n\t\trespData = []byte(err.Error())\n\t}\n\tresp.WriteHeader(status)\n\t_, _ = resp.Write(respData)\n}", "func HandleHTTP() {\n\tDefaultServer.HandleHTTP()\n}", "func (Executor) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tlogger.Logging(logger.DEBUG, \"receive msg\", req.Method, req.URL.Path)\n\tdefer logger.Logging(logger.DEBUG, \"OUT\")\n\n\tswitch reqUrl := req.URL.Path; {\n\tdefault:\n\t\tlogger.Logging(logger.DEBUG, \"Unknown URL\")\n\t\tcommon.MakeErrorResponse(w, errors.NotFoundURL{reqUrl})\n\n\tcase !(strings.Contains(reqUrl, (url.Base()+url.Management())) ||\n\t\tstrings.Contains(reqUrl, (url.Base()+url.Monitoring())) ||\n\t\tstrings.Contains(reqUrl, (url.Base()+url.Notification()))):\n\t\tlogger.Logging(logger.DEBUG, \"Unknown URL\")\n\t\tcommon.MakeErrorResponse(w, errors.NotFoundURL{reqUrl})\n\n\tcase strings.Contains(reqUrl, url.Unregister()):\n\t\thealthAPIExecutor.Handle(w, req)\n\n\tcase strings.Contains(reqUrl, url.Management()) &&\n\t\tstrings.Contains(reqUrl, url.Apps()):\n\t\tdeploymentAPIExecutor.Handle(w, req)\n\n\tcase strings.Contains(reqUrl, url.Resource()):\n\t\tresourceAPIExecutor.Handle(w, req)\n\n\tcase strings.Contains(reqUrl, url.Configuration()):\n\t\tconfigurationAPIExecutor.Handle(w, req)\n\n\tcase strings.Contains(reqUrl, url.Device()):\n\t\tdeviceAPIExecutor.Handle(w, req)\n\n\tcase strings.Contains(reqUrl, url.Notification()):\n\t\tnotificationAPIExecutor.Handle(w, req)\n\t}\n}", "func GenericHandler(response http.ResponseWriter, request *http.Request){\n\n\t// Set cookie and MIME type in the HTTP headers.\n\tSetMyCookie(response)\n\tresponse.Header().Set(\"Content-type\", \"text/plain\")\n\n\t// Parse URL and POST data into the request.Form\n\terr := request.ParseForm()\n\tif err != nil {\n\t\thttp.Error(response, fmt.Sprintf(\"error parsing url %v\", err), 500)\n\t}\n\n\t// Send the text diagnostics to the client.\n\tfmt.Fprint(response, \"FooWebHandler says ... \\n\")\n\tfmt.Fprintf(response, \" request.Method '%v'\\n\", request.Method)\n\tfmt.Fprintf(response, \" request.RequestURI '%v'\\n\", request.RequestURI)\n\tfmt.Fprintf(response, \" request.URL.Path '%v'\\n\", request.URL.Path)\n\tfmt.Fprintf(response, \" request.Form '%v'\\n\", request.Form)\n\tfmt.Fprintf(response, \" request.Cookies() '%v'\\n\", request.Cookies())\n}", "func (srv *server) handleRequest(clt *Client, msg *Message) {\n\treplyPayload, returnedErr := srv.impl.OnRequest(\n\t\tcontext.Background(),\n\t\tclt,\n\t\tmsg,\n\t)\n\tswitch returnedErr.(type) {\n\tcase nil:\n\t\tsrv.fulfillMsg(clt, msg, replyPayload)\n\tcase ReqErr:\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\tcase *ReqErr:\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\tdefault:\n\t\tsrv.errorLog.Printf(\"Internal error during request handling: %s\", returnedErr)\n\t\tsrv.failMsg(clt, msg, returnedErr)\n\t}\n}", "func Handler(c *gin.Context) {\n\tvar req Request\n\tc.BindJSON(&req)\n\ts := service{\n\t\tcontext: c,\n\t\treq: req,\n\t}\n\tres, err := s.Execute()\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\"data\": res.Data})\n}", "func Handle(req gohttp.Request) (gohttp.Response, error) {\n\tvar err error\n\n\tlogrus.Info(\"Value of body: \", string(req.GetBody()))\n\n\tmessage := fmt.Sprintf(\"Body: %s\", string(req.GetBody()))\n\n\treturn gohttp.FunctionResponse{\n\t\tBody: []byte(message),\n\t\tStatusCode: http.StatusAccepted,\n\t\tHeader: http.Header{\"Content-Type\": []string{\"text/plain\"}}}, err\n}", "func (d *Delete) HandleRequest(req *web.Request, res *web.Response) {\n\tresp := fmt.Sprintf(\"your method is [%s].\\n\", req.Method)\n\tres.WriteString(resp)\n\tres.Flush()\n}", "func handler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"%s %s %s\\n\", r.Method, r.URL.String(), r.Proto)\n\t//print headers to the response\n\tfor header, value := range r.Header {\n\t\tfmt.Fprintf(w, \"Header[%q] = %q\\n\", header, value)\n\t}\n\t//print the host\n\tfmt.Fprintf(w, \"Host = %q\\n\", r.Host)\n\t//print remote address\n\tfmt.Fprintf(w, \"Remote address = %q\\n\", r.RemoteAddr)\n\t//parse the form arguments /index.htlm?pretty=true\n\tif err := r.ParseForm(); err != nil {\n\t\t//err is visible only in the scope of the if's block\n\t\tlog.Print(err)\n\t}\n\t//now print the form\n\tfor form, value := range r.Form {\n\t\tfmt.Fprintf(w, \"Form[%q] = %q\\n\", form, value)\n\t}\n}", "func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t_, _ = pretty.Println(\"parsed:\", request.Body)\n\treturn events.APIGatewayProxyResponse{Body: \"response is working\", StatusCode: 200}, nil\n}", "func Handler(rc *Context, s storage.Store, storeExecutor kvs) {\r\n\r\n\t// Make sure all resources are cleanup after leaving\r\n\tcancelFunc := rc.CtxCancel\r\n\tdefer cancelFunc()\r\n\r\n\t// Err channel shared across\r\n\terrc := make(chan error, 1)\r\n\r\n\t// Execution call\r\n\tout := make(chan interface{}, 1)\r\n\r\n\tgo func() {\r\n\t\tdefer close(out)\r\n\t\tdefer close(errc)\r\n\r\n\t\tinb := <-httpExtractor(rc, errc)\r\n\r\n\t\tlogging.MsgFields(\r\n\t\t\trc.uID,\r\n\t\t\t\"HttpExtractor\",\r\n\t\t\tlogging.Input,\r\n\t\t\tlogging.Field{{logging.Payload, inb}})\r\n\r\n\t\tif rc.Cancelled() {\r\n\t\t\tlogging.Msg(\r\n\t\t\t\trc.uID,\r\n\t\t\t\t\"Handler\",\r\n\t\t\t\tlogging.Cancelled,\r\n\t\t\t\t\"kvs execution was cancelled from another goroutine\")\r\n\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\tres, err := storeExecutor(s, inb)\r\n\r\n\t\tif err != nil {\r\n\t\t\terrc <- err\r\n\t\t\tcancelFunc()\r\n\t\t\treturn\r\n\t\t}\r\n\r\n\t\tselect {\r\n\t\tcase out <- res:\r\n\t\tcase <-rc.Ctx.Done():\r\n\t\t\treturn\r\n\t\t}\r\n\t}()\r\n\r\n\tHTTPResponse(rc, out, errc)\r\n}", "func (q *eventQ) handleRequest(req *protocol.Request) (*protocol.Response, error) {\n\tvar resp *protocol.Response\n\tvar err error\n\tinternal.Debugf(q.conf, \"request: %s\", &req.Name)\n\n\tswitch req.Name {\n\tcase protocol.CmdBatch:\n\t\tresp, err = q.handleBatch(req)\n\t\tinstrumentRequest(stats.BatchRequests, stats.BatchErrors, err)\n\tcase protocol.CmdRead:\n\t\tresp, err = q.handleRead(req)\n\t\tinstrumentRequest(stats.ReadRequests, stats.ReadErrors, err)\n\tcase protocol.CmdTail:\n\t\tresp, err = q.handleTail(req)\n\t\tinstrumentRequest(stats.TailRequests, stats.TailErrors, err)\n\tcase protocol.CmdStats:\n\t\tresp, err = q.handleStats(req)\n\t\tinstrumentRequest(stats.StatsRequests, stats.StatsErrors, err)\n\tcase protocol.CmdClose:\n\t\tresp, err = q.handleClose(req)\n\t\tinstrumentRequest(stats.CloseRequests, stats.CloseErrors, err)\n\tcase protocol.CmdConfig:\n\t\tresp, err = q.handleConfig(req)\n\t\tinstrumentRequest(stats.ConfigRequests, stats.ConfigErrors, err)\n\tdefault:\n\t\tlog.Printf(\"unhandled request type passed: %v\", req.Name)\n\t\tresp = req.Response\n\t\tcr := req.Response.ClientResponse\n\t\tcr.SetError(protocol.ErrInvalid)\n\t\terr = protocol.ErrInvalid\n\t\tif _, werr := req.WriteResponse(resp, cr); werr != nil {\n\t\t\terr = werr\n\t\t}\n\t}\n\n\treturn resp, err\n}", "func (this *HTTPHandler) handle(req Request) Response {\n\tname := resources.NewObjectName(req.Namespace, req.Name)\n\tlogctx := this.NewContext(\"object\", name.String())\n\tlogctx.Infof(\"handle request for %s\", req.Resource)\n\tresp := this.webhook.Handle(logctx, req)\n\tif err := resp.Complete(req); err != nil {\n\t\tlogctx.Error(err, \"unable to encode response\")\n\t\treturn ErrorResponse(http.StatusInternalServerError, errUnableToEncodeResponse)\n\t}\n\treturn resp\n}", "func (s server) Handle(w http.ResponseWriter, r *http.Request) {\n\t/* If we have creds set, check them */\n\tif \"\" != s.username || \"\" != s.password {\n\t\tw.Header().Set(\n\t\t\t\"WWW-Authenticate\",\n\t\t\t`Basic realm=\"Auth Required\"`,\n\t\t)\n\t\tu, p, ok := r.BasicAuth()\n\t\tif !ok || (\"\" == u && \"\" == p) { /* Client didn't know? */\n\t\t\tlog.Printf(\"[%v] No auth\", r.RemoteAddr)\n\t\t\thttp.Error(w, \"Not authorized\", 401)\n\t\t\treturn\n\t\t}\n\t\tif u != s.username || p != s.password {\n\t\t\tlog.Printf(\n\t\t\t\t\"[%s] Auth fail (%q / %q)\",\n\t\t\t\tr.RemoteAddr,\n\t\t\t\tu,\n\t\t\t\tp,\n\t\t\t)\n\t\t\thttp.Error(w, \"Not authorized\", 401)\n\t\t\treturn\n\t\t}\n\t}\n\n\tlogReq(r)\n\n\t/* Special cases sometimes */\n\tswitch r.Method {\n\tcase http.MethodDelete: /* We may not allow deletes */\n\t\tif s.noDelete {\n\t\t\treturn\n\t\t}\n\tcase http.MethodGet: /* Maybe serve a single file */\n\t\tif \"\" != s.serveFile {\n\t\t\thttp.ServeFile(w, r, s.serveFile)\n\t\t\treturn\n\t\t}\n\t}\n\n\t/* If we're only allowing read access, whitelist the allowed methods */\n\tif s.readOnly {\n\t\tswitch r.Method {\n\t\tcase \"OPTIONS\", \"GET\", \"HEAD\", \"PROPFIND\":\n\t\t\t/* These are ok */\n\t\tdefault:\n\t\t\t/* This is not ok */\n\t\t\treturn\n\t\t}\n\t}\n\n\ts.w.ServeHTTP(w, r)\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\tipn.Handler(w, r)\n}", "func ApiHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"POST\" {\n\t\t// Parsing JSON from request\n\t\tvar req RequestJSON;\n\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\tlog.Printf(\"ApiHandler: Something went wrong when decoding the JSON object.\\n%v\\n\", err)\n\t\t\thttp.Error(w, \"Bad request\", http.StatusBadRequest)\n\t\t}\n\t\t\n\t\t// Call different handlers depending on type of request\n\t\tswitch req.Request {\n\t\t\tcase \"Timeline\":\n\t\t\t\t// Check the session cookie to see if user is authenticated and session is valid\n\t\t\t\trespCookie := CheckCookie(r)\n\t\t\t\tif respCookie.Status == false {\n\t\t\t\t\tsave(w, &respCookie)\n\t\t\t\t}\n\n\t\t\t\tres := timelineHandler(req)\n\t\t\t\tsave(w, &res)\n\t\t\tcase \"Auth\":\n\t\t\t\tres := loginHandler(req, w, r)\n\t\t\t\tsave(w, &res)\n\t\t\tcase \"User\":\n\t\t\t\t// Check the session cookie to see if user is authenticated and session is valid\n\t\t\t\trespCookie := CheckCookie(r)\n\t\t\t\tif respCookie.Status == false {\n\t\t\t\t\tsave(w, &respCookie)\n\t\t\t\t}\n\n\t\t\t\tres := userHandler(req)\n\t\t\t\tsave(w, &res)\n\t\t}\n\t} else {\n\t\thttp.Error(w, \"This method is not allowed.\", 403)\n\t}\n}", "func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tr.HandleFunc(w, req)\n}", "func (h *Handler) handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/customers\", h.returnAllCustomers)\n\tlog.Fatal(http.ListenAndServe(frontendPort, nil))\n}", "func (h *handler) ServeHTTP(w stdhttp.ResponseWriter, r *stdhttp.Request) {\n\th.query = r.URL.Query()\n\th.header = r.Header\n\n\tif r.Method != stdhttp.MethodGet {\n\t\th.readBody(w, r)\n\t}\n\n\tw.WriteHeader(stdhttp.StatusOK)\n\t_, err := w.Write([]byte(\"message\"))\n\th.require.NoError(err)\n}", "func (r *relay) handleRequest(reqId uint64, req []byte) {\n\trep := r.handler.HandleRequest(req)\n\tif err := r.sendReply(reqId, rep); err != nil {\n\t\tlog.Printf(\"iris: failed to send reply: %v.\", err)\n\t}\n}", "func (handler *InterceptorRequestHandler) Handle(request string) (string, error) {\n\tlogrus.Debugf(\"Handle: %+v\", request)\n\tvar response *Response = nil\n\tselect {\n\tcase <-handler.Ctx.Done():\n\t\tresponse = ReturnFail(Code[HandlerClosed], Code[HandlerClosed].Msg)\n\tdefault:\n\t\t// decode\n\t\treq := &Request{}\n\t\terr := json.Unmarshal([]byte(request), req)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar ok = true\n\t\t// interceptor\n\t\tinterceptor := handler.Interceptor\n\t\tif interceptor != nil && !meta.Info.Debugging {\n\t\t\tresponse, ok = interceptor.Handle(req)\n\t\t}\n\t\tif ok {\n\t\t\t// Call Handler only when passing the interceptor\n\t\t\tresponse = handler.Handler.Handle(req)\n\t\t}\n\t}\n\t// encode\n\tbytes, err := json.Marshal(response)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), nil\n}", "func (auth *AuthManager) HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\n\tlogger := GetLogManager().GetLogger()\n\n\t// remove /auth/ from url and split\n\tparts := strings.Split(r.URL.Path[len(AuthEndpoint)+2:], \"/\")\n\n\t// Check if it is an internal action\n\tif action, ok := auth.authActions[parts[0]]; ok {\n\t\tlogger.Printf(\"API builtin action called %q\", parts[0])\n\t\treturn action(w, r)\n\t}\n\n\treturn errors.New(\"Invalid operation\")\n}", "func (handler *WebHandler) Handle(w http.ResponseWriter, req *http.Request) {\n\tswitch req.Method {\n\tcase \"GET\":\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tswitch req.URL.Path[len(\"/analysis/\"):] {\n\t\tcase \"totals\":\n\t\t\tparams, err := processParams(req.URL.Query())\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresults, err := totals(params, handler.rates, handler.backend.DB)\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tjson, _ := json.Marshal(results)\n\t\t\tfmt.Fprintln(w, string(json))\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tcase \"graph\":\n\t\t\tparams, err := processParams(req.URL.Query())\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgParams := gInitialise(params)\n\t\t\tresults, err := graph(gParams, handler.rates, handler.backend.DB)\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(w, results)\n\t\t\tw.Header().Set(\"Content-Type\", \"image/svg+xml\")\n\t\tcase \"assets\":\n\t\t\tparams, err := processParams(req.URL.Query())\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresults, err := asts(params, handler.rates, handler.backend)\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tjson, err := json.Marshal(results)\n\t\t\tif err != nil {\n\t\t\t\twebhandler.ReturnError(err, w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(w, string(json))\n\t\tdefault:\n\t\t\thttp.Error(w, http.StatusText(404), 404)\n\t\t\treturn\n\t\t}\n\tcase \"OPTIONS\":\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"OPTIONS, GET\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"content-type\")\n\tdefault:\n\t\thttp.Error(w, http.StatusText(405), 405)\n\t}\n}", "func handleRequest(resp *http.Response, err error) () {\n if err != nil {\n log.Fatal(err)\n }\n defer resp.Body.Close()\n\n // Dump response\n data, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(string(data))\n}", "func HandleRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodPost {\n\t\thttp.Error(w, fmt.Sprintf(\"Bad method %q\", r.Method), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\taction := r.FormValue(\"action\")\n\tswitch action {\n\tcase \"deleteUser\":\n\t\temail := r.FormValue(\"email\")\n\t\tif err := deleteUser(ctx, email); err != nil {\n\t\t\tlog.Printf(\"Failed deleting %v: %v\", email, err)\n\t\t\thttp.Error(w, fmt.Sprintf(\"Failed deleting %v: %v\", email, err), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"Deleted %v\\n\", email)\n\t\t}\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"Invalid action %q\", action), http.StatusBadRequest)\n\t\treturn\n\t}\n}", "func handler(w http.ResponseWriter, r *http.Request) {\n\thandlerReal(false, w, r)\n}", "func (p *Plain_node) handleRequest(conn net.Conn) error {\n\t// Make a buffer to hold incoming data.\n\tdefer conn.Close()\n\n\tbuf := make([]byte, 1024)\n\n\t// Read the incoming connection into the buffer.\n\t_ , err := conn.Read(buf)\n\n\tif err != nil {\n\t\teprint(err)\n\t\treturn err\n\t}\n\n\tmsg := strings.Trim(string(buf), \"\\x00\")\n\tmsg = strings.Trim(msg, \"\\n\")\n\n\tswitch msg[0] {\n\t\tcase 'J':\n\t\t\tfmt.Println(DHT_PREFIX+\"Joinging Request Received.\")\n\t\t\tp.handle_join(msg, conn)\n\t\tcase 'A':\n\t\t\tfmt.Println(DHT_PREFIX+\"Join Ack Received.\")\n\t\t\tp.handle_join_ack(msg)\n\t\tcase 'B':\n\t\t\tfmt.Println(DHT_PREFIX+\"Newbie joined.\")\n\t\t\tp.add_newbie(msg)\n\t\tcase APP_PREFIX:\n\t\t\tfmt.Println(DHT_PREFIX+\"Application Data Received.\")\n\t\t\tforward_to_app(msg)\n\t\tdefault:\n\t\t\tfmt.Println(DHT_PREFIX+\"Unknown msg format\")\n\t\t//\tconn.Write([]byte(\"Don't Know What You Mean by\"+msg))\n\t}\n\n\treturn nil\n}", "func handleRequest(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, req *http.Request) {\n\t\tfn(rw, req)\n\t}\n}", "func (l RequestID) Handler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\trequestID := strconv.FormatInt(time.Now().Unix(), 10)\n\n\t// if was received the header x-request-id, its value is set in the request context\n\tif v := r.Header.Values(\"x-request-id\"); len(v) > 0 {\n\t\trequestID = v[0]\n\t}\n\n\tctx := context.WithValue(r.Context(), \"request-id\", requestID)\n\n\tnext(w, r.WithContext(ctx))\n}", "func (r *Router) handle(c *Ctx) {\n\tvar handler HandlerFunc\n\treq := c.Request()\n\tw := c.Writer()\n\tpath := req.URL.Path\n\tmethod := req.Method\n\tres := r.trie.Match(path)\n\n\tif res.Node == nil {\n\t\t// FixedPathRedirect or TrailingSlashRedirect\n\t\tif res.TSR != \"\" || res.FPR != \"\" {\n\t\t\treq.URL.Path = res.TSR\n\t\t\tif res.FPR != \"\" {\n\t\t\t\treq.URL.Path = res.FPR\n\t\t\t}\n\t\t\tcode := 301\n\t\t\tif method != \"GET\" {\n\t\t\t\tcode = 307\n\t\t\t}\n\t\t\thttp.Redirect(w, req, req.URL.String(), code)\n\t\t\treturn\n\t\t}\n\t\tif r.noRoute == nil {\n\t\t\thttp.Error(w, fmt.Sprintf(`\"%s\" not implemented`, path), 501)\n\t\t\treturn\n\t\t}\n\t\thandler = r.noRoute\n\t} else {\n\t\t// ok := false\n\t\thd := res.Node.GetHandler(method)\n\t\thandler, _ = hd.(HandlerFunc)\n\t\t// handler = r.wrapHandler(hd)\n\t\t// if !ok {\n\t\t// \tpanic(\"handler error\")\n\t\t// }\n\t\tif handler == nil {\n\t\t\t// OPTIONS support\n\t\t\tif method == http.MethodOptions {\n\t\t\t\tw.Header().Set(\"Allow\", res.Node.GetAllow())\n\t\t\t\tw.WriteHeader(204)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif r.noMethod == nil {\n\t\t\t\t// If no route handler is returned, it's a 405 error\n\t\t\t\tw.Header().Set(\"Allow\", res.Node.GetAllow())\n\t\t\t\thttp.Error(w, fmt.Sprintf(`\"%s\" not allowed in \"%s\"`, method, path), 405)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandler = r.noMethod\n\t\t}\n\t}\n\n\tif len(res.Params) != 0 {\n\t\tc.params = res.Params\n\t}\n\tc.handlers = append(c.handlers, handler)\n\tc.Next()\n}", "func (f *server) Handler(w http.ResponseWriter, r *http.Request) {\n\tdefer log.Info(\"Handler goes down\")\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"upgrade error: %v\", err)\n\t\treturn\n\t}\n\n\tvar conn net.Conn = newConn(c)\n\tinBound, err := f.listener.Connect()\n\tif err != nil {\n\t\tlog.Errorf(\"connect error: %v\", err)\n\t\treturn\n\t}\n\n\tgo f.forward(conn, inBound)\n\tf.forward(inBound, conn)\n}", "func requestHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\", buildResponse())\n}", "func (proxy *proxyService) handleRequest(\n\tw gohttp.ResponseWriter, r *gohttp.Request,\n) {\n\tlogger := proxy.logger\n\n\t// Per the stdlib docs, \"It is an error to set this field in an HTTP client\n\t// request\". Therefore, we ensure it is empty in case the client set it.\n\tr.RequestURI = \"\"\n\n\t// Send request to target service\n\n\tresp, err := proxy.transport.RoundTrip(r)\n\tif err != nil {\n\t\tlogger.Debugf(\"Error: %v\\n\", err)\n\t\tgohttp.Error(w, err.Error(), 503)\n\t\treturn\n\t}\n\n\t// Send response to client (everything below)\n\n\tlogger.Debugf(\"Received response status: %s\\n\", resp.Status)\n\n\tcopyHeaders(w.Header(), resp.Header)\n\n\tw.WriteHeader(resp.StatusCode)\n\n\t_, err = io.Copy(w, resp.Body)\n\tif err != nil {\n\t\tlogger.Errorf(\"Can't write response to body: %s\\n\", err)\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlogger.Debugf(\"Can't close response body %v\\n\", err)\n\t}\n}", "func (k *Kite) HandleHTTP(pattern string, handler http.Handler) {\n\tk.muxer.Handle(pattern, handler)\n}", "func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {\n\tswitch r.URL.Path {\n\tcase \"/status\":\n\t\tp.handleStatus(w, r)\n\tcase \"/hello\":\n\t\tp.handleHello(c,w, r)\n\tdefault:\n\t\thttp.NotFound(w, r)\n\t}\n}", "func (r *router) handle(c *Context) {\n\tn, params := r.getRoute(c.Method, c.Path) //if request method and path exist, return pattern of node and params\n\tif n != nil {\n\t\tc.Params = params\n\t\tc.handlers = append(c.handlers, n.handler) //insert handler after middleware\n\t} else {\n\t\tc.handlers = append(c.handlers, func(c *Context) {\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND: %s\\n\", c.Path)\n\t\t})\n\t}\n\tc.Next()\n}", "func (r *router) handle(c *Context){\n\tn, params := r.getRoute(c.Method, c.Path)\n\tif n != nil {\n\t\tc.Params = params\n\t\t// connection between Context and Router!\n\t\t// it's important\n\t\tkey := c.Method + \"-\" + n.pattern\n\t\t// 两种函数都放到一起了\n\t\tc.handlers = append(c.handlers, r.handlers[key])\n\t\t//r.handlers[key](c)\n\t}else{\n\t\tc.handlers = append(c.handlers, func(c *Context){\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND%s\\n\", c.Path)\n\t\t})\n\t}\n\t//放在这里一起执行, 中间执行, 其逻辑导致\"并行\"效果\n\tc.Next()\n}", "func fetchHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tfetchGetHandler(w, r)\n\tcase \"POST\":\n\t\tfetchPostHandler(w, r)\n\tdefault:\n\t\tlog.Println(\"Invalid Method for /fetch\")\n\t}\n}", "func ProcessGetRequest(w *http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Received GET request \", r.URL.Path)\n\n\t// open the file\n\tfile, err := os.Open(DedupSrvHome + r.URL.Path) // For read access.\n\tif err != nil {\n\t\tlog.Fatalln(\"could not open file \", r.URL.Path, \" err \", err)\n\t\thttp.NotFound(*w, r)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\t// read\n\tvar lines int = 0\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tword := scanner.Text()\n\t\tlines++\n\t\t//log.Println(word)\n\t\tfmt.Fprintln(*w, word)\n\t}\n\tif serr := scanner.Err(); serr != nil {\n\t\tlog.Fatalln(\"error reading the file\", serr)\n\t\treturn\n\t}\n\tlog.Println(\"successfully processed GET request for \", r.URL.Path, \"lines \", lines)\n}", "func HttpHandler() func(http.ResponseWriter, *http.Request) {\n\treturn Default.HttpHandler()\n}", "func (h *ConnectionHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {\n\tswitch req.Method {\n\tcase \"GET\":\n\t\th.get(res, req)\n\tcase \"POST\":\n\t\th.post(res, req)\n\tdefault:\n\t\tpageNotFoundHandler(res, req)\n\t}\n}", "func (httpHandler *HttpHandler) Run(r *http.Request) {\n\tif r.RequestURI == \"/favicon.ico\" {\n\t\thttpHandler.Response = &Response{200, map[string]string{}, nil, \"\"}\n\t\treturn\n\t}\n\t//reqParams := \"\"\n\tname, port := buildNamePort(r.Host)\n\n\thm, err := httpHandler.Vhosts.GetHostMap(port, name)\n\tif err != nil {\n\t\thttpHandler.Response = &Response{200, map[string]string{}, nil, \"<h1>404</h1>\"}\n\t\treturn\n\t}\n\n\tdocumentRoot := hm.DocumentRoot\n\n\terr, env := httpHandler.buildEnv(documentRoot, r)\n\n\tvar response *Response\n\tif err != nil {\n\t\tresponse = GetResponseByContent(403, nil, nil, \"not allow\")\n\n\t} else {\n\n\t\tfileCode,filename := httpHandler.buildServerHttp(r, env, hm)\n\n\t\tif fileCode == FileCodeStatic {\n\n\n\t\t\t\thttpHandler.StaticFile = &StaticFileHandler{\n\t\t\t\t\tname,\n\t\t\t\t\tport,\n\t\t\t\t\tfilename,\n\t\t\t\t}\n\t\t\t\treturn\n\n\t\t}\n\n\t\tif fileCode == FileCodeTry {\n\t\t\ttryFiles(r.RequestURI, hm.TryFiles, env)\n\t\t}\n\n\t\tif fileCode == FileCodeNotFound {\n\t\t\tresponse = &Response{404,nil,nil,\"<h1>404</h1>\"}\n\t\t\treturn\n\t\t}\n\n\n\t\tfcgi, err := New(hm.Net, hm.Addr)\n\n\t\treq := fcgi.GetRequest(r, env)\n\n\t\tif err != nil {\n\t\t\thttpHandler.log.Printf(\"err: %v\", err)\n\t\t}\n\n\t\tcontent, _, err := fcgi.DoRequest(req)\n\n\t\tif err != nil {\n\t\t\thttpHandler.log.Printf(\"ERROR: %s - %v\", r.URL.Path, err)\n\t\t}\n\n\t\tresponse = GetResponse(fmt.Sprintf(\"%s\", content))\n\n\t}\n\n\thttpHandler.Response = response\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\tvar responseJSON []byte\n\tqueryParams := r.URL.Query()\n\tglog.Info(\"Prime Number params -> \", queryParams)\n\tif len(queryParams) == 0 {\n\t\tglog.Info(\"Query Params are missing\")\n\t}\n\tinput, ok := queryParams[\"input\"]\n\tif !ok {\n\t\tglog.Info(\"URL Param is missing\")\n\t}\n\tn, err := strconv.Atoi(input[0])\n\tif err != nil {\n\t\tglog.Info(err)\n\t}\n\n\tprimeNumbers := make(chan []int)\n\tgo FindPrime(n, primeNumbers)\n\tresult := <-primeNumbers\n\n\t// Marshal and initialize ResponsJSON\n\tresponseJSON, err = json.Marshal(result)\n\tif err != nil {\n\t\tglog.Info(err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(responseJSON))\n}", "func GetHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Received a content request. Preparing response\")\n\tresp := response{\n\t\tSuccessful: false,\n\t\tErrMsg: errors.New(\"Unknown failure\"),\n\t}\n\twriter := json.NewEncoder(w)\n\tdefer writer.Encode(resp)\n\n\t// Parse the request.\n\tfmt.Println(\"Parsing request\")\n\tdata := form{}\n\tresp.ErrMsg = json.NewDecoder(r.Body).Decode(&data)\n\n\tfmt.Println(\"Obtained following data: \")\n\tfmt.Printf(\"%+v\\n\", data)\n\n\t// Validate requestor token\n\tvalid := true\n\tvalid, resp.ErrMsg = session.Validate(data.User, data.Token)\n\n\tfilepath = path + data.ID + data.ContentType\n\n\tresp.ErrMsg = read(filepath)\n\n}", "func (api *Api) handleRequest(handler RequestHandlerFunction) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\thandler(api.DB, w, r)\n\t}\n}", "func (l *logger) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\t// log.Printf(\"%s %s - begin\", req.Method, req.URL.Path)\n\tstart := time.Now()\n\tl.handler.ServeHTTP(w, req)\n\tlog.Printf(\"%s %s %v\", req.Method, req.URL.Path, time.Since(start))\n\t// log.Printf(\"header: %v\", req.Header)\n}", "func (l *logger) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\t// log.Printf(\"%s %s - begin\", req.Method, req.URL.Path)\n\tstart := time.Now()\n\tl.handler.ServeHTTP(w, req)\n\tlog.Printf(\"%s %s %v\", req.Method, req.URL.Path, time.Since(start))\n\t// log.Printf(\"header: %v\", req.Header)\n}", "func (t *HandlerTCP) Handler() {\n\t//todo ask about binds!\n\tln, err := net.Listen(\"tcp\", \":8080\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"TCP server started on :8080\")\n\tdefer func() {\n\t\terr := ln.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Connection doesn't accepted: \")\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tgo HandleJSON(conn, t)\n\t}\n}", "func handleRequests() {\n\n\thttp.HandleFunc(\"/\", home)\n\thttp.HandleFunc(\"/greet-me/\", greetMe)\n\thttp.HandleFunc(\"/books\", getBooks)\n\thttp.HandleFunc(\"/book\", createBook)\n\thttp.HandleFunc(\"/book/\", getBookById)\n\thttp.HandleFunc(\"/books/title/\", getBookByTitle)\n\n\tlog.Fatal(http.ListenAndServe(\":10000\", nil))\n}", "func (c *RequestKey) Handler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tc.ServeHTTP(w, r)\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (pi *PackageIndexer) HandleRequest(req Request) string {\n\t// bad request made \n\tif req.err != \"\" {\n\t\treturn ERROR \n\t}\n\t// set the name of the package \t\n\tpack := Package{name: req.pack}\t\t\t\t\t\t\t\t\n\t// add package dependencies \n\tfor _, name := range req.dep {\t\t\t\t\t\t\t\t \n\t\tpack.deps = append(pack.deps, &Package{name: name})\n\t}\n\t// check command type \n switch req.comm {\t\t\t\t\t\t\t\t\t\t\t\n case \"INDEX\":\n return pi.Index(&pack)\n case \"REMOVE\":\n return pi.Remove(&pack)\n case \"QUERY\":\n return pi.Query(pack.name)\n }\n\n // otherwise, error with request \n return ERROR \t\t\t\t\t\t\t\t\t\t\t\t\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"Handling request to /art. [uri: %s]\", r.RequestURI)\n\n\tfileNameSlice := r.URL.Query()[\"fileName\"]\n\tif fileNameSlice == nil {\n\t\thttp.Error(w, \"expecting fileName query parameter\", http.StatusInternalServerError)\n\t\tlog.Printf(\"expecting fileName query parameter\")\n\t}\n\n\tfileName = fileNameSlice[0]\n\n\tpicture = tag.Picture{}\n\tfilepath.Walk(list.WatchDir, visit)\n\n\tif picture.Data != nil {\n\t\tw.Header().Set(\"Content-Type\", picture.MIMEType)\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(picture.Data)))\n\t\tw.Write(picture.Data)\n\t} else {\n\t\tlog.Printf(\"Checking %s for a .jpg or a .png file\", songDir)\n\t\tstoredPic = storedPicture{}\n\t\tfilepath.Walk(songDir, visit2)\n\t\tif storedPic.Data != nil {\n\t\t\tw.Header().Set(\"Content-Type\", storedPic.Type)\n\t\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(storedPic.Data)))\n\t\t\tw.Write(storedPic.Data)\n\t\t} else {\n\t\t\thttp.Error(w, \"Unable to find picture.\", http.StatusNotFound)\n\t\t}\n\t}\n\n}", "func Handler(c *clevergo.Context) error {\n\tname := strings.TrimPrefix(c.Params.String(\"name\"), \"/\")\n\tif handler, ok := handlers[name]; ok {\n\t\treturn handler(c)\n\t}\n\treturn index(c)\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\n\tdefer catchPanic(w, r)\n\n\tif basePath := \"/Foogazi\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello\"))\n\t\treturn\n\t}\n\tif basePath := \"/Foo\"; strings.Contains(r.URL.Path, basePath) {\n\n\t\tif basePath := \"/Foo/Bar\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\t\ttools.ShortenPath(basePath, r)\n\n\t\t\tw.Write([]byte(r.URL.Path))\n\t\t\treturn\n\t\t}\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello world\"))\n\t\treturn\n\t}\n\tif basePath := \"/hello\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello World\"))\n\t\treturn\n\t}\n\tif basePath := \"/hello_POST\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"POST\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\t\tprintln(\"Request to Hello_post\")\n\t\tw.Write([]byte(\"Hello World\"))\n\t\treturn\n\t}\n}", "func (a *App) Handler() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar (\n\t\t\tstatus int\n\t\t\tfinal string\n\t\t\taction string\n\t\t\tbody interface{}\n\t\t\tmatched *route\n\t\t\tresponse *Response\n\t\t)\n\t\treq := newRequest(r)\n\t\tfor _, route := range a.routes {\n\t\t\tif route.Match(req) != nil {\n\t\t\t\tif route.handler != nil {\n\t\t\t\t\troute.handler(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmatched = route\n\t\t\t\tstatus, body, action = route.Respond(req)\n\t\t\t\tif status == 301 || status == 302 {\n\t\t\t\t\tresp, ok := body.(*Response)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tfinal = resp.Body.(string)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinal = body.(string)\n\t\t\t\t\t}\n\t\t\t\t\tresp.Headers.Set(\"Location\", final)\n\t\t\t\t\tresp.status = status\n\t\t\t\t\tresp.write(w)\n\t\t\t\t\treq.log(status, len(final))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\trouteData := &RouteData{\n\t\t\tAction: action,\n\t\t\tVerb: r.Method,\n\t\t}\n\t\tif matched == nil {\n\t\t\tstatus = 404\n\t\t\tfinal = \"\"\n\t\t} else {\n\t\t\trouteData.ControllerName = pluralOf(matched.controller)\n\t\t}\n\t\tcontentType := req.ContentType()\n\n\t\tif resp, ok := body.(*Response); ok {\n\t\t\tresponse = resp\n\t\t\tif ct := response.Headers.Get(\"Content-Type\"); ct != contentType && ct != \"\" {\n\t\t\t\tcontentType = ct\n\t\t\t}\n\t\t} else {\n\t\t\tresponse = NewResponse(body)\n\t\t}\n\n\t\tstatus, final, mime, _ := a.Process(req, status, response.Body, contentType, routeData)\n\n\t\tresponse.status = status\n\t\tresponse.final = final\n\t\tresponse.Headers.Set(\"Content-Type\", mime)\n\t\tresponse.write(w)\n\t\treq.log(status, len(response.final))\n\t}\n}", "func Handler(c Config) (http.Handler, error) {\n\th, _, err := HandlerAPI(c)\n\treturn h, err\n}", "func Handle(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tauth(w, r)\n\tcase http.MethodPost:\n\t\tregister(w, r)\n\tdefault:\n\t\tw.WriteHeader(http.StatusNotImplemented)\n\t}\n}" ]
[ "0.6943892", "0.69266075", "0.6889878", "0.68744844", "0.68425554", "0.68363994", "0.67919886", "0.67399997", "0.6602364", "0.6536131", "0.6513273", "0.65003955", "0.6492272", "0.6476155", "0.64585626", "0.6449561", "0.6427381", "0.64236087", "0.63830346", "0.6380513", "0.63704425", "0.6346832", "0.63444597", "0.63279647", "0.6327202", "0.6324188", "0.6323964", "0.6307958", "0.6307556", "0.6282218", "0.6274111", "0.6273404", "0.62655526", "0.62646", "0.6264188", "0.6262502", "0.6262502", "0.62619644", "0.6257715", "0.62572205", "0.6249908", "0.62481076", "0.62448084", "0.62402767", "0.62363976", "0.6230813", "0.6226752", "0.62204933", "0.6212221", "0.6202016", "0.6199839", "0.61872953", "0.61862123", "0.61770314", "0.616694", "0.61628324", "0.6143977", "0.61368555", "0.6132228", "0.61303455", "0.61231446", "0.6120447", "0.6116253", "0.61146975", "0.6114144", "0.6105285", "0.61016554", "0.61004955", "0.609623", "0.60944474", "0.6092627", "0.60921675", "0.60908747", "0.60841554", "0.6083891", "0.6083815", "0.6077174", "0.60771215", "0.6075448", "0.6070575", "0.6069134", "0.60679823", "0.60673493", "0.60639364", "0.60633445", "0.60584176", "0.60546", "0.6054063", "0.6053831", "0.60512555", "0.60512555", "0.6050797", "0.604996", "0.6046009", "0.6039499", "0.6030933", "0.60278577", "0.60187715", "0.60146207", "0.60138726", "0.60118884" ]
0.0
-1
Load defines HTTP API
func Load(s server.Controller, middleware ...gin.HandlerFunc) http.Handler { e := gin.New() gin.SetMode(gin.ReleaseMode) e.Use(gin.Recovery()) e.Use(header.NoCache) e.Use(header.Options) e.Use(middleware...) e.Use(logger.Logger()) e.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "code": 404, "message": "request not found", }) }) app := e.Group("/api/v1") { app.GET("/application/:name", s.GetApplication) app.GET("/applications", s.ListApplications) app.POST("/application", s.CreateApplication) app.DELETE("/application/:name", s.DeleteApplication) app.GET("/resource/:name", s.GetResource) app.DELETE("/resource/:name", s.DeleteResource) app.GET("/resources", s.ListResource) app.GET("/resources/timeframe/:name", s.ListTimeframeResource) app.DELETE("/resources/timeframe/:name", s.DeleteTimeframeResource) app.GET("/resources/timeframe/:name/:appName", s.GetTimeframeResource) // app.POST("/resource", s.CreateResource) app.POST("/timeframe", s.CreateTimeframe) app.GET("/timeframes", s.ListTimeframes) app.GET("/timeframe/:name", s.GetTimeframe) app.PUT("/timeframe", s.UpdateTimeframe) app.DELETE("/timeframe/:name", s.DeleteTimeframe) } e.GET("/version", versionCtrl) return e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *APILoader) LoadDefinitions(repo api.Repository) {\n\tspecs := m.getAPISpecs(repo)\n\tm.RegisterApis(specs)\n}", "func Load(entrypoint string, root *cobra.Command) (API, error) {\n\turis := []string{}\n\n\tif !strings.HasSuffix(entrypoint, \"/\") {\n\t\tentrypoint += \"/\"\n\t}\n\n\turi, err := url.Parse(entrypoint)\n\tif err != nil {\n\t\treturn API{}, err\n\t}\n\n\tname, config := findAPI(entrypoint)\n\tdesc := API{}\n\tfound := false\n\n\tfromFileOrUrl := func(uri string) ([]byte, error) {\n\t\turiLower := strings.ToLower(uri)\n\t\tif strings.Index(uriLower, \"http\") == 0 {\n\t\t\tresp, err := http.Get(uri)\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\t\t\treturn ioutil.ReadAll(resp.Body)\n\t\t} else {\n\t\t\treturn ioutil.ReadFile(os.ExpandEnv(uri))\n\t\t}\n\t}\n\tif name != \"\" && len(config.SpecFiles) > 0 {\n\t\t// Load the local files\n\t\tfor _, filename := range config.SpecFiles {\n\t\t\tresp := &http.Response{\n\t\t\t\tProto: \"HTTP/1.1\",\n\t\t\t\tStatusCode: 200,\n\t\t\t}\n\n\t\t\tbody, err := fromFileOrUrl(filename)\n\t\t\tif err != nil {\n\t\t\t\treturn API{}, err\n\t\t\t}\n\n\t\t\tfor _, l := range loaders {\n\t\t\t\t// Reset the body\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(body))\n\n\t\t\t\tif l.Detect(resp) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(body))\n\t\t\t\t\ttmp, err := load(root, *uri, *uri, resp, name, l)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn API{}, err\n\t\t\t\t\t}\n\t\t\t\t\tLogDebug(\"Loaded %s\", filename)\n\t\t\t\t\tdesc.Merge(tmp)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif found {\n\t\t\treturn desc, nil\n\t\t}\n\t}\n\n\tLogDebug(\"Checking API entrypoint %s\", entrypoint)\n\treq, err := http.NewRequest(http.MethodGet, entrypoint, nil)\n\tif err != nil {\n\t\treturn API{}, err\n\t}\n\n\t// For fetching specs, we apply a 24-hour cache time if no cache headers\n\t// are set. So APIs can opt-in to caching if they want control, otherwise\n\t// we try and do the right thing and not hit them too often. Localhost\n\t// is never cached to make local development easier.\n\tclient := MinCachedTransport(24 * time.Hour).Client()\n\tif viper.GetBool(\"rsh-no-cache\") || req.URL.Hostname() == \"localhost\" {\n\t\tclient = &http.Client{Transport: InvalidateCachedTransport()}\n\t}\n\n\thttpResp, err := MakeRequest(req, WithClient(client), WithoutLog())\n\tif err != nil {\n\t\treturn API{}, err\n\t}\n\tdefer httpResp.Body.Close()\n\n\tresp, err := ParseResponse(httpResp)\n\tif err != nil {\n\t\treturn API{}, err\n\t}\n\n\t// Start with known link relations for API descriptions.\n\tfor _, l := range resp.Links[\"service-desc\"] {\n\t\turis = append(uris, l.URI)\n\t}\n\tfor _, l := range resp.Links[\"describedby\"] {\n\t\turis = append(uris, l.URI)\n\t}\n\n\t// Try hints from loaders next. These are likely places for API descriptions\n\t// to be on the server, like e.g. `/openapi.json`.\n\tfor _, l := range loaders {\n\t\turis = append(uris, l.LocationHints()...)\n\t}\n\n\turis = append(uris, uri.String())\n\n\tfor _, checkURI := range uris {\n\t\tparsed, err := url.Parse(checkURI)\n\t\tif err != nil {\n\t\t\treturn API{}, err\n\t\t}\n\t\tresolved := uri.ResolveReference(parsed)\n\t\tLogDebug(\"Checking %s\", resolved)\n\n\t\tresp, err := client.Get(resolved.String())\n\t\tif err != nil {\n\t\t\treturn API{}, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn API{}, err\n\t\t}\n\n\t\tfor _, l := range loaders {\n\t\t\t// Reset the body\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(body))\n\n\t\t\tif l.Detect(resp) {\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewReader(body))\n\n\t\t\t\treturn load(root, *uri, *resolved, resp, name, l)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn API{}, fmt.Errorf(\"could not detect API type: %s\", entrypoint)\n}", "func InitAPI() {\n\n}", "func (apiConfig *api) load() {\n\tlogger.Log.Info(\"Reading API config...\")\n\t// viper.SetEnvPrefix(\"api\")\n\tviper.SetConfigFile(\".env\")\n\tviper.AutomaticEnv()\n\n\tapiConfig.apiKey = viper.GetString(\"api_key\")\n}", "func (api *api) load() {\n\tcontent, err := ioutil.ReadFile(api.ConfigFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tv := map[string]string{}\n\terr = json.Unmarshal(content, &v)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfor k, t := range v {\n\t\terr = api.addService(k, t)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func Load() {\n\trouter.Get(uri, Index)\n}", "func InitApi(app *iris.Application) {\n\t// var getAPI router.Party\n\n\tif config.Conf.Debug {\n\t\tppApi := app.Party(\"/debug\")\n\t\tppApi.Get(\"/pprof\", pprofHandler(pprof.Index))\n\t\tppApi.Get(\"/cmdline\", pprofHandler(pprof.Cmdline))\n\t\tppApi.Get(\"/profile\", pprofHandler(pprof.Profile))\n\t\tppApi.Post(\"/symbol\", pprofHandler(pprof.Symbol))\n\t\tppApi.Get(\"/symbol\", pprofHandler(pprof.Symbol))\n\t\tppApi.Get(\"/trace\", pprofHandler(pprof.Trace))\n\t\tppApi.Get(\"/block\", pprofHandler(pprof.Handler(\"block\").ServeHTTP))\n\t\tppApi.Get(\"/goroutine\", pprofHandler(pprof.Handler(\"goroutine\").ServeHTTP))\n\t\tppApi.Get(\"/allocs\", pprofHandler(pprof.Handler(\"allocs\").ServeHTTP))\n\t\tppApi.Get(\"/heap\", pprofHandler(pprof.Handler(\"heap\").ServeHTTP))\n\t\tppApi.Get(\"/mutex\", pprofHandler(pprof.Handler(\"mutex\").ServeHTTP))\n\t\tppApi.Get(\"/threadcreate\", pprofHandler(pprof.Handler(\"threadcreate\").ServeHTTP))\n\n\t\tgetAPI := app.Party(\"/get\")\n\t\tgetAPI.Get(\"/crontab\", ShowCrontab)\n\t}\n}", "func Load() {\n\n\tAppCfg = appConfig{\n\t\tElasticSearchURL: \"localhost:9200\",\n\t\tItemServiceURL: \"localhost:4040\",\n\t}\n\n\t/*\n\t\tAppCfg = appConfig{\n\t\t\tElasticSearchURL: os.Getenv(\"ES_HOST\"),\n\t\t\tItemServiceURL: os.Getenv(\"ITEM_SERVICE_URL\"),\n\t\t}\n\t*/\n}", "func loadTargetApis() (Configs, error) {\n\tvar configs Configs\n\t//allApps := false\n\n\traw, err := ioutil.ReadFile(*configFile)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn configs, err\n\t}\n\n\tjson.Unmarshal(raw, &configs)\n\n\treturn configs, err\n}", "func api(api API) []string {\n\turi := api.URI\n\trequire(\"api\", uri)\n\treturn []string{\"api\", uri}\n}", "func loadInMicroServiceURL() {\n\t//Check to see if ENV Creds are available first\n\t_, ok := os.LookupEnv(\"CRUD_URL\")\n\tif !ok {\n\t\tmessage := \"This ENV Variable is not present: \" + \"CRUD_URL\"\n\t\tpanic(message)\n\t}\n\t_, ok2 := os.LookupEnv(\"TEXT_API\")\n\tif !ok2 {\n\t\tmessage := \"This ENV Variable is not present: \" + \"TEXT_API\"\n\t\tpanic(message)\n\t}\n\n\tmongoCrudURL = os.Getenv(\"CRUD_URL\")\n\ttextAPIURL = os.Getenv(\"TEXT_API\")\n}", "func (srv *Server) initAPI(addr string) {\n\tmux := http.NewServeMux()\n\n\t// 404 Calls\n\thandleHTTPRequest(mux, \"/\", srv.unrecognizedCallHandler)\n\n\t// Consensus API Calls\n\thandleHTTPRequest(mux, \"/consensus/status\", srv.consensusStatusHandler)\n\thandleHTTPRequest(mux, \"/consensus/synchronize\", srv.consensusSynchronizeHandler)\n\n\t// Daemon API Calls\n\thandleHTTPRequest(mux, \"/daemon/stop\", srv.daemonStopHandler)\n\thandleHTTPRequest(mux, \"/daemon/updates/apply\", srv.daemonUpdatesApplyHandler)\n\thandleHTTPRequest(mux, \"/daemon/updates/check\", srv.daemonUpdatesCheckHandler)\n\n\t// Debugging API Calls\n\thandleHTTPRequest(mux, \"/debug/constants\", srv.debugConstantsHandler)\n\thandleHTTPRequest(mux, \"/debug/mutextest\", srv.mutexTestHandler)\n\n\t// Gateway API Calls\n\thandleHTTPRequest(mux, \"/gateway/status\", srv.gatewayStatusHandler)\n\thandleHTTPRequest(mux, \"/gateway/peers/add\", srv.gatewayPeersAddHandler)\n\thandleHTTPRequest(mux, \"/gateway/peers/remove\", srv.gatewayPeersRemoveHandler)\n\n\t// Host API Calls\n\thandleHTTPRequest(mux, \"/host/announce\", srv.hostAnnounceHandler)\n\thandleHTTPRequest(mux, \"/host/configure\", srv.hostConfigureHandler)\n\thandleHTTPRequest(mux, \"/host/status\", srv.hostStatusHandler)\n\n\t// HostDB API Calls\n\thandleHTTPRequest(mux, \"/hostdb/hosts/active\", srv.hostdbHostsActiveHandler)\n\thandleHTTPRequest(mux, \"/hostdb/hosts/all\", srv.hostdbHostsAllHandler)\n\n\t// Miner API Calls\n\thandleHTTPRequest(mux, \"/miner/start\", srv.minerStartHandler)\n\thandleHTTPRequest(mux, \"/miner/status\", srv.minerStatusHandler)\n\thandleHTTPRequest(mux, \"/miner/stop\", srv.minerStopHandler)\n\thandleHTTPRequest(mux, \"/miner/blockforwork\", srv.minerBlockforworkHandler) // Deprecated\n\thandleHTTPRequest(mux, \"/miner/submitblock\", srv.minerSubmitblockHandler) // Deprecated\n\thandleHTTPRequest(mux, \"/miner/headerforwork\", srv.minerHeaderforworkHandler)\n\thandleHTTPRequest(mux, \"/miner/submitheader\", srv.minerSubmitheaderHandler)\n\n\t// Renter API Calls\n\thandleHTTPRequest(mux, \"/renter/downloadqueue\", srv.renterDownloadqueueHandler)\n\thandleHTTPRequest(mux, \"/renter/files/delete\", srv.renterFilesDeleteHandler)\n\thandleHTTPRequest(mux, \"/renter/files/download\", srv.renterFilesDownloadHandler)\n\thandleHTTPRequest(mux, \"/renter/files/list\", srv.renterFilesListHandler)\n\thandleHTTPRequest(mux, \"/renter/files/load\", srv.renterFilesLoadHandler)\n\thandleHTTPRequest(mux, \"/renter/files/loadascii\", srv.renterFilesLoadAsciiHandler)\n\thandleHTTPRequest(mux, \"/renter/files/rename\", srv.renterFilesRenameHandler)\n\thandleHTTPRequest(mux, \"/renter/files/share\", srv.renterFilesShareHandler)\n\thandleHTTPRequest(mux, \"/renter/files/shareascii\", srv.renterFilesShareAsciiHandler)\n\thandleHTTPRequest(mux, \"/renter/files/upload\", srv.renterFilesUploadHandler)\n\thandleHTTPRequest(mux, \"/renter/status\", srv.renterStatusHandler) // TODO: alter\n\n\t// TransactionPool API Calls\n\thandleHTTPRequest(mux, \"/transactionpool/transactions\", srv.transactionpoolTransactionsHandler)\n\n\t// Wallet API Calls\n\thandleHTTPRequest(mux, \"/wallet/address\", srv.walletAddressHandler)\n\thandleHTTPRequest(mux, \"/wallet/send\", srv.walletSendHandler)\n\thandleHTTPRequest(mux, \"/wallet/status\", srv.walletStatusHandler)\n\n\t// create graceful HTTP server\n\tsrv.apiServer = &graceful.Server{\n\t\tTimeout: apiTimeout,\n\t\tServer: &http.Server{Addr: addr, Handler: mux},\n\t}\n}", "func loadAPIEndpoints(router router.Router, repo api.Repository, ntf notifier.Notifier, guard jwt.Guard) {\n\tlog.Debug(\"Loading API Endpoints\")\n\n\t// Apis endpoints\n\thandler := api.NewController(repo, ntf)\n\tgroup := router.Group(\"/apis\")\n\tgroup.Use(jwt.NewMiddleware(guard).Handler)\n\t{\n\t\tgroup.GET(\"/\", handler.Get())\n\t\tgroup.GET(\"/{name}\", handler.GetBy())\n\t\tgroup.POST(\"/\", handler.Post())\n\t\tgroup.PUT(\"/{name}\", handler.PutBy())\n\t\tgroup.DELETE(\"/{name}\", handler.DeleteBy())\n\t}\n}", "func Load(middleware ...gin.HandlerFunc) http.Handler {\n\te := gin.New()\n\te.Use(gin.Recovery())\n\n\tfs := http.FileServer(http.Dir(\"/fileserver\"))\n\te.GET(\"/static/*filepath\", func(c *gin.Context) {\n\t\tfs.ServeHTTP(c.Writer, c.Request)\n\t})\n\n\te.Use(middleware...)\n\te.Use(session.SetUser())\n\te.Use(token.Refresh)\n\n\te.GET(\"/login\", api.ShowLogin)\n\te.GET(\"/logout\", api.GetLogout)\n\n\tauth := e.Group(\"/authorize\")\n\t{\n\t\tauth.GET(\"\", api.GetLogin)\n\t\tauth.POST(\"\", api.GetLogin)\n\t\tauth.POST(\"/token\", api.GetLoginToken)\n\t}\n\n\tdisconf := e.Group(\"/api/disconf\")\n\t{\n\t\tdisconf.Use(session.MustAdmin())\n\t\tdisconf.POST(\"/push\", api.DisConfPush)\n\t\tdisconf.GET(\"/pull\", api.DisConfPull)\n\t\tdisconf.GET(\"/search\", api.DisConfList)\n\t\tdisconf.DELETE(\"/delete\", api.DisConfDel)\n\t}\n\n\tbuildpack := e.Group(\"/api/buildpack\")\n\t{\n\t\tbuildpack.Use(session.MustAdmin())\n\t\tbuildpack.POST(\"/import\", api.BuildpackImport)\n\t\tbuildpack.GET(\"/search\", api.BuildpackList)\n\t\tbuildpack.DELETE(\"/delete\", api.BuildpackDel)\n\t\tbuildpack.POST(\"/dockerfile/push\", api.BuildpackDockerfilePush)\n\t\tbuildpack.GET(\"/dockerfile/pull\", api.BuildpackDockerfilePull)\n\t\tbuildpack.GET(\"/image/push\", api.BuildpackImagePush)\n\t}\n\treturn e\n}", "func API(w http.ResponseWriter, r *http.Request, cfg cli.Config) {\n\tvar f = mux.Vars(r)[\"name\"]\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tswitch f {\n\tcase \"ping\":\n\t\tping(w, r, &cfg)\n\tcase \"init.trace\":\n\t\tinitTrace(w, r, &cfg)\n\tcase \"get.trace\":\n\t\tgetTrace(w, r)\n\tcase \"close.trace\":\n\t\tcloseTrace(w, r)\n\tcase \"geo\":\n\t\tgetGeo(w, r)\n\t}\n}", "func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {\n\t// Middlewares.\n\tg.Use(gin.Recovery())\n\tg.Use(middleware.Options)\n\tg.Use(middleware.Secure)\n\tg.Static(\"/packgages\", \"/root/widget_storage\")\n\tg.Use(middleware.NoCache)\n\tg.Use(mw...)\n\t// 404 Handler.\n\tg.NoRoute(func(c *gin.Context) {\n\t\tc.String(http.StatusNotFound, \"The incorrect API route.\")\n\t})\n\tapiv1 := g.Group(\"/api/v1\")\n\t{\n\t\tapiv1.POST(\"user\", user.Create) // 创建用户\n\t\tapiv1.DELETE(\"user/:id\", user.Delete) // 删除用户\n\t\tapiv1.PUT(\"user/:id\", user.Update) // 更新用户\n\t\tapiv1.GET(\"user\", user.List) // 用户列表\n\t\tapiv1.GET(\"user/:username\", user.Get) // 获取指定用户的详细信息\n\n\t\tapiv1.POST(\"page\", page.Create) // 创建页面\n\t\tapiv1.PUT(\"page/:id\", page.Update) // 更新页面\n\t\tapiv1.POST(\"pageList\", page.List) // 更新页面\n\t\tapiv1.GET(\"page/:id\", page.Get) // 获取指定用户的详细信息\n\t\tapiv1.GET(\"getUploadToken\", page.UploadToken) // 获取指定用户的详细信息\n\t\tapiv1.GET(\"projectList\", page.ProjectList) // 构建页面\n\t\tapiv1.GET(\"projectDelete/:id\", page.ProjectDelete) // 构建页面\n\t\tapiv1.GET(\"build/:id\", page.Build) // 构建页面\n\t\tapiv1.GET(\"widgetList\", page.GetWidgetList) // 获取挂件列表\n\t\tapiv1.GET(\"pageWidgetsVersion/:id\", page.GetPageWidgetsVersion) // 获取页面挂件版本信息\n\t\tapiv1.POST(\"pushPageResource/:id\", page.PushPageResource) // 更新组件版本信息\n\t\tapiv1.POST(\"pullPageResource/:id\", page.PullPageResource) // 更新组件版本信息\n\t\tapiv1.GET(\"getPageResource/:id\", page.GetPageResource) // 更新组件版本信息\n\t\tapiv1.POST(\"updateWidgetVersion\", page.Version) // 更新组件版本信息\n\t}\n\t// The health check handlers\n\tsvcd := g.Group(\"/sd\")\n\t{\n\t\tsvcd.GET(\"/health\", sd.HealthCheck)\n\t\tsvcd.GET(\"/disk\", sd.DiskCheck)\n\t\tsvcd.GET(\"/cpu\", sd.CPUCheck)\n\t\tsvcd.GET(\"/ram\", sd.RAMCheck)\n\t}\n\n\treturn g\n}", "func initAPI() {\n\t// 1. init router\n\tr := chi.NewRouter()\n\tr.Post(\"/sub\", subscribe)\n\tr.Post(\"/unsub\", unsubscribe)\n\tr.Post(\"/pub\", publish)\n\tr.Post(\"/unpub\", unpublish)\n\n\t_ = dubbologger.InitLog(path.Join(logPath, \"dubbo.log\"))\n\n\t// FIXME make port configurable\n\tutils.GoWithRecover(func() {\n\t\tif err := http.ListenAndServe(\":\"+apiPort, r); err != nil {\n\t\t\tlog.DefaultLogger.Infof(\"auto write config when updated\")\n\t\t}\n\t}, nil)\n\n\t// 2. init dubbo router\n\tinitRouterManager()\n}", "func (suite *TestSuite) Test_API_Types() {\n\trouter, config := LoadAPI()\n\tauth := config.AuthenticationToken\n\tsuite.Equal(config.Port, \":44889\")\n\t_ = performRequest(router, \"GET\", \"/v1/types?auth=\"+auth)\n}", "func loadAPIEndpoints(router router.Router, authMiddleware *jwt.Middleware, loader *api.Loader) {\n\tlog.Debug(\"Loading API Endpoints\")\n\n\t// Apis endpoints\n\thandler := api.NewController(loader)\n\tgroup := router.Group(\"/apis\")\n\tgroup.Use(authMiddleware.Handler)\n\t{\n\t\tgroup.GET(\"\", handler.Get())\n\t\tgroup.POST(\"\", handler.Post())\n\t\tgroup.GET(\"/:id\", handler.GetBy())\n\t\tgroup.PUT(\"/:id\", handler.PutBy())\n\t\tgroup.DELETE(\"/:id\", handler.DeleteBy())\n\t}\n}", "func Load() error {\n\tserver = createServer()\n\tlogrus.Infof(\"HTTP server is listening on '%s'\", server.Addr)\n\tif err := server.ListenAndServe(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start HTTP server: %s\", err)\n\t}\n\treturn nil\n}", "func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {\n\t// Middlewares.\n\tg.Use(gin.Recovery())\n\tg.Use(middleware.NoCache)\n\tg.Use(middleware.Options)\n\tg.Use(middleware.Secure)\n\tg.Use(mw...)\n\t// 404 Handler.\n\tg.NoRoute(func(c *gin.Context) {\n\t\tc.String(http.StatusNotFound, \"The incorrect API route.\")\n\t})\n\n\tg.POST(\"/api/v1/login\", user.Login)\n\n\tu := g.Group(\"/api/v1/user\")\n\tu.Use(middleware.AuthMiddleware())\n\t{\n\t\tu.GET(\"\", user.Get)\n\t\tu.PUT(\"\", user.Update)\n\t}\n\n\tmatterRouter := g.Group(\"api/v1/matter\")\n\tmatterRouter.Use(middleware.AuthMiddleware())\n\t{\n\t\tmatterRouter.POST(\"\", matter.Create)\n\t\tmatterRouter.GET(\"\", matter.List)\n\t\tmatterRouter.GET(\"/:id\", matter.Get)\n\t\tmatterRouter.PUT(\"/:id\", matter.Update)\n\t\tmatterRouter.DELETE(\"/:id\", matter.Delete)\n\t\tmatterRouter.PUT(\"/:id/finish\", matter.Finish)\n\t}\n\n\t// swagger\n\tg.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\n\t// The health check handlers\n\tsvcd := g.Group(\"/sd\")\n\t{\n\t\tsvcd.GET(\"/health\", sd.HealthCheck)\n\t\tsvcd.GET(\"/disk\", sd.DiskCheck)\n\t\tsvcd.GET(\"/cpu\", sd.CPUCheck)\n\t\tsvcd.GET(\"/ram\", sd.RAMCheck)\n\t}\n\n\treturn g\n}", "func (openapi *Openapi) LoadOpenAPI() (router *openapi3filter.Router, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\trouter = nil\n\t\t\tif e, ok := r.(error); ok {\n\t\t\t\terr = errors.Wrap(e, \"Caught panic while trying to load\")\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"Caught panic while trying to load\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tloader := openapi3.NewSwaggerLoader()\n\tloader.IsExternalRefsAllowed = true\n\n\tvar u *url.URL\n\tu, err = url.Parse(openapi.Request.RequestURI)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tswagger, err := loader.LoadSwaggerFromDataWithPath(openapi.Doc, u)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Create a new router using the OpenAPI document's declared paths.\n\trouter = openapi3filter.NewRouter().WithSwagger(swagger)\n\n\treturn\n}", "func InitializeAPI() {\n\tlog.Println(\"Starting Up Server...\")\n\trouter := mux.NewRouter()\n\tlog.Println(\"Server Online\")\n\n\trouter.HandleFunc(\"/stops\", models.GetStops).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/id/{stop_id}\", models.GetStop).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/stop_name/{stop_name}\", models.GetStopByName).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/stop_name_fuzzy/{stop_name}\", models.GetStopByFuzzyName).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/operator/{operator_name}\", models.GetStopsByOperator).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/distance\", models.GetStopsByDistance).Methods(\"GET\")\n\trouter.HandleFunc(\"/stops/distance/{stop_id}\", models.GetNearbyStopsByID).Methods(\"GET\")\n\n\n\thttp.ListenAndServe(\":8000\", router)\n\n}", "func Load() {\n\n\tdeveloper :=\n\t\tbeego.NewNamespace(\"/developer\",\n\t\t\tbeego.NSRouter(\"\", &developer.Home{}, \"GET:Display\"),\n\t\t\tdata.Get(),\n\t\t\tapi.Get(),\n\t\t\ttools.Get(),\n\t\t)\n\n\tbeego.AddNamespace(developer)\n}", "func init() {\n\tRegister(\"http\", StartHTTP)\n}", "func (Http) RestObjects() map[string]sophos.RestObject { return defsHttp }", "func InitAPIs() {\n\tapis := make(apiSet, 0)\n\n\tcmcFactory := CoinMarketCapFactory{}\n\tcmcConf, ok := apiConfigs[sourceNameCoinMarketCap]\n\tif !ok {\n\t\tlogrus.Warning(\"can't find key:\", sourceNameCoinMarketCap, \", please check APIconfig.json\")\n\t} else {\n\t\tcmc, _ := cmcFactory.Create(cmcConf.Auth)\n\t\tapis = append(apis, cmc)\n\t}\n\n\tcgFactory := CoinGeckoFactory{}\n\tcgConf, ok := apiConfigs[sourceNameCoinGecko]\n\tif !ok {\n\t\tlogrus.Warning(\"can't find key:\", sourceNameCoinGecko, \", please check APIconfig.json\")\n\t} else {\n\t\tcg, _ := cgFactory.Create(cgConf.Auth)\n\t\tapis = append(apis, cg)\n\t}\n\tcdFactory := CoinDeskFactory{}\n\tcdConf, ok := apiConfigs[sourceNameCoinDesk]\n\tif !ok {\n\t\tlogrus.Warning(\"can't find key:\", sourceNameCoinDesk, \", please check APIconfig.json\")\n\t} else {\n\t\tcd, _ := cdFactory.Create(cdConf.Auth)\n\t\tapis = append(apis, cd)\n\t}\n\n\tapis.firstCall()\n\n\tfor _, v := range apis {\n\t\tgo runTicker(v)\n\t}\n}", "func InitAPI() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\t// router.HandleFunc(\"/lastfive\", getData)\n\trouter.Handle(\"/prices\", PriceHandler()).Methods(\"GET\")\n\tlog.Println(\"Server running\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", router))\n}", "func (Http) Definition() sophos.Definition { return *defHttp }", "func (env *Env) startAPI() {\n\tserver := registerRoutes(env)\n\terr := server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func LoadHTTPRoutes() {\n\tr := setupRouter()\n\terr := r.Run()\n\tpanic(err)\n}", "func (m *APILoader) RegisterAPI(def *api.Definition) {\n\tlogger := log.WithField(\"api_name\", def.Name)\n\tlogger.Debug(\"Starting RegisterAPI\")\n\n\tactive, err := def.Validate()\n\tif false == active && err != nil {\n\t\tlogger.WithError(err).Error(\"Validation errors\")\n\t}\n\n\tif false == def.Active {\n\t\tlogger.Warn(\"API is not active, skipping...\")\n\t\tactive = false\n\t}\n\n\tif active {\n\t\trouterDefinition := proxy.NewRouterDefinition(def.Proxy)\n\n\t\tfor _, plg := range def.Plugins {\n\t\t\tl := logger.WithField(\"name\", plg.Name)\n\n\t\t\tisValid, err := plugin.ValidateConfig(plg.Name, plg.Config)\n\t\t\tif !isValid || err != nil {\n\t\t\t\tl.WithError(err).Error(\"Plugin configuration is invalid\")\n\t\t\t}\n\n\t\t\tif plg.Enabled {\n\t\t\t\tl.Debug(\"Plugin enabled\")\n\n\t\t\t\tsetup, err := plugin.DirectiveAction(plg.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Error(\"Error loading plugin\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = setup(routerDefinition, plg.Config)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Error(\"Error executing plugin\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tl.Debug(\"Plugin not enabled\")\n\t\t\t}\n\t\t}\n\n\t\tif len(def.Proxy.Hosts) > 0 {\n\t\t\trouterDefinition.AddMiddleware(middleware.NewHostMatcher(def.Proxy.Hosts).Handler)\n\t\t}\n\n\t\t// Add middleware to insert tags to context\n\t\ttags := []tag.Mutator{\n\t\t\ttag.Insert(obs.KeyListenPath, def.Proxy.ListenPath),\n\t\t}\n\t\trouterDefinition.AddMiddleware(middleware.NewStatsTagger(tags).Handler)\n\n\t\tm.register.Add(routerDefinition)\n\t\tlogger.Debug(\"API registered\")\n\t} else {\n\t\tlogger.WithError(err).Warn(\"API URI is invalid or not active, skipping...\")\n\t}\n}", "func API(shutdown chan os.Signal, log *log.Logger) http.Handler {\n\n\t// Construct the web.App which holds all routes as well as common Middleware.\n\tapp := web.NewApp(shutdown, log, webcontext.Env_Dev, mid.Logger(log))\n\n\tapp.Handle(\"GET\", \"/swagger/\", saasSwagger.WrapHandler)\n\tapp.Handle(\"GET\", \"/swagger/*\", saasSwagger.WrapHandler)\n\n\t/*\n\t\tOr can use SaasWrapHandler func with configurations.\n\t\turl := saasSwagger.URL(\"http://localhost:1323/swagger/doc.json\") //The url pointing to API definition\n\t\te.GET(\"/swagger/*\", saasSwagger.SaasWrapHandler(url))\n\t*/\n\n\treturn app\n}", "func (m *APILoader) RegisterAPIs(cfgs []*api.Definition) {\n\tfor _, spec := range cfgs {\n\t\tm.RegisterAPI(spec)\n\t}\n}", "func HTTPInitDocumentation(r *gin.Engine) {\n\tbaseURL, ok := os.LookupEnv(\"HTTP_DOMAIN\")\n\tif !ok {\n\t\tpanic(\"http-docs-error\")\n\t}\n\turl := ginSwagger.URL(fmt.Sprintf(\"%s/swagger/doc.json\", baseURL))\n\tr.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler, url))\n}", "func GETapi(w http.ResponseWriter, request *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tURLs := mux.Vars(request)\n\tif len(URLs) != 0 {\n\t\thttp.Error(w, \"400 - Bad Request!\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tmetaInfo := &MetaInfo{}\n\tmetaInfo.Uptime = FormatSince(startTime)\n\tmetaInfo.Info = \"Service for IGC tracks\"\n\tmetaInfo.Version = \"version 1.0\"\n\n\tjson.NewEncoder(w).Encode(metaInfo)\n}", "func InitAPI() {\n\t// we need to do that to use the library game later\n\trand.Seed(time.Now().Unix())\n}", "func Init() {\n\t// default :\n\t// micro health go.micro.api.gin call this function.\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new( examples )\n\tclient.DefaultClient = client.NewClient( client.Registry(etcdv3.DefaultEtcdRegistry) )\n\te.cl = example.NewPreferencesService(conf.ApiConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\t// To register others...\n\n\tlog.Info(\"Modules init finished.\")\n}", "func (httpAPI *HTTPAPIService) Run() error {\n\tlog.Println(\"running HTTP API service\")\n\n\t// create APIs\n\tlegacyAPI, err := api.ComposeAPI(api.HTTPClientSettings{\n\t\tURI: httpAPI.cfg.LegacyNode.URI,\n\t\tClient: &http.Client{\n\t\t\tTimeout: httpAPI.cfg.LegacyNode.Timeout,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to build legacy API: %w\", err)\n\t}\n\n\tc2API := iotago.NewNodeHTTPAPIClient(httpAPI.cfg.C2Node.URI,\n\t\tiotago.WithNodeHTTPAPIClientHTTPClient(&http.Client{Timeout: httpAPI.cfg.C2Node.Timeout}),\n\t)\n\n\thttpAPI.e.GET(\"/state\", func(c echo.Context) error {\n\n\t\tstate := &StateResponse{}\n\n\t\ttreasuryRes, err := c2API.Treasury(context.Background())\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tstate.TreasuryTokens = treasuryRes.Amount\n\t\t\tstate.TokensMigrated = consts.TotalSupply - treasuryRes.Amount\n\t\tdefault:\n\t\t\tstate.TreasuryTokens = consts.TotalSupply\n\t\t}\n\n\t\tlegacyNodeInfo, err := legacyAPI.GetNodeInfo()\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"unable to query node info from legacy node: %v\", err))\n\t\t}\n\n\t\tledgerQueryRes, err := common.QueryLedgerState(httpAPI.cfg.LegacyNode.URI, int(legacyNodeInfo.LatestSolidSubtangleMilestoneIndex))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"unable to query ledger state from legacy node for milestone %d: %v\", legacyNodeInfo.LatestSolidSubtangleMilestoneIndex, err))\n\t\t}\n\n\t\tvar totalLocked uint64\n\t\tfor addr, balance := range ledgerQueryRes.Balances {\n\t\t\tif balance < uint64(httpAPI.cfg.MinTokenAmountForMigration) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, err := address.ParseMigrationAddress(addr); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotalLocked += balance\n\t\t\tstate.LegacyFundsLocked.MigratedAddressesTotal++\n\t\t}\n\n\t\tstate.LegacyFundsLocked.TokensTotal = totalLocked\n\t\tstate.LegacyFundsLocked.TokensPercentageOfTotalSupply = math.Floor((float64(totalLocked)/float64(consts.TotalSupply))*100) / 100\n\n\t\treturn c.JSON(http.StatusOK, state)\n\t})\n\n\thttpAPI.e.GET(\"/receipts/integrity\", func(c echo.Context) error {\n\t\treceipts, err := c2API.Receipts(context.Background())\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"unable to retrieve receipts from C2 node: %v\", err))\n\t\t}\n\n\t\tseenTailTx := make(map[string]struct{})\n\t\tfor _, receipt := range receipts {\n\t\t\tfor _, seri := range receipt.Receipt.Funds {\n\t\t\t\tentry := seri.(*iotago.MigratedFundsEntry)\n\t\t\t\tif _, seen := seenTailTx[string(entry.TailTransactionHash[:])]; seen {\n\t\t\t\t\ttailTxTrytes := b1t6.EncodeToTrytes(entry.TailTransactionHash[:])\n\t\t\t\t\ttailTxHex := hex.EncodeToString(entry.TailTransactionHash[:])\n\t\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"tail tx %s / %s was migrated multiple times\", tailTxTrytes, tailTxHex))\n\t\t\t\t}\n\t\t\t\tseenTailTx[string(entry.TailTransactionHash[:])] = struct{}{}\n\t\t\t}\n\t\t}\n\n\t\treturn c.String(http.StatusOK, \"integrity ok\")\n\t})\n\n\thttpAPI.e.GET(\"/recentlyLocked/:numEntries\", func(c echo.Context) error {\n\t\tnumEntriesWanted, err := strconv.Atoi(c.Param(\"numEntries\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"unable to parse numEntries parameter: %v\", err))\n\t\t}\n\n\t\t// use the latest solid milestone as a base and then go back a max amount of milestones to collect entries\n\t\tnodeInfo, err := legacyAPI.GetNodeInfo()\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"unable to parse numEntries parameter: %v\", err))\n\t\t}\n\n\t\ttarget := nodeInfo.LatestSolidSubtangleMilestoneIndex - int64(httpAPI.cfg.MaxMilestonesToQueryForEntries)\n\t\tswitch {\n\t\tcase target < 0:\n\t\t\ttarget = 0\n\t\t}\n\n\t\t// we can't check for the pruning index since it is not part of the legacy node info\n\t\tvar funds []Funds\n\n\tout:\n\t\tfor msIndex := nodeInfo.LatestSolidSubtangleMilestoneIndex; msIndex > target; msIndex-- {\n\t\t\tres, err := common.QueryLedgerDiffExtended(httpAPI.cfg.LegacyNode.URI, int(msIndex))\n\t\t\tif err != nil {\n\t\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"unable to extended ledger diff for milestone %d: %v\", msIndex, err))\n\t\t\t}\n\n\t\t\tfor _, tx := range res.ConfirmedTxWithValue {\n\t\t\t\tif tx.Value <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tedAddr, err := address.ParseMigrationAddress(tx.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfunds = append(funds, Funds{\n\t\t\t\t\tTailTransactionHash: tx.TailTxHash,\n\t\t\t\t\tValue: uint64(tx.Value),\n\t\t\t\t\tTargetEd25519Address: hex.EncodeToString(edAddr[:]),\n\t\t\t\t})\n\n\t\t\t\tif len(funds) == numEntriesWanted {\n\t\t\t\t\tbreak out\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn c.JSON(http.StatusOK, funds)\n\t})\n\n\thttpAPI.e.GET(\"/recentlyMinted/:numReceipts\", func(c echo.Context) error {\n\t\treceipts, err := c2API.Receipts(context.Background())\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"unable to retrieve receipts from C2 node: %v\", err))\n\t\t}\n\n\t\tnumReceiptsWanted, err := strconv.Atoi(c.Param(\"numReceipts\"))\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"unable to parse numReceipts parameter: %v\", err))\n\t\t}\n\n\t\tif len(receipts) == 0 {\n\t\t\treturn c.JSON(http.StatusOK, make([]*RecentReceipt, 0))\n\t\t}\n\n\t\trecentReceipts := make([]*RecentReceipt, numReceiptsWanted)\n\t\tsort.Slice(receipts, func(i, j int) bool {\n\t\t\treturn receipts[i].MilestoneIndex > receipts[j].MilestoneIndex\n\t\t})\n\n\t\tif numReceiptsWanted > len(receipts) {\n\t\t\tnumReceiptsWanted = len(receipts)\n\t\t}\n\n\t\tfor i := 0; i < numReceiptsWanted; i++ {\n\t\t\trecentReceipts[i] = &RecentReceipt{\n\t\t\t\tEmbeddedMilestoneIndex: receipts[i].MilestoneIndex,\n\t\t\t\tLegacyMilestoneIndex: receipts[i].Receipt.MigratedAt,\n\t\t\t\tFunds: func() []Funds {\n\t\t\t\t\tfunds := make([]Funds, len(receipts[i].Receipt.Funds))\n\t\t\t\t\tfor j, f := range receipts[i].Receipt.Funds {\n\t\t\t\t\t\tentry := f.(*iotago.MigratedFundsEntry)\n\t\t\t\t\t\taddr := entry.Address.(*iotago.Ed25519Address)\n\t\t\t\t\t\tfunds[j] = Funds{\n\t\t\t\t\t\t\tTailTransactionHash: hex.EncodeToString(entry.TailTransactionHash[:]),\n\t\t\t\t\t\t\tValue: entry.Deposit,\n\t\t\t\t\t\t\tTargetEd25519Address: hex.EncodeToString(addr[:]),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn funds\n\t\t\t\t}(),\n\t\t\t}\n\t\t}\n\n\t\treturn c.JSON(http.StatusOK, recentReceipts)\n\t})\n\n\tif err := httpAPI.e.Start(httpAPI.listenAddr); err != nil {\n\t\tif errors.Is(err, http.ErrServerClosed) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func initCommon(c *cli.Context) {\n\tvar (\n\t\terr error\n\t\t//resp *resty.Response\n\t\tsession tls.ClientSessionCache\n\t)\n\tif err = configSetup(c); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to read the configuration: \"+\n\t\t\t\"%s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// setup our REST client\n\tClient = resty.New().SetRESTMode().\n\t\t//SetTimeout(Cfg.Run.TimeoutResty). XXX Bad client setting?\n\t\tSetDisableWarn(true).\n\t\tSetHeader(`User-Agent`, fmt.Sprintf(\"%s %s\", c.App.Name, c.App.Version)).\n\t\tSetHostURL(Cfg.Run.SomaAPI.String())\n\n\tif Cfg.Run.SomaAPI.Scheme == `https` {\n\t\tsession = tls.NewLRUClientSessionCache(64)\n\n\t\t// SetTLSClientConfig replaces, SetRootCertificate updates the\n\t\t// tls configuration - option ordering is important\n\t\tClient = Client.SetTLSClientConfig(&tls.Config{\n\t\t\tServerName: strings.SplitN(Cfg.Run.SomaAPI.Host, `:`, 2)[0],\n\t\t\tClientSessionCache: session,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tMaxVersion: tls.VersionTLS12,\n\t\t\tCipherSuites: []uint16{\n\t\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\t},\n\t\t}).SetRootCertificate(Cfg.Run.CertPath)\n\t}\n\n\t/*\n\t\t// check configured API\n\t\tif resp, err = Client.R().Head(`/`); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error tasting the API endpoint: %s\\n\",\n\t\t\t\terr.Error())\n\t\t} else if resp.StatusCode() != 204 {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error, API Url returned %d instead of 204.\"+\n\t\t\t\t\" Sure this is SOMA?\\n\", resp.StatusCode())\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// check who we talked to\n\t\tif resp.Header().Get(`X-Powered-By`) != `SOMA Configuration System` {\n\t\t\tfmt.Fprintf(os.Stderr, `Just FYI, at the end of that API URL`+\n\t\t\t\t` is not SOMA`)\n\t\t\tos.Exit(1)\n\t\t}\n\t*/\n\n\t// embed configuration in boltdb wrapper\n\tstore.Configure(\n\t\tCfg.Run.PathBoltDB,\n\t\tos.FileMode(uint32(Cfg.Run.ModeBoltDB)),\n\t\t&bolt.Options{Timeout: Cfg.Run.TimeoutBoltDB},\n\t)\n\n\t// configure adm client library\n\tadm.ConfigureClient(Client)\n\tadm.ActivateAsyncWait(Cfg.AsyncWait)\n\tadm.AutomaticJobSave(Cfg.JobSave)\n\tadm.ConfigureCache(&store)\n}", "func LoadAPIConfig() error {\n\treturn loadConfig([]func() error{\n\t\tloadAppConfig,\n\t\tloadDBConfig,\n\t})\n}", "func loadAPIConfiguration(file string) (JSONConfigurationAPI, error) {\n\tvar config JSONConfigurationAPI\n\t// Load file and read config\n\tviper.SetConfigFile(file)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\treturn config, err\n\t}\n\t// API values\n\tapiRaw := viper.Sub(projectName)\n\tif apiRaw == nil {\n\t\treturn config, fmt.Errorf(\"could not find key %s\", projectName)\n\t}\n\tif err := apiRaw.Unmarshal(&config); err != nil {\n\t\treturn config, err\n\t}\n\t// No errors!\n\treturn config, nil\n}", "func Load(r *mux.Router) {\n\tr.HandleFunc(\"/\", homeHandler).Methods(http.MethodGet)\n}", "func (Http) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/http/cff_action/\",\n\t\t\"/api/objects/http/cff_action/{ref}\",\n\t\t\"/api/objects/http/cff_action/{ref}/usedby\",\n\t\t\"/api/objects/http/cff_profile/\",\n\t\t\"/api/objects/http/cff_profile/{ref}\",\n\t\t\"/api/objects/http/cff_profile/{ref}/usedby\",\n\t\t\"/api/objects/http/device_auth/\",\n\t\t\"/api/objects/http/device_auth/{ref}\",\n\t\t\"/api/objects/http/device_auth/{ref}/usedby\",\n\t\t\"/api/objects/http/domain_regex/\",\n\t\t\"/api/objects/http/domain_regex/{ref}\",\n\t\t\"/api/objects/http/domain_regex/{ref}/usedby\",\n\t\t\"/api/objects/http/exception/\",\n\t\t\"/api/objects/http/exception/{ref}\",\n\t\t\"/api/objects/http/exception/{ref}/usedby\",\n\t\t\"/api/objects/http/group/\",\n\t\t\"/api/objects/http/group/{ref}\",\n\t\t\"/api/objects/http/group/{ref}/usedby\",\n\t\t\"/api/objects/http/local_site/\",\n\t\t\"/api/objects/http/local_site/{ref}\",\n\t\t\"/api/objects/http/local_site/{ref}/usedby\",\n\t\t\"/api/objects/http/lsl_tag/\",\n\t\t\"/api/objects/http/lsl_tag/{ref}\",\n\t\t\"/api/objects/http/lsl_tag/{ref}/usedby\",\n\t\t\"/api/objects/http/pac_file/\",\n\t\t\"/api/objects/http/pac_file/{ref}\",\n\t\t\"/api/objects/http/pac_file/{ref}/usedby\",\n\t\t\"/api/objects/http/parent_proxy/\",\n\t\t\"/api/objects/http/parent_proxy/{ref}\",\n\t\t\"/api/objects/http/parent_proxy/{ref}/usedby\",\n\t\t\"/api/objects/http/profile/\",\n\t\t\"/api/objects/http/profile/{ref}\",\n\t\t\"/api/objects/http/profile/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_category/\",\n\t\t\"/api/objects/http/sp_category/{ref}\",\n\t\t\"/api/objects/http/sp_category/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_subcat/\",\n\t\t\"/api/objects/http/sp_subcat/{ref}\",\n\t\t\"/api/objects/http/sp_subcat/{ref}/usedby\",\n\t}\n}", "func NewAPI(\n\tpromURL string,\n\tproxy *Proxy,\n\treadConfig func() ([]byte, error),\n\tlg logrus.FieldLogger) *API {\n\tw := &API{\n\t\tConfigReload: make(chan *config.Config, 2),\n\t\tTargetReload: make(chan map[string][]*target.Target, 2),\n\t\tEngine: gin.Default(),\n\t\tlg: lg,\n\t\tpromURL: promURL,\n\t\tpromCli: prom.NewClient(promURL),\n\t\tproxy: proxy,\n\t}\n\n\tw.GET(w.path(\"/api/v1/shard/runtimeinfo/\"), api.Wrap(w.lg, w.runtimeInfo))\n\tw.GET(w.path(\"/api/v1/shard/targets/\"), api.Wrap(w.lg, w.getTargets))\n\tw.POST(w.path(\"/api/v1/shard/targets/\"), api.Wrap(w.lg, w.updateTargets))\n\tw.GET(w.path(\"/api/v1/status/config/\"), api.Wrap(lg, func(ctx *gin.Context) *api.Result {\n\t\treturn prom.APIReadConfig(readConfig)\n\t}))\n\tw.POST(w.path(\"/-/reload/\"), api.Wrap(lg, func(ctx *gin.Context) *api.Result {\n\t\treturn prom.APIReloadConfig(readConfig, w.ConfigReload)\n\t}))\n\treturn w\n}", "func LoadEnvs() {\n\tManifestsPath = loadw(\"BROADWAY_MANIFESTS_PATH\")\n\tif ManifestsPath == \"\" {\n\t\tManifestsPath = defaultManifestsPath\n\t}\n\tPlaybooksPath = loadw(\"BROADWAY_PLAYBOOKS_PATH\")\n\tif PlaybooksPath == \"\" {\n\t\tPlaybooksPath = defaultPlaybooksPath\n\t}\n\tAuthBearerToken = loadw(\"BROADWAY_AUTH_TOKEN\")\n\n\tServerHost = loadw(\"HOST\")\n\n\tSlackWebhook = loadw(\"SLACK_WEBHOOK\")\n\tSlackToken = loadw(\"SLACK_VERIFICATION_TOKEN\")\n\n\tK8sServiceHost = loadw(\"KUBERNETES_SERVICE_HOST\")\n\tK8sServicePort = loadw(\"KUBERNETES_PORT_443_TCP_PORT\")\n\tK8sNamespace = loadf(\"KUBERNETES_NAMESPACE\")\n\n\tK8sCertFile = loadw(\"KUBERNETES_CERT_FILE\")\n\tK8sKeyFile = loadw(\"KUBERNETES_KEY_FILE\")\n\tK8sCAFile = loadw(\"KUBERNETES_CA_FILE\")\n\n\tEtcdEndpoints = loadw(\"ETCD_ENDPOINTS\")\n\tEtcdPath = loadw(\"ETCD_PATH\")\n}", "func (config *Config) LoadAPIKey() {\n\tconfig.MasterWorker.APIKeys.OpenExchangeRates = getOpenExchangeRatesAPIKey()\n}", "func newApiDefinitionFromAPI(a utils.API) *api {\n\treturn &api{a.ID, a.Name, a.Context, a.Version, a.Provider,\n\t\ta.LifeCycleStatus}\n}", "func (gorilla Gorilla) Load(req *http.Request, key string, result interface{}) error {\n\tvalue := gorilla.Get(req, key)\n\tif value != \"\" {\n\t\treturn json.Unmarshal([]byte(value), result)\n\t}\n\treturn nil\n}", "func Load() error {\n\treturn def.Load()\n}", "func InitAPI() {\n\tBaseRoutes = &Routes{}\n\tBaseRoutes.Root = mux.NewRouter()\n\tBaseRoutes.Root.Handle(\"/\", http.HandlerFunc(indexHandler))\n\tBaseRoutes.Recipe = BaseRoutes.Root.PathPrefix(\"/recipe\").Subrouter()\n\tBaseRoutes.NeedRecipe = BaseRoutes.Recipe.PathPrefix(\"/{recipe-id:[0-9]+}\").Subrouter()\n\tBaseRoutes.Recipes = BaseRoutes.Root.PathPrefix(\"/recipes\").Subrouter()\n\tInitRecipe()\n}", "func LoadRoute() *gin.Engine {\n\tr := gin.Default()\n\n\t// create controller\n\tvar (\n\t\tsqliteRepo = db.NewSQLiteRepository(\"./dbsocmed.db\")\n\t\trelationController = relation.NewController(sqliteRepo)\n\t)\n\n\tr.Use(Cors())\n\tv1 := r.Group(\"api/v1\")\n\t{\n\t\tv1.POST(\"/friendconnection\", relationController.PostFriendConnection)\n\t\tv1.POST(\"/friendlist\", relationController.PostFriendList)\n\t\tv1.POST(\"/friendcommonlist\", relationController.PostFriendCommonList)\n\t\tv1.POST(\"/friendsubscribe\", relationController.PostFriendSubscribe)\n\t\tv1.POST(\"/friendblock\", relationController.PostFriendBlock)\n\t\tv1.POST(\"/friendupdates\", relationController.PostFriendUpdates)\n\t}\n\n\treturn r\n}", "func loadConfig(r io.Reader) (*whatphone.API, error) {\n\tvar config whatphone.API\n\tvar err error\n\n\terr = json.NewDecoder(r).Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func (h *HTTPApi) Start(router *httprouter.Router) {\n\t// List of datasource_instances on the storage node\n\trouter.GET(\"/v1/datasource_instance\", httputil.LoggingHandler(h.listDatasourceInstance))\n\n\t// Just dump the current meta we have\n\trouter.GET(\"/v1/datasource_instance/:datasource/metadata\", httputil.LoggingHandler(h.showMetadata))\n\n\t// DB Management\n\t// DB sets\n\trouter.GET(\"/v1/datasource_instance/:datasource/database\", httputil.LoggingHandler(h.listDatabase))\n\n\t// DB instance\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname\", httputil.LoggingHandler(h.viewDatabase))\n\trouter.POST(\"/v1/datasource_instance/:datasource/database/:dbname\", httputil.LoggingHandler(h.ensureDatabase))\n\trouter.DELETE(\"/v1/datasource_instance/:datasource/database/:dbname\", httputil.LoggingHandler(h.removeDatabase))\n\n\t// Shard Instances\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance\", httputil.LoggingHandler(h.listShardInstance))\n\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance\", httputil.LoggingHandler(h.viewShardInstance))\n\trouter.POST(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance\", httputil.LoggingHandler(h.ensureShardInstance))\n\trouter.DELETE(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance\", httputil.LoggingHandler(h.removeShardInstance))\n\n\t// Collections\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection\", httputil.LoggingHandler(h.listCollection))\n\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname\", httputil.LoggingHandler(h.viewCollection))\n\trouter.POST(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname\", httputil.LoggingHandler(h.ensureCollection))\n\trouter.DELETE(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname\", httputil.LoggingHandler(h.removeCollection))\n\n\t// TODO: endpoints for index and fields\n\t// Index\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname/indexes\", httputil.LoggingHandler(h.listIndex))\n\n\trouter.GET(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname/indexes/:indexname\", httputil.LoggingHandler(h.viewIndex))\n\trouter.POST(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname/indexes/:indexname\", httputil.LoggingHandler(h.ensureIndex))\n\trouter.DELETE(\"/v1/datasource_instance/:datasource/database/:dbname/shard_instance/:shardinstance/collection/:collectionname/indexes/:indexname\", httputil.LoggingHandler(h.removeIndex))\n\n\trouter.POST(\"/v1/datasource_instance/:datasource/data/raw/:qtype\", httputil.LoggingHandler(h.rawQueryHandler))\n\n\t// TODO: options to enable/disable (or scope to just localhost)\n\trouter.GET(\"/v1/debug/pprof/\", wrapHandler(http.HandlerFunc(pprof.Index)))\n\trouter.GET(\"/v1/debug/pprof/cmdline\", wrapHandler(http.HandlerFunc(pprof.Cmdline)))\n\trouter.GET(\"/v1/debug/pprof/profile\", wrapHandler(http.HandlerFunc(pprof.Profile)))\n\trouter.GET(\"/v1/debug/pprof/symbol\", wrapHandler(http.HandlerFunc(pprof.Symbol)))\n\trouter.GET(\"/v1/debug/pprof/trace\", wrapHandler(http.HandlerFunc(pprof.Trace)))\n\n\t// TODO: wrap a different registry (if we ever want more than one per process)\n\trouter.GET(\"/metrics\", wrapHandler(promhandler.Handler(h.storageNode.registry)))\n}", "func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {\n\t// 使用中间件\n\tg.Use(middleware.NoCache)\n\tg.Use(middleware.Options)\n\tg.Use(middleware.Secure)\n\tg.Use(middleware.Logging())\n\tg.Use(middleware.RequestID())\n\tg.Use(mw...)\n\n\t// 404 Handler.\n\tg.NoRoute(handler.RouteNotFound)\n\tg.NoMethod(handler.RouteNotFound)\n\n\t// 静态资源,主要是图片\n\tg.Static(\"/static\", \"./static\")\n\n\t// swagger api docs\n\tg.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\n\t// pprof router 性能分析路由\n\t// 默认关闭,开发环境下可以打开\n\t// 访问方式: HOST/debug/pprof\n\t// 通过 HOST/debug/pprof/profile 生成profile\n\t// 查看分析图 go tool pprof -http=:5000 profile\n\t// pprof.Register(g)\n\n\t// 认证相关路由\n\tg.POST(\"/v1/register\", user.Register)\n\tg.POST(\"/v1/login\", user.Login)\n\tg.POST(\"/v1/login/phone\", user.PhoneLogin)\n\tg.GET(\"/v1/vcode\", user.VCode)\n\n\t// 用户\n\tg.GET(\"/v1/users/:id\", user.Get)\n\n\tu := g.Group(\"/v1/users\")\n\tu.Use(middleware.AuthMiddleware())\n\t{\n\t\tu.PUT(\"/:id\", user.Update)\n\t\tu.POST(\"/follow\", user.Follow)\n\t\tu.GET(\"/:id/following\", user.FollowList)\n\t\tu.GET(\"/:id/followers\", user.FollowerList)\n\t}\n\n\treturn g\n}", "func Load() {\n\t_ = env.Parse(&RedisConfig)\n\t_ = env.Parse(&MongoConfig)\n}", "func Init() {\n\t// default ..\n\t// micro health go.micro.api.gin call this function..\n\tModules.Router.POST(\"/\", NoModules)\n\tModules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/gin\", NoModules)\n\t// Modules.Router.GET(\"/dbservice\", NoModules)\n\n\t// Examples Begin:micro api --handler=http as proxy, default is rpc .\n\t// Base module router for rest full, Preferences is name of table or tables while Module equals database.\n\t// Call url:curl \"http://localhost:8004/Preferences/GetPreference?user=1\"\n\te := new(examples)\n\t// Init Preferences Server Client\n\te.cl = go_micro_srv_dbservice.NewPreferencesService(conf2.AppConf.SrvName, client.DefaultClient)\n\tModules.Router.GET(\"/Preferences/*action\", e.Preferences)\n\t// Examples End\n\n\t// register other handlers here, each request run in goroutine.\n\n\t// To register others...\n\n\tfmt.Println(\"Modules init finished.\")\n}", "func Load(httpClient *http.Client) {\n\tentitlementService = commonLibEntitlement.NewEntitlementService(\n\t\thttpClient,\n\t\tconfig.Config.EntitlementMsURL,\n\t\tconfig.Config.EntitlementCacheSettings.DataTTLSec,\n\t\tconfig.Config.EntitlementCacheSettings.Size,\n\t)\n}", "func (c *Conf) loadDefault() {\n\tc.Version = \"0.16\"\n\tc.Start = time.Now()\n\tc.TimeFormat = \"2 Jan 2006, 15:04:04\"\n\n\tc.MailSender = \"[email protected]\"\n\n\tc.Parsed.Default = true\n\n\tc.File.Name = \"go-ticket.json\"\n\tc.File.Paths = append(c.File.Paths, \".\", \"../conf\", \"./conf\")\n\n\tc.Addr.Private = \":8080\"\n\n\t// API fragments to bind to handlers.\n\tc.API.QRImage = \"/q/\"\n\tc.API.Ping = \"/ping/\"\n\tc.API.Admin = \"/admin/\"\n\tc.API.Activate = \"/act/\"\n\tc.API.Ticket = \"/tkt/\"\n\tc.API.Logout = \"/logout/\"\n\tc.API.MailTicket = \"/mt/\"\n\n\t// Url QUERY parameters names, no slashes.\n\tc.API.QueryParam.QRText = \"c\"\n\tc.API.QueryParam.Ticket = \"t\"\n\tc.API.QueryParam.ActivationRequestID = \"a\"\n\tc.API.QueryParam.Mail = \"m\"\n\n\tc.Cookie.Name = \"deviceid\"\n\tc.Cookie.MaxAge = 3600 * 24 // 24 h\n\n\tc.Superuser.Name = \"admin\"\n\tc.Superuser.Password = \"changeit\"\n\tc.Superuser.Realm = \"go-ticket\"\n\n\tc.Barcode.Format = common.QR300x300H\n\n\tc.Templates.Paths = append([]string{\".\", \"./tpl\", \"../tpl\"}, c.File.Paths...)\n}", "func SetAPI(url string, secretParam string) {\n\tBaseUrl = url\n\tsecret = secretParam\n}", "func (b *bot) initHTTP() {\n\tif b.HTTP.EnableEcho {\n\t\tb.initEcho()\n\t}\n\n\t// Handle all routing from here.\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tb.HTTP.logger.Printf(\"%s %s from %s\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\t\tif b.HTTP.EnableEcho && r.URL.Path == b.HTTP.EchoRoute && r.Method == b.HTTP.EchoMethod {\n\t\t\tb.echoHandler(w, r)\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tfmt.Fprintf(w, \"404\")\n\t\t}\n\t})\n\n\t// Fire up the server in a goroutine so that we aren't blocking.\n\tgo func() {\n\t\thttp.ListenAndServe(b.HTTP.Address+\":\"+b.HTTP.Port, nil)\n\t\tb.mainWG.Done()\n\t}()\n}", "func API(log *log.Logger) http.Handler {\n\t// func NewHandler(logger *log.Logger, db *sqlx.DB) *Handlers {\n\tapp := web.NewApp(log)\n\n\t// Register helloworld endpoint.\n\ts := Specimen{log: log}\n\tapp.TreeMux.Handle(\"GET\", \"/hello\", s.HelloWorld)\n\treturn app\n}", "func createAPIs() (apis APIs, err error) {\n\n\tparam := os.Getenv(\"OPSMAN\")\n\n\tvar config helpers.OpsManConfig\n\tif err = json.Unmarshal([]byte(param), &config); err == nil {\n\n\t\t// First find the opsman API\n\t\tvar opsMan *helpers.OpsManAPI\n\t\tif opsMan, err = helpers.NewOpsManAPI(config); err == nil {\n\t\t\tapis = APIs{\n\t\t\t\thelpers.None: nil,\n\t\t\t\thelpers.OpsMan: opsMan,\n\t\t\t}\n\n\t\t\tvar api helpers.API\n\t\t\tif api, err = helpers.NewAppsManAPI(opsMan); err == nil {\n\t\t\t\tapis[helpers.AppsMan] = api\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlog.Printf(\"API Error: %s\", err)\n\t}\n\n\treturn apis, err\n}", "func API(build string, shutdown chan os.Signal, log *log.Logger) *web.App {\n\tapp := web.NewApp(shutdown, middleware.Logger(log), middleware.Errors(log), middleware.Metrics(), middleware.Panics(log))\n\n\tcheck := check{\n\t\tlog: log,\n\t}\n\n\tapp.Handle(http.MethodGet, \"/readiness\", check.readiness)\n\treturn app\n}", "func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {\n\t// Middlewares.\n\tg.Use(gin.Recovery())\n\t//g.Use(middleware.NoCache)\n\tg.Use(middleware.Options)\n\tg.Use(middleware.Secure)\n\tg.Use(mw...)\n\t// 404 Handler.\n\tg.NoRoute(func(c *gin.Context) {\n\t\tc.String(http.StatusNotFound, \"The incorrect API route.\")\n\t})\n\t// swagger api docs\n\tg.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\n\t// pprof router\n\tpprof.Register(g)\n\n\t// api for authentication functionalities\n\tg.POST(\"/login\", login.Login)\n\n\t// The user handlers, requiring authentication\n\t//u := g.Group(\"/user\")\n\t//u.Use(middleware.AuthMiddleware())\n\t//{\n\t//\tu.POST(\"\", user.Create)\n\t//\tu.DELETE(\"/:id\", user.Delete)\n\t//\tu.PUT(\"/:id\", user.Update)\n\t//\tu.GET(\"\", user.List)\n\t//\tu.GET(\"/:username\", user.Get)\n\t//}\n\t/////////////////////////////////////////////////////后台 start///////////////////////////////////////////////////////////////////////////\n\tadmin := g.Group(\"/admin/\")\n\t//条件\n\tadmin.GET(\"condition\", condition.Condition)\n\t//菜单\n\tadmin.GET(\"menu\", permission.Menu)\n\t//获取当前的管理员信息\n\tadmin.GET(\"manager/current-user\", user.Current)\n\n\tadmin.Use(middleware.AuthMiddleware())\n\t{\n\t\t//manager module\n\t\t//----------------------------权限----------------------------------------------------------\n\t\t//新增权限\n\t\tadmin.POST(\"manager/permission\", permission.Create)\n\t\t//删除权限\n\t\tadmin.DELETE(\"manager/permission/:id\", permission.Delete)\n\t\t//修改权限\n\t\tadmin.PUT(\"manager/permission/:id\", permission.Update)\n\t\t//获取一条\n\t\tadmin.GET(\"manager/permission/:id\", permission.Get)\n\t\t//获取权限列表\n\t\tadmin.GET(\"manager/permission\", permission.List)\n\n\t\t//----------------------------角色----------------------------------------------------------\n\t\t//新增角色\n\t\tadmin.POST(\"manager/role\", role.Create)\n\t\t//删除角色\n\t\tadmin.DELETE(\"manager/role/:id\", role.Delete)\n\t\t//修改角色\n\t\tadmin.PUT(\"manager/role/:id\", role.Update)\n\t\t//获取角色信息\n\t\tadmin.GET(\"manager/role/:id\", role.Get)\n\t\t//获取角色列表\n\t\tadmin.GET(\"manager/role\", role.List)\n\t\t//----------------------------管理员----------------------------------------------------------\n\t\t//新增管理员\n\t\tadmin.POST(\"manager/user\", user.Create)\n\t\t//冻结管理员\n\t\tadmin.PUT(\"manager/user-freeze/:id\", user.Freeze)\n\t\t//修改密码\n\t\tadmin.PUT(\"manager/user-pwd/:id\", user.Pwd)\n\t\t//更新管理员\n\t\tadmin.PUT(\"manager/user/:id\", user.Update)\n\t\t//获取管理员信息\n\t\tadmin.GET(\"manager/user/:id\", user.Get)\n\t\t//获取管理员列表\n\t\tadmin.GET(\"manager/user\", user.List)\n\n\t}\n\n\t/////////////////////////////////////////////////////后台 start///////////////////////////////////////////////////////////////////////////\n\t//公共接口\n\tglobals := g.Group(\"/globals\")\n\t{\n\t\tglobals.POST(\"/uploads\", global.Uploads)\n\t\tglobals.GET(\"/caches\", global.Cache)\n\t}\n\n\t// The health check handlers\n\tsvcd := g.Group(\"/sd\")\n\t{\n\t\tsvcd.GET(\"/health\", sd.HealthCheck)\n\t\tsvcd.GET(\"/disk\", sd.DiskCheck)\n\t\tsvcd.GET(\"/cpu\", sd.CPUCheck)\n\t\tsvcd.GET(\"/ram\", sd.RAMCheck)\n\t}\n\n\treturn g\n}", "func GetApis() (map[string]API, error) {\n\n\tif len(APIMap) != 0 {\n\t\treturn APIMap, nil\n\t}\n\n\tAPIMap = make(map[string]API)\n\tvar apis []API\n\n\tobjs, err := ioutil.ReadFile(\"apis.json\")\n\terr = json.Unmarshal(objs, &apis)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Convertimos el array de apis a Map\n\tfor _, api := range apis {\n\t\tAPIMap[api.ID] = api\n\t}\n\treturn APIMap, err\n}", "func LoadAuthyAPI() (*authy.Authy, error) {\n\tconfig, err := LoadConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapi := authy.NewAuthyAPI(config.APIKey)\n\tapi.BaseURL = \"https://api.authy.com\"\n\n\treturn api, nil\n}", "func init() {\r\n\tappConfig = config.GetAppConfiguration();\r\n\trequestTimeout := time.Duration(appConfig[\"httpRequestTimeout\"].(float64));\r\n\thttpClient = http.Client{Timeout: time.Millisecond * requestTimeout}\r\n}", "func initBaseConf() {\n\tssLEnable := false\n\tif viper.GetBool(defaultEnvHttpsEnable) {\n\t\tssLEnable = true\n\t} else {\n\t\tssLEnable = viper.GetBool(\"sslEnable\")\n\t}\n\trunMode := viper.GetString(\"runmode\")\n\tvar apiBase string\n\tif \"debug\" == runMode {\n\t\tapiBase = viper.GetString(\"dev_url\")\n\t} else if \"test\" == runMode {\n\t\tapiBase = viper.GetString(\"test_url\")\n\t} else {\n\t\tapiBase = viper.GetString(\"prod_url\")\n\t}\n\n\turi, err := url.Parse(apiBase)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbaseHOSTByEnv := viper.GetString(defaultEnvHost)\n\tif baseHOSTByEnv != \"\" {\n\t\turi.Host = baseHOSTByEnv\n\t\tapiBase = uri.String()\n\t} else {\n\t\tisAutoHost := viper.GetBool(defaultEnvAutoGetHost)\n\t\tSugar().Debugf(\"isAutoHost %v\", isAutoHost)\n\t\tif isAutoHost {\n\t\t\tipv4, err := sys.NetworkLocalIP()\n\t\t\tif err == nil {\n\t\t\t\taddrStr := viper.GetString(\"addr\")\n\t\t\t\tvar proc string\n\t\t\t\tif ssLEnable {\n\t\t\t\t\tproc = \"https\"\n\t\t\t\t} else {\n\t\t\t\t\tproc = \"http\"\n\t\t\t\t}\n\t\t\t\tapiBase = fmt.Sprintf(\"%v://%v%v\", proc, ipv4, addrStr)\n\t\t\t}\n\t\t}\n\t}\n\n\tif ssLEnable {\n\t\tapiBase = strings.Replace(apiBase, \"http://\", \"https://\", 1)\n\t}\n\tSugar().Debugf(\"config file uri.Host %v\", uri.Host)\n\tSugar().Debugf(\"apiBase %v\", apiBase)\n\tbaseConf = BaseConf{\n\t\tBaseURL: apiBase,\n\t\tSSLEnable: ssLEnable,\n\t}\n}", "func main() {\n\n\t//init api\n\tserver.Init()\n}", "func (self *userRestAPI) init(r *mux.Router,configfile string) error {\n\tvar err error\n\n\tself.engine,err = model.NewEngine(configfile)\n\tif err != nil {\n\t\treturn logError(err)\n\t}\n\n\tapi := r.PathPrefix(\"/user/v1\").Subrouter()\n\n\tapi.HandleFunc(\"/flighthistory/id/{token}/b/{band}/n/{number}\", self.flightHistory).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/transactions/id/{token}/b/{band}/n/{number}\", self.transactions).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/promises/id/{token}/b/{band}/n/{number}\", self.promises).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/account/id/{token}/b/{band}/n/{number}\", self.account).Methods(http.MethodGet)\n\tapi.HandleFunc(\"/dailystats/id/{token}\", self.dailyStats)\n\tapi.Use(middlewareIdToken)\n\n\treturn nil\n}", "func (*okapiLang) Loads() []rule.LoadInfo {\n\treturn []rule.LoadInfo{\n\t\t{\n\t\t\tName: \"@obazl_rules_ocaml//ocaml:rules.bzl\",\n\t\t\tSymbols: []string{\n\t\t\t\t\"ocaml_ns_library\",\n\t\t\t\t\"ocaml_library\",\n\t\t\t\t\"ppx_ns_library\",\n\t\t\t\t\"ppx_library\",\n\t\t\t\t\"ocaml_ns_archive\",\n\t\t\t\t\"ocaml_archive\",\n\t\t\t\t\"ppx_ns_archive\",\n\t\t\t\t\"ppx_archive\",\n\t\t\t\t\"ocaml_module\",\n\t\t\t\t\"ppx_module\",\n\t\t\t\t\"ocaml_signature\",\n\t\t\t\t\"ocaml_executable\",\n\t\t\t\t\"ppx_executable\",\n\t\t\t\t\"ocaml_test\",\n\t\t\t\t\"ppx_test\",\n\t\t\t\t\"ocaml_lex\",\n\t\t\t},\n\t\t\tAfter: nil,\n\t\t},\n\t}\n}", "func Load(fs *axis2.FileSystem, log rblutil.Logger) (data *Database, err error) {\n\tdefer errors.TrapError(&err, log)\n\n\trblutil.LogSeparator(log)\n\tlog.Println(\"Loading Addons...\")\n\n\tdata = &Database{\n\t\tTable: map[string]*Addon{},\n\t\tMeta: map[string]*Meta{},\n\t\tPacks: map[string]*PackMeta{},\n\t\tBanks: map[string]string{},\n\n\t\ttagsFirst: map[string][]string{},\n\t\ttagsLast: map[string][]string{},\n\n\t\tupdateBlacklist: map[string]bool{},\n\n\t\tGlobals: NewFileList(),\n\t}\n\n\tlog.Println(\" Loading Global Settings...\")\n\tglobal := NewPackMeta()\n\tcontent, err := fs.ReadAll(\"addons/global.meta\")\n\tif err == nil {\n\t\terr := json.Unmarshal(killMetaComments.ReplaceAllLiteral(content, []byte(\"\\n\")), global)\n\t\tif err != nil {\n\t\t\terrors.RaiseWrappedError(\"While loading global.meta\", err)\n\t\t}\n\t}\n\tdata.Writers = append(data.Writers, global.Writers...)\n\tfor k, v := range global.TagsFirst {\n\t\tdata.tagsFirst[k] = v\n\t}\n\tfor k, v := range global.TagsLast {\n\t\tdata.tagsLast[k] = v\n\t}\n\n\t// Import any tags defined by native APIs (generally script runners).\n\tfor k, v := range DefaultFirst {\n\t\tdata.tagsFirst[k] = v\n\t}\n\tfor k, v := range DefaultLast {\n\t\tdata.tagsLast[k] = v\n\t}\n\n\tlog.Println(\" Attempting to Read Auto-Update Blacklist...\")\n\tcontent, err = fs.ReadAll(\"addons/update_blacklist.txt\")\n\tif err == nil {\n\t\tlog.Println(\" Read OK, loading...\")\n\t\tfor _, line := range strings.Split(string(content), \"\\n\") {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tif line == \"\" || line[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata.updateBlacklist[line] = true\n\t\t}\n\t} else {\n\t\tlog.Println(\" Read failed (this is most likely ok)\\n Error:\", err)\n\t}\n\n\tlog.Println(\" Attempting to Read Content Server List...\")\n\tcontent, err = fs.ReadAll(\"addons/content_servers.txt\")\n\tif err == nil {\n\t\tlog.Println(\" Read OK, loading...\")\n\t\tfor _, line := range strings.Split(string(content), \"\\n\") {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tif line == \"\" || line[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata.Servers = append(data.Servers, line)\n\t\t}\n\t} else {\n\t\tlog.Println(\" Read failed (this is most likely ok)\\n Error:\", err)\n\t}\n\n\tlog.Println(\" Loading Addons From Local Directories...\")\n\n\tloadGlobals(fs, data, nil, nil, \"addons\")\n\tpmeta := loadMeta(fs, \"\", \"addons\", nil)\n\n\tfor _, dir := range fs.ListDirs(\"addons\") {\n\t\tloadDir(fs, data, dir, \"addons/\"+dir, nil, nil, pmeta)\n\t}\n\n\tlog.Println(\" Loading Addons From Globally Requested Addon Packs...\")\n\n\tfor _, pack := range global.Dependencies {\n\t\tloadPack(fs, log, data, pack, fs.Exists(\"addons/\"+pack+\".zip\"))\n\t}\n\n\tlog.Println(\" Loading Addons From Addon Packs...\")\n\n\tfor _, filename := range fs.ListFiles(\"addons\") {\n\t\tif strings.HasSuffix(filename, \".zip\") {\n\t\t\tname := rblutil.StripExt(filename)\n\t\t\tloadPack(fs, log, data, name, true)\n\t\t}\n\t}\n\n\tlog.Println(\" Checking Loaded Data...\")\n\n\t// Sort the addon list\n\tsort.Sort(addonSorter(data.List))\n\n\t// Add global files from addons\n\tdata.Globals.UpdateGlobals(data.List)\n\n\t// Fill in extra fields.\n\tfor _, addon := range data.List {\n\t\tdata.Table[addon.Meta.Name] = addon\n\t\tdata.Meta[addon.Meta.Name] = addon.Meta\n\t\tif addon.Meta.Tags[\"DocPack\"] {\n\t\t\tdata.DocPacks = append(data.DocPacks, addon.Meta)\n\t\t}\n\t}\n\n\t// Find any duplicates.\n\tdups := map[string]bool{}\n\tfor i := range data.List {\n\t\tif dups[data.List[i].Meta.Name] {\n\t\t\terrors.RaiseError(\" Duplicate addon found: \\\"\" + data.List[i].Meta.Name + \"\\\"\")\n\t\t}\n\t\tdups[data.List[i].Meta.Name] = true\n\t}\n\treturn data, nil\n}", "func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {\n\tg.Use(gin.Recovery())\n\tg.Use(middleware.NoCache)\n\tg.Use(middleware.Options)\n\tg.Use(middleware.Secure)\n\tg.Use(mw...)\n\n\t// 404 handler\n\tg.NoRoute(func(c *gin.Context) {\n\t\tc.String(http.StatusNotFound, \"The incorrect API route\")\n\t})\n\n\t// swagger api docs\n\tg.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\n\t// pprof router\n\tpprof.Register(g)\n\n\tg.POST(\"/login\", user.Login)\n\n\t// User Handler\n\tu := g.Group(\"/v1/user\")\n\tu.Use(middleware.AuthMiddleware()) {\n\t\tu.POST(\"\", user.Create)\n\t\tu.DELETE(\"/:id\", user.Delete)\n\t\tu.PUT(\"/:id\", user.Update)\n\t\tu.GET(\"\", user.List)\n\t\tu.GET(\"/:user_name\", user.Get)\n\t}\n\n\t// Health check handlers\n\th := g.Group(\"/health\") {\n\t\th.GET(\"/check\", health.Check)\n\t\th.GET(\"/disk\", health.DiskCheck)\n\t\th.GET(\"/cpu\", health.CPUCheck)\n\t\th.GET(\"/mem\", health.MemCheck)\n\t}\n\n\treturn g\n}", "func loadOAuthEndpoints(router router.Router, authMiddleware *jwt.Middleware, loader *oauth.Loader) {\n\tlog.Debug(\"Loading OAuth Endpoints\")\n\n\t// Oauth servers endpoints\n\toAuthHandler := oauth.NewController(loader)\n\toauthGroup := router.Group(\"/oauth/servers\")\n\toauthGroup.Use(authMiddleware.Handler)\n\t{\n\t\toauthGroup.GET(\"\", oAuthHandler.Get())\n\t\toauthGroup.POST(\"\", oAuthHandler.Post())\n\t\toauthGroup.GET(\"/:id\", oAuthHandler.GetBy())\n\t\toauthGroup.PUT(\"/:id\", oAuthHandler.PutBy())\n\t\toauthGroup.DELETE(\"/:id\", oAuthHandler.DeleteBy())\n\t}\n}", "func (b *Base) InitAPI() (err error) {\n\tvar (\n\t\tc *auth.Credentials\n\t\tprivateToken string\n\t)\n\n\tif privateToken = os.Getenv(\"C14_PRIVATE_TOKEN\"); privateToken != \"\" {\n\t\tc = &auth.Credentials{\n\t\t\tAccessToken: privateToken,\n\t\t}\n\t} else {\n\t\tif c, err = auth.GetCredentials(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tb.OnlineAPI = api.NewC14API(oauth2.NewClient(oauth2.NoContext, c), version.UserAgent, Root.Verbose)\n\treturn\n}", "func main() {\n\tc := webapi.Config{\n\t\tBaseUrl: os.Getenv(\"WEB_API_BASE_URL\"),\n\t\tPort: os.Getenv(\"WEB_API_PORT\"),\n\t\tEnv: os.Getenv(\"APP_ENV\"),\n\t}\n\n\tdbctx := context.Background()\n\tdbC, err := db.NewClient(dbctx, db.Config{\n\t\tURI: os.Getenv(\"MONGO_URI\"),\n\t\tDB: os.Getenv(\"MONGO_DB\"),\n\t})\n\n\tdefer dbC.Disconnect(dbctx)\n\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Can not get Configuration value from ENV : %s\", err))\n\t}\n\n\tif err := dbC.Health(context.Background()); err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"An error occured while instanciating db dependency : %s\", err))\n\t}\n\tam := webapi.NewAPIMiddleware(dbC)\n\th := webapi.NewAPIHandler(dbC)\n\ts := webapi.Server{\n\t\tConf: c,\n\t\tDBClient: dbC,\n\t\tMiddleware: am,\n\t\tHandler: h,\n\t}\n\t// todo v1.1: inject a logger, and monitoring agent in server\n\ts.InitServer()\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"An error occured during the web Api init : %s\", err))\n\t}\n\n\terr = s.Router.Run(s.Conf.BaseUrl + \":\" + s.Conf.Port)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Can not start server : %s\", err))\n\t}\n\n}", "func init() {\n\thttp.HandleFunc(\"/savecasedriver\",\thandlerSaveCaseDriver)\n\thttp.HandleFunc(\"/saveimage\",\t\t\t\thandlerSaveImage)\n\thttp.HandleFunc(\"/sendemail\",\t\t\t\thandlerSendEmail)\n\thttp.HandleFunc(\"/serve/\",\t\t\t\t\thandlerServe)\n\thttp.HandleFunc(\"/login\",\t\t\t\t\t\thandlerLogin)\n\n\t// API Versions\n\thttp.HandleFunc(\"/api/1.0/\",\t\t\t\thandlerAPI10) // API version 1.0\n\n http.HandleFunc(\"/\",\t\t\t\t\t\t\t\thandlerRoot)\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func parseAPI(discovery []byte) (API map[string]interface{}, err error) {\n\tif discovery == nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(discovery, &API)\n\treturn\n}", "func API(cfg *APIConfig) http.Handler {\n\n\t// Construct the App which holds all routes as well as common Middleware.\n\tapp := NewApp(cfg.Shutdown, cfg.Log)\n\n\t// Register health check endpoint. This route is not authenticated.\n\tcheck := api.Check{Log: cfg.Log}\n\tapp.Get(\"/api/v1/health\", check.Health)\n\n\thandlers := api.Handlers{\n\t\tLog: cfg.Log,\n\t\tDemo: cfg.Demo,\n\t\tTokenStore: cfg.TokenStore,\n\t\tStorage: storage.NewAlertStorage(),\n\t}\n\n\t// Main application routes\n\tapp.Route(\"/api/v1\", func(r chi.Router) {\n\t\tr.Use(chiMiddleware.RequestID)\n\t\tr.Use(chiMiddleware.RealIP)\n\t\tr.Use(middleware.Logger(cfg.Log.Desugar()))\n\t\tr.Use(chiMiddleware.Recoverer)\n\t\tr.Use(chiMiddleware.Timeout(60 * time.Second))\n\t\tr.Use(middleware.Tracing)\n\n\t\tr.Group(func(r chi.Router) {\n\t\t\t// check the token for the event collector endpoint, even if reverse-proxy auth is enabled\n\t\t\tr.Use(middleware.CollectorTokenAuth(cfg.TokenStore, cfg.Log))\n\t\t\tr.Route(\"/events\", func(r chi.Router) {\n\t\t\t\tr.Post(\"/\", handlers.CreateEventBatch)\n\t\t\t})\n\t\t})\n\n\t\tr.Group(func(r chi.Router) {\n\t\t\t// these routes are protected via reverse-proxy auth\n\n\t\t\tr.Route(\"/tokens\", func(r chi.Router) {\n\t\t\t\tr.Get(\"/\", handlers.ListTokens)\n\t\t\t\tr.Post(\"/\", handlers.CreateToken)\n\t\t\t\tr.Delete(\"/{tokenID}\", handlers.DeleteToken)\n\t\t\t})\n\n\t\t\tr.Route(\"/alerts\", func(r chi.Router) {\n\t\t\t\tr.Get(\"/\", handlers.ListAlerts)\n\n\t\t\t\tr.Route(\"/{alertID}\", func(r chi.Router) {\n\t\t\t\t\tr.Post(\"/review\", handlers.ReviewAlert)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n\n\tapp.Route(\"/\", func(r chi.Router) {\n\t\tstaticHandler := web.AssetHandler(\"/\", \"build\")\n\n\t\tr.Get(\"/\", staticHandler.ServeHTTP)\n\t\tr.Get(\"/*\", staticHandler.ServeHTTP)\n\t})\n\n\treturn app\n}", "func (a HTTPAPI) Start() error {\n\t// Setup API\n\trouter := gin.New()\n\n\t// Middleware\n\trouter.Use(a.MWLog)\n\n\tcorsCfg := cors.DefaultConfig()\n\tcorsCfg.AllowAllOrigins = true\n\trouter.Use(cors.New(corsCfg))\n\n\t// Routes\n\trouter.GET(\"/api/v0/health\",\n\t\ta.EPTHealth)\n\trouter.POST(\"/api/v0/flight_plan\",\n\t\ta.EPTCreateFlightPlan)\n\trouter.GET(\"/api/v0/flight_plan/:id\",\n\t\ta.EPTGetFlightPlan)\n\n\treturn router.Run(a.Config.HTTPHost)\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func InitApi(\n\tcfg Config,\n\ttemplates models.Templates,\n\tlocaleManager LocaleManager,\n) *Api {\n\treturn &Api{\n\t\tConfig: cfg,\n\t\ttemplates: templates,\n\t\tlocaleManager: localeManager,\n\t}\n}", "func LoadEnvs() {\n\tvar err error\n\n\tif err = godotenv.Load(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tPort, err = strconv.Atoi(os.Getenv(\"APP_PORT\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tAPIURL = os.Getenv(\"API_URL\")\n\tHashKey = []byte(os.Getenv(\"HASH_KEY\"))\n\tBlockKey = []byte(os.Getenv(\"BLOCK_KEY\"))\n}", "func Load(pattern string) (*api.Microgateway, error) {\n\tpatternJSON := []byte{}\n\tpatternJSON = getPattern(pattern)\n\tpDef := &api.Microgateway{}\n\terr := json.Unmarshal(patternJSON, pDef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pDef, nil\n}", "func (k *Keystone) RegisterHTTPAPI(r apiserver.HTTPRouter) {\n\tr.POST(\"/keystone/v3/auth/tokens\", k.CreateTokenAPI, apiserver.WithNoAuth())\n\tr.GET(\"/keystone/v3/auth/tokens\", k.ValidateTokenAPI, apiserver.WithNoAuth())\n\n\t// TODO: Remove this, since \"/keystone/v3/projects\" is a keystone endpoint\n\tr.GET(\n\t\t\"/keystone/v3/auth/projects\",\n\t\tk.ListAuthProjectsAPI,\n\t\tapiserver.WithNoAuth(),\n\t\tapiserver.WithHomepageType(apiserver.CollectionEndpoint),\n\t)\n\tr.GET(\"/keystone/v3/auth/domains\", k.listDomainsAPI, apiserver.WithHomepageType(apiserver.CollectionEndpoint))\n\n\tr.GET(\n\t\t\"/keystone/v3/projects\",\n\t\tk.ListProjectsAPI,\n\t\tapiserver.WithNoAuth(),\n\t\tapiserver.WithHomepageType(apiserver.CollectionEndpoint),\n\t)\n\tr.GET(\"/keystone/v3/projects/:id\", k.GetProjectAPI)\n\tr.GET(\"/keystone/v3/domains\", k.listDomainsAPI, apiserver.WithHomepageType(apiserver.CollectionEndpoint))\n\n\tr.GET(\"/keystone/v3/users\", k.ListUsersAPI, apiserver.WithHomepageType(apiserver.CollectionEndpoint))\n}", "func Load(middleware ...gin.HandlerFunc) http.Handler {\n\tif config.Debug {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\te := gin.New()\n\n\te.SetHTMLTemplate(\n\t\ttemplate.Load(),\n\t)\n\n\te.Use(middleware...)\n\te.Use(logger.SetLogger())\n\te.Use(recovery.SetRecovery())\n\te.Use(store.SetStore())\n\te.Use(header.SetCache())\n\te.Use(header.SetOptions())\n\te.Use(header.SetSecure())\n\te.Use(header.SetVersion())\n\te.Use(session.SetCurrent())\n\n\troot := e.Group(config.Server.Root)\n\t{\n\t\troot.StaticFS(\n\t\t\t\"/storage\",\n\t\t\tgin.Dir(\n\t\t\t\tconfig.Server.Storage,\n\t\t\t\tfalse,\n\t\t\t),\n\t\t)\n\n\t\troot.StaticFS(\n\t\t\t\"/assets\",\n\t\t\tassets.Load(),\n\t\t)\n\n\t\troot.GET(\"/favicon.ico\", web.Favicon)\n\t\troot.GET(\"\", web.Index)\n\n\t\tbase := root.Group(\"/api\")\n\t\t{\n\t\t\tbase.GET(\"\", api.IndexInfo)\n\n\t\t\t//\n\t\t\t// Auth\n\t\t\t//\n\t\t\tauth := base.Group(\"/auth\")\n\t\t\t{\n\t\t\t\tauth.GET(\"/verify/:token\", api.AuthVerify)\n\t\t\t\tauth.GET(\"/logout\", session.MustCurrent(), api.AuthLogout)\n\t\t\t\tauth.GET(\"/refresh\", session.MustCurrent(), api.AuthRefresh)\n\t\t\t\tauth.POST(\"/login\", session.MustNobody(), api.AuthLogin)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Profile\n\t\t\t//\n\t\t\tprofile := base.Group(\"/profile\")\n\t\t\t{\n\t\t\t\tprofile.Use(session.MustCurrent())\n\n\t\t\t\tprofile.GET(\"/token\", api.ProfileToken)\n\t\t\t\tprofile.GET(\"/self\", api.ProfileShow)\n\t\t\t\tprofile.PATCH(\"/self\", api.ProfileUpdate)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Registries\n\t\t\t//\n\t\t\tregistries := base.Group(\"/registries\")\n\t\t\t{\n\t\t\t\tregistries.Use(session.MustCurrent())\n\t\t\t\tregistries.Use(session.MustRegistries(\"display\"))\n\n\t\t\t\tregistries.GET(\"\", api.RegistryIndex)\n\t\t\t\tregistries.GET(\"/:registry\", session.SetRegistry(), api.RegistryShow)\n\t\t\t\tregistries.DELETE(\"/:registry\", session.SetRegistry(), session.MustRegistries(\"delete\"), api.RegistryDelete)\n\t\t\t\tregistries.PATCH(\"/:registry\", session.SetRegistry(), session.MustRegistries(\"change\"), api.RegistryUpdate)\n\t\t\t\tregistries.POST(\"\", session.MustRegistries(\"change\"), api.RegistryCreate)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Tags\n\t\t\t//\n\t\t\ttags := base.Group(\"/orgs/:org/repos/:repo/tags\")\n\t\t\t{\n\t\t\t\ttags.Use(session.SetOrg())\n\t\t\t\ttags.Use(session.SetRepo())\n\t\t\t\ttags.Use(session.MustTags(\"display\"))\n\n\t\t\t\ttags.GET(\"\", api.TagIndex)\n\t\t\t\ttags.GET(\"/:tag\", session.SetTag(), api.TagShow)\n\t\t\t\ttags.DELETE(\"/:tag\", session.SetTag(), session.MustTags(\"delete\"), api.TagDelete)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Repos\n\t\t\t//\n\t\t\trepos := base.Group(\"/orgs/:org/repos\")\n\t\t\t{\n\t\t\t\trepos.Use(session.SetOrg())\n\t\t\t\trepos.Use(session.MustRepos(\"display\"))\n\n\t\t\t\trepos.GET(\"\", api.RepoIndex)\n\t\t\t\trepos.GET(\"/:repo\", session.SetRepo(), api.RepoShow)\n\t\t\t\trepos.DELETE(\"/:repo\", session.SetRepo(), session.MustRepos(\"delete\"), api.RepoDelete)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Orgs\n\t\t\t//\n\t\t\torgs := base.Group(\"/orgs\")\n\t\t\t{\n\t\t\t\torgs.Use(session.MustOrgs(\"display\"))\n\n\t\t\t\torgs.GET(\"\", api.OrgIndex)\n\t\t\t\torgs.GET(\"/:org\", session.SetOrg(), api.OrgShow)\n\t\t\t\torgs.DELETE(\"/:org\", session.SetOrg(), session.MustOrgs(\"delete\"), api.OrgDelete)\n\t\t\t\torgs.PATCH(\"/:org\", session.SetOrg(), session.MustOrgs(\"change\"), api.OrgUpdate)\n\t\t\t\torgs.POST(\"\", session.MustOrgs(\"change\"), api.OrgCreate)\n\t\t\t}\n\n\t\t\torgTeams := base.Group(\"/orgs/:org/teams\")\n\t\t\t{\n\t\t\t\torgTeams.Use(session.MustCurrent())\n\t\t\t\torgTeams.Use(session.SetOrg())\n\n\t\t\t\torgTeams.GET(\"\", session.MustOrgTeams(\"display\"), api.OrgTeamIndex)\n\t\t\t\torgTeams.POST(\"\", session.MustOrgTeams(\"change\"), api.OrgTeamAppend)\n\t\t\t\torgTeams.PATCH(\"\", session.MustOrgTeams(\"change\"), api.OrgTeamPerm)\n\t\t\t\torgTeams.DELETE(\"\", session.MustOrgTeams(\"change\"), api.OrgTeamDelete)\n\t\t\t}\n\n\t\t\torgUsers := base.Group(\"/orgs/:org/users\")\n\t\t\t{\n\t\t\t\torgUsers.Use(session.MustCurrent())\n\t\t\t\torgUsers.Use(session.SetOrg())\n\n\t\t\t\torgUsers.GET(\"\", session.MustOrgUsers(\"display\"), api.OrgUserIndex)\n\t\t\t\torgUsers.POST(\"\", session.MustOrgUsers(\"change\"), api.OrgUserAppend)\n\t\t\t\torgUsers.PATCH(\"\", session.MustOrgUsers(\"change\"), api.OrgUserPerm)\n\t\t\t\torgUsers.DELETE(\"\", session.MustOrgUsers(\"change\"), api.OrgUserDelete)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Users\n\t\t\t//\n\t\t\tusers := base.Group(\"/users\")\n\t\t\t{\n\t\t\t\tusers.Use(session.MustUsers(\"display\"))\n\n\t\t\t\tusers.GET(\"\", api.UserIndex)\n\t\t\t\tusers.GET(\"/:user\", session.SetUser(), api.UserShow)\n\t\t\t\tusers.DELETE(\"/:user\", session.SetUser(), session.MustUsers(\"delete\"), api.UserDelete)\n\t\t\t\tusers.PATCH(\"/:user\", session.SetUser(), session.MustUsers(\"change\"), api.UserUpdate)\n\t\t\t\tusers.POST(\"\", session.MustUsers(\"change\"), api.UserCreate)\n\t\t\t}\n\n\t\t\tuserTeams := base.Group(\"/users/:user/teams\")\n\t\t\t{\n\t\t\t\tuserTeams.Use(session.MustCurrent())\n\t\t\t\tuserTeams.Use(session.SetUser())\n\n\t\t\t\tuserTeams.GET(\"\", session.MustUserTeams(\"display\"), api.UserTeamIndex)\n\t\t\t\tuserTeams.POST(\"\", session.MustUserTeams(\"change\"), api.UserTeamAppend)\n\t\t\t\tuserTeams.PATCH(\"\", session.MustUserTeams(\"change\"), api.UserTeamPerm)\n\t\t\t\tuserTeams.DELETE(\"\", session.MustUserTeams(\"change\"), api.UserTeamDelete)\n\t\t\t}\n\n\t\t\tuserOrgs := base.Group(\"/users/:user/orgs\")\n\t\t\t{\n\t\t\t\tuserOrgs.Use(session.MustCurrent())\n\t\t\t\tuserOrgs.Use(session.SetUser())\n\n\t\t\t\tuserOrgs.GET(\"\", session.MustUserOrgs(\"display\"), api.UserOrgIndex)\n\t\t\t\tuserOrgs.POST(\"\", session.MustUserOrgs(\"change\"), api.UserOrgAppend)\n\t\t\t\tuserOrgs.PATCH(\"\", session.MustUserOrgs(\"change\"), api.UserOrgPerm)\n\t\t\t\tuserOrgs.DELETE(\"\", session.MustUserOrgs(\"change\"), api.UserOrgDelete)\n\t\t\t}\n\n\t\t\t//\n\t\t\t// Teams\n\t\t\t//\n\t\t\tteams := base.Group(\"/teams\")\n\t\t\t{\n\t\t\t\tteams.Use(session.MustTeams(\"display\"))\n\n\t\t\t\tteams.GET(\"\", api.TeamIndex)\n\t\t\t\tteams.GET(\"/:team\", session.SetTeam(), api.TeamShow)\n\t\t\t\tteams.DELETE(\"/:team\", session.SetTeam(), session.MustTeams(\"delete\"), api.TeamDelete)\n\t\t\t\tteams.PATCH(\"/:team\", session.SetTeam(), session.MustTeams(\"change\"), api.TeamUpdate)\n\t\t\t\tteams.POST(\"\", session.MustTeams(\"change\"), api.TeamCreate)\n\t\t\t}\n\n\t\t\tteamUsers := base.Group(\"/teams/:team/users\")\n\t\t\t{\n\t\t\t\tteamUsers.Use(session.MustCurrent())\n\t\t\t\tteamUsers.Use(session.SetTeam())\n\n\t\t\t\tteamUsers.GET(\"\", session.MustTeamUsers(\"display\"), api.TeamUserIndex)\n\t\t\t\tteamUsers.POST(\"\", session.MustTeamUsers(\"change\"), api.TeamUserAppend)\n\t\t\t\tteamUsers.PATCH(\"\", session.MustTeamUsers(\"change\"), api.TeamUserPerm)\n\t\t\t\tteamUsers.DELETE(\"\", session.MustTeamUsers(\"change\"), api.TeamUserDelete)\n\t\t\t}\n\n\t\t\tteamOrgs := base.Group(\"/teams/:team/orgs\")\n\t\t\t{\n\t\t\t\tteamOrgs.Use(session.MustCurrent())\n\t\t\t\tteamOrgs.Use(session.SetTeam())\n\n\t\t\t\tteamOrgs.GET(\"\", session.MustTeamOrgs(\"display\"), api.TeamOrgIndex)\n\t\t\t\tteamOrgs.POST(\"\", session.MustTeamOrgs(\"change\"), api.TeamOrgAppend)\n\t\t\t\tteamOrgs.PATCH(\"\", session.MustTeamOrgs(\"change\"), api.TeamOrgPerm)\n\t\t\t\tteamOrgs.DELETE(\"\", session.MustTeamOrgs(\"change\"), api.TeamOrgDelete)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn e\n}", "func Run(){\n\tRestApiImplPtr.RegisterApi()\n\tRestServerImplPtr.StartRestServer();\n}", "func (h *HTTP) GetLoader(_ modules.Job) lua.LGFunction {\n\treturn func() lua.LGFunction {\n\t\treturn func(luaState *lua.LState) int {\n\t\t\tvar exports = map[string]lua.LGFunction{\n\t\t\t\t\"request\": h.request,\n\t\t\t\t\"post\": h.send(http.MethodPost),\n\t\t\t\t\"get\": h.send(http.MethodGet),\n\t\t\t\t\"put\": h.send(http.MethodPut),\n\t\t\t\t\"delete\": h.send(http.MethodDelete),\n\t\t\t}\n\n\t\t\tmod := luaState.SetFuncs(luaState.NewTable(), exports)\n\n\t\t\tmod.RawSetString(\"methodGet\", lua.LString(http.MethodGet))\n\t\t\tmod.RawSetString(\"methodHead\", lua.LString(http.MethodHead))\n\t\t\tmod.RawSetString(\"methodPost\", lua.LString(http.MethodPost))\n\t\t\tmod.RawSetString(\"methodPut\", lua.LString(http.MethodPut))\n\t\t\tmod.RawSetString(\"methodPatch\", lua.LString(http.MethodPatch))\n\t\t\tmod.RawSetString(\"methodDelete\", lua.LString(http.MethodDelete))\n\t\t\tmod.RawSetString(\"methodConnect\", lua.LString(http.MethodConnect))\n\t\t\tmod.RawSetString(\"methodOptions\", lua.LString(http.MethodOptions))\n\t\t\tmod.RawSetString(\"methodTrace\", lua.LString(http.MethodTrace))\n\n\t\t\tluaState.Push(mod)\n\t\t\treturn 1\n\t\t}\n\t}()\n}", "func Initialize(\n\tctx context.Context,\n\t// configuration\n\tcfg *config.TemporalConfig,\n\tversion string,\n\topts Options,\n\tclients Clients,\n\t// API dependencies\n\tl *zap.SugaredLogger,\n\n) (*API, error) {\n\tvar (\n\t\terr error\n\t\trouter = gin.Default()\n\t)\n\t// update dev mode\n\tdev = opts.DevMode\n\tl = l.Named(\"api\")\n\tim, err := rtfs.NewManager(\n\t\tcfg.IPFS.APIConnection.Host+\":\"+cfg.IPFS.APIConnection.Port,\n\t\t\"\", time.Minute*60,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timCluster, err := rtfscluster.Initialize(\n\t\tctx,\n\t\tcfg.IPFSCluster.APIConnection.Host,\n\t\tcfg.IPFSCluster.APIConnection.Port,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set up API struct\n\tapi, err := new(cfg, router, l, clients, im, imCluster, opts.DebugLogging)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapi.version = version\n\n\t// init routes\n\tif err = api.setupRoutes(); err != nil {\n\t\treturn nil, err\n\t}\n\tapi.l.Info(\"api initialization successful\")\n\n\t// return our configured API service\n\treturn api, nil\n}", "func (a *App) apiRoute(e *echo.Echo) error {\n\tapiUrl, err := a.conf.Get(\"api-url\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t//General API\n\tg := e.Group(apiUrl.(string))\n\t//auth\n\tg.Post(\"/auth\", a.login)\n\t//oauth\n\ta.fb, err = oauth.NewFacebook(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfbg := g.Group(\"/oauth\")\n\tfbg.Get(\"/facebook\", a.facebookAuth)\n\tfbg.Get(\"/facebook/redirect\", a.facebookRedirect)\n\t//tasks\n\ttokenizer := jwt.NewTokenizer(a)\n\ttg := g.Group(\"/tasks\", tokenizer.Check())\n\ttg.Post(\"\", a.create)\n\ttg.Get(\"/:id\", a.retrieve)\n\ttg.Get(\"\", a.retrieveAll)\n\ttg.Put(\"/:id\", a.update)\n\ttg.Delete(\"/:id\", a.delete)\n\treturn nil\n}", "func Load() (*Config, error) {\n\tport := flag.Int(\"port\", 8080, \"port number to run http server on\")\n\n\tflag.Parse()\n\n\tcfg := &Config{\n\t\tHTTPPort: *port,\n\t}\n\n\tif err := config.Load(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.StravaClientID <= 0 || cfg.StravaSecretID == \"\" {\n\t\treturn nil, errors.New(\"please provide your Strava's client_id and client_secret\")\n\t}\n\n\treturn cfg, nil\n}", "func Initialize() {\n\n\t// Register all rest endpoints.\n\tws := &restful.WebService{}\n\tws.Path(fmt.Sprintf(\"/api/%s\", api.APIVersion)).\n\t\tConsumes(restful.MIME_JSON, \"text/plain\", \"text/event-stream\").\n\t\tProduces(restful.MIME_JSON, \"text/plain\", \"text/event-stream\")\n\n\t// Register APIs to the web service.\n\tregisterWebhookAPIs(ws)\n\tregisterHealthCheckAPIs(ws)\n\tregisterServiceAPIs(ws)\n\tregisterVersionAPIs(ws)\n\t// TODO Register project API.\n\t//registerProjectAPIs(ws)\n\tregisterRemoteAPIs(ws)\n\tregisterVersionLogAPIs(ws)\n\tregisterResourceAPIs(ws)\n\tregisterDeployAPIs(ws)\n\n\tregisterTemplateAPIs(ws)\n\tregisterCloudsAPIs(ws)\n\n\trestful.Add(ws)\n\n\t// Add container filter to enable CORS and respond to OPTIONS.\n\tcors := restful.CrossOriginResourceSharing{\n\t\tExposeHeaders: []string{\"X-My-Header\"},\n\t\t// The header \"token\" is not a standard header. It's used in auth server\n\t\t// to handle authentication.\n\t\tAllowedHeaders: []string{\"Content-Type\", \"Accept\", \"token\"},\n\t\tCookiesAllowed: false,\n\t\tContainer: restful.DefaultContainer,\n\t}\n\trestful.Filter(cors.Filter)\n\trestful.Filter(restful.OPTIONSFilter())\n\n\tremoteManager = remote.NewManager()\n}", "func LoadData() (Config, error) {\n\tvar cfg Config\n\tenvPortHTTP := os.Getenv(\"AFS_PORT_HTTP\")\n\tif envPortHTTP != \"\" {\n\t\tvar value int\n\n\t\tvalue, err := strconv.Atoi(envPortHTTP)\n\t\tif err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t\t*portHttp = value\n\t}\n\tcfg.PortHTTP = fmt.Sprintf(\"%d\", *portHttp)\n\n\treturn cfg, nil\n}", "func (openapi *Openapi) LoadDoc(location string) (doc []byte, err error) {\n\t//if has prefix http ,get doc from url\n\tif strings.HasPrefix(location, \"http\") {\n\t\tresp, httErr := http.Get(location)\n\t\tif httErr != nil {\n\t\t\terr = httErr\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tdoc, err = ioutil.ReadAll(resp.Body)\n\t}\n\tfilename := location\n\tif _, err = os.Stat(filename); err != nil {\n\t\treturn\n\t}\n\n\tdoc, err = ioutil.ReadFile(filename)\n\treturn\n}", "func Load() Configuration {\n\tif cfg.APIAiToken != \"\" {\n\t\treturn cfg\n\t}\n\tconf, err := os.Open(\"config/config.json\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\tdecoder := json.NewDecoder(conf)\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\tlog.Fatal(\"config:Load error : \", err)\n\t}\n\n\treturn cfg\n}", "func init() {\n//\tvar _r = net.GetRouter()\n//\tvar r = _r.PathPrefix(\"/v1\").Subrouter()\n\n var r = net.GetRouter()\n\t//route for test\n\t log.Print(\"cz init net_v1\")\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBGettokenizedcards, nil)).Methods(\"GET\") //logicbusiness.go\n r.Handle(\"/v3/processpayment\", netHandle(v4handleDBProcesspayment, nil)).Methods(\"GET\") //logicbusiness.go \n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBGeneratetokenized, nil)).Methods(\"GET\") //logicbusiness.go\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBPostGettokenizedcards, nil)).Methods(\"POST\") //logicbusiness.go\n\tr.Handle(\"/v3/processpayment\", netHandle(v4handleDBPostProcesspayment, nil)).Methods(\"POST\") //logicbusiness.go \t \n\n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBPostGeneratetokenized, nil)).Methods(\"POST\") //logicbusiness.go\n\n\t \n}", "func loadMock() {\n\tdb := &URLDB.URLDB{}\n\tbyteValue, _ := ioutil.ReadFile(\"./configs/db.json\")\n\t_ = db.UnmarshalJSON(byteValue)\n\tdomains = db.Domains\n}", "func newAPI(cfg *ClientConfig, options ...ClientOption) *Client {\n\tclient := &Client{\n\t\tConfig: cfg,\n\t\thttpClient: &http.Client{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\treturn client\n}" ]
[ "0.61819816", "0.6145376", "0.6132068", "0.6036757", "0.600604", "0.5945516", "0.59435636", "0.5902919", "0.58774483", "0.57917875", "0.5787408", "0.57356775", "0.5726812", "0.5726081", "0.57181555", "0.5660854", "0.5660561", "0.56412345", "0.55986047", "0.5566639", "0.5561168", "0.55572903", "0.55437434", "0.5528657", "0.55139035", "0.54847646", "0.54639614", "0.54522955", "0.5438943", "0.53991985", "0.53923094", "0.5392033", "0.53490186", "0.53406304", "0.53365475", "0.53308797", "0.53248775", "0.53186643", "0.5315163", "0.53118104", "0.53116894", "0.5302079", "0.52831036", "0.52824837", "0.5281087", "0.5264975", "0.5262692", "0.52584577", "0.5244738", "0.5240929", "0.52328503", "0.523106", "0.52067935", "0.5206033", "0.51898193", "0.51887864", "0.51827776", "0.517927", "0.51738673", "0.51705045", "0.516545", "0.5164001", "0.5163889", "0.515606", "0.51551574", "0.5152577", "0.5144911", "0.5144322", "0.5140548", "0.51376677", "0.5133334", "0.51319957", "0.5131732", "0.51269394", "0.5121378", "0.5118712", "0.51130384", "0.5109269", "0.51086956", "0.51059026", "0.50990343", "0.5089288", "0.50889885", "0.50868785", "0.5083922", "0.50784665", "0.5068993", "0.50667447", "0.5066481", "0.5063315", "0.50613105", "0.50611407", "0.5060844", "0.50501347", "0.50489527", "0.5048238", "0.50477284", "0.5043486", "0.5043248", "0.5037696" ]
0.579643
9
Your code here RPC handlers for the worker to call. an example RPC handler. the RPC argument and reply types are defined in rpc.go.d
func (m *Master) Example(args *ExampleArgs, reply *ExampleReply) error { reply.Y = args.X + 1 return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func callWorker(worker, name string, args interface{}, reply interface{}) bool {\n\treturn call(worker, \"RPCWorker.\"+name, args, reply)\n}", "func (cl *Client) DoRPC(functionName string, args interface{}) (response interface{}, err error) {\n\t/*\n\t\tDoes a remote procedure call using the msgpack2 protocol for RPC that return a QueryReply\n\t*/\n\tif args == nil {\n\t\treturn nil, fmt.Errorf(\"args must be non-nil - have: args: %v\", args)\n\t}\n\tmessage, err := msgpack2.EncodeClientRequest(\"DataService.\"+functionName, args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqURL := cl.BaseURL + \"/rpc\"\n\treq, err := http.NewRequestWithContext(context.Background(), \"POST\", reqURL, bytes.NewBuffer(message))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-msgpack\")\n\tclient := new(http.Client)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func(resp *http.Response) {\n\t\tif err2 := resp.Body.Close(); err2 != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"failed to close http client for marketstore api. err=%v\", err2))\n\t\t}\n\t}(resp)\n\n\t// Handle any error in the RPC call\n\tconst statusOK = 200\n\tif resp.StatusCode != statusOK {\n\t\tbodyBytes, err2 := goio.ReadAll(resp.Body)\n\t\tvar errText string\n\t\tif err2 != nil {\n\t\t\terrText = err2.Error()\n\t\t} else if bodyBytes != nil {\n\t\t\terrText = string(bodyBytes)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"response error (%d): %s\", resp.StatusCode, errText)\n\t}\n\n\t// Unpack and format the response from the RPC call\n\tdecodeFunc, found := decodeFuncMap[functionName]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"unsupported RPC response\")\n\t}\n\treturn decodeFunc(resp)\n}", "func rpc(w http.ResponseWriter, r *http.Request) {\n\t// Parses the command into the rpc struct\n\tvar rpc rpcCall\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(bodyBytes, &rpc)\n\tif err != nil {\n\t\tsendHTTPResp(w, 500, err)\n\t\treturn\n\t}\n\n\t// Processes the rpc opcodes\n\tif rpc.Call == \"mkdirp\" { // Opcode for creating new dirs\n\t\tpath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.MkdirAll(path, os.ModePerm)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t} else if rpc.Call == \"mv\" { // Opcode for moving/renaming files\n\t\tsrcPath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t\tdstPath, err := validPath(rpc.Args[1])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.Rename(srcPath, dstPath)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t} else if rpc.Call == \"rm\" { // Opcode for removing files\n\t\tpath, err := validPath(rpc.Args[0])\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = os.RemoveAll(path)\n\t\tif err != nil {\n\t\t\tsendHTTPResp(w, 500, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Write([]byte(\"ok\"))\n}", "func Rpc(queue string, message interface{}, conn *amqp.Connection, l *logging.Logger) ([]byte, error) {\n\n\tl.Info(\"Executing RPC to queue: %s\", queue)\n\tl.Debug(\"Getting Channel for RPC\")\n\tchannel, err := conn.Channel()\n\tdefer channel.Close()\n\tl.Debug(\"Got Channel for RPC\")\n\n\tvar q amqp.Queue\n\tvar msgs <-chan amqp.Delivery\n\n\tl.Debug(\"Declaring Queue for RPC\")\n\tq, err = channel.QueueDeclare(\n\t\t\"\",\n\t\tfalse,\n\t\tfalse,\n\t\ttrue,\n\t\tfalse,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\tdebug.PrintStack()\n\t\tl.Errorf(\"Failed to declare a queue: %v\", err)\n\t\treturn nil, err\n\t}\n\tl.Debug(\"Declared Queue for RPC\")\n\tl.Debug(\"Registering consumer for RPC\")\n\tmsgs, err = channel.Consume(\n\t\tq.Name,\n\t\t\"\",\n\t\ttrue,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\tdebug.PrintStack()\n\t\tl.Errorf(\"Failed to register a consumer: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tl.Debug(\"Registered consumer for RPC\")\n\tcorrId := randomString(32)\n\n\tmrs, err := json.Marshal(message)\n\tif err != nil {\n\t\tl.Errorf(\"Error while marshaling: %v\", err)\n\t\treturn nil, err\n\t}\n\tl.Debug(\"Publishing message to queue %s\", queue)\n\terr = channel.Publish(\n\t\tOpenbatonExchangeName, // exchange\n\t\tqueue, // routing key\n\t\tfalse, // mandatory\n\t\tfalse, // immediate\n\t\tamqp.Publishing{\n\t\t\tContentType: AmqpContentType,\n\t\t\tCorrelationId: corrId,\n\t\t\tReplyTo: q.Name,\n\t\t\tBody: []byte(mrs),\n\t\t})\n\n\tif err != nil {\n\t\tl.Errorf(\"Failed to publish a message\")\n\t\treturn nil, err\n\t}\n\tl.Debugf(\"Published message to queue %s\", queue)\n\n\tfor d := range msgs {\n\t\tif corrId == d.CorrelationId {\n\t\t\tl.Debug(\"Received Response\")\n\t\t\treturn d.Body, nil\n\t\t}\n\t}\n\treturn nil, errors.New(fmt.Sprintf(\"Not found message with correlationId [%s]\", corrId))\n}", "func main() {\n\thandleRequests := func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err == nil {\n\t\t\tbuf := bytes.NewBuffer(body).String()\n\n\t\t\tif handleMtSupporteMethods(buf, w) {\n\t\t\t\treturn\n\t\t\t} else if handleMetaWeblogGetRecentPosts(buf, w) {\n\t\t\t\treturn\n\t\t\t} else if handleMetaWeblogNewPost(buf, w) {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Not a known method call %s\", buf)\n\t\t\t\t// return error\n\t\t\t\tio.WriteString(w, \"<?xml version=\\\"1.0\\\"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><int>-32601</int></value></member><member><name>faultString</name><value><string>server error. requested method not found</string></value></member></struct></value></fault></methodResponse>\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t\tio.WriteString(w, \"<?xml version=\\\"1.0\\\"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><int>-32601</int></value></member><member><name>faultString</name><value><string>server error. requested method not found</string></value></member></struct></value></fault></methodResponse>\")\n\t\t}\n\t}\n\n\thttp.HandleFunc(\"/xmlrpc.php\", handleRequests)\n\n\tlog.Println(\"Starting XML-RPC server on localhost:80/xmlrpc.php\")\n\tlog.Fatal(http.ListenAndServe(\":80\", nil))\n}", "func (b *Backend) RPC(choice uint64, body []byte, v interface{}) error {\n\tconn, err := b.Dial()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer conn.Close()\n\n\tchoiceBuf := make([]byte, binary.MaxVarintLen64)\n\tbinary.PutUvarint(choiceBuf, choice)\n\t_, err = conn.conn.Write(choiceBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbodyLenBuf := make([]byte, binary.MaxVarintLen64)\n\tbinary.PutUvarint(bodyLenBuf, uint64(len(body)))\n\n\t_, err = conn.conn.Write(bodyLenBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = conn.conn.Write(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trespLenBuf := make([]byte, binary.MaxVarintLen64)\n\t_, err = conn.conn.Read(respLenBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\trespLen, _ := binary.Uvarint(respLenBuf)\n\trespBuf := make([]byte, respLen)\n\t_, err = conn.conn.Read(respBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(respBuf, v)\n\n\treturn err\n}", "func (rm *REKTManager) worker(req http.Request) Response {\n\tresp, err := rm.client.Do(&req)\n\tif err != nil {\n\t\treturn Response{make([]byte, 0), err}\n\t}\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn Response{make([]byte, 0), err}\n\t}\n\n\treturn Response{data, err}\n}", "func HandleRpcs(cmd PB_CommandToServer, params RPC_UserParam, rpcHandler RPC_AllHandlersInteract, responseHandler RPC_ResponseHandlerInterface) {\n\n\tsplits := strings.Split(cmd.Command, \".\")\n\n\tif len(splits) != 2 {\n\t\tnoDevErr(errors.New(\"HandleRpcs: splic is not 2 parts\"))\n\t\treturn\n\t}\n\n\tswitch splits[0] {\n\n\tcase \"RPC_Auth\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Auth\n\t\trpc := rpcHandler.RPC_Auth\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Auth\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"CheckPhone\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.CheckPhone(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.CheckPhone\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.CheckPhone\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCode\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCode(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCode\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCode\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCodeToSms\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCodeToSms(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCodeToSms\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCodeToSms\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCodeToTelgram\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCodeToTelgram(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCodeToTelgram\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCodeToTelgram\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SingUp\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SingUp(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SingUp\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SingUp\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SingIn\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SingIn(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SingIn\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SingIn\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"LogOut\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.LogOut(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.LogOut\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.LogOut\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Chat\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Chat\n\t\trpc := rpcHandler.RPC_Chat\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Chat\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"AddNewMessage\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_AddNewMessage{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.AddNewMessage(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.AddNewMessage\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_AddNewMessage\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_AddNewMessage\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_AddNewMessage\",\"RPC_Chat.AddNewMessage\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetRoomActionDoing\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetRoomActionDoing{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetRoomActionDoing(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetRoomActionDoing\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetRoomActionDoing\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetRoomActionDoing\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetRoomActionDoing\",\"RPC_Chat.SetRoomActionDoing\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetMessagesRangeAsSeen\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetChatMessagesRangeAsSeen{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetMessagesRangeAsSeen(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetMessagesRangeAsSeen\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetChatMessagesRangeAsSeen\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetChatMessagesRangeAsSeen\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetChatMessagesRangeAsSeen\",\"RPC_Chat.SetMessagesRangeAsSeen\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"DeleteChatHistory\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_DeleteChatHistory{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.DeleteChatHistory(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.DeleteChatHistory\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_DeleteChatHistory\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteChatHistory\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteChatHistory\",\"RPC_Chat.DeleteChatHistory\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"DeleteMessagesByIds\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_DeleteMessagesByIds{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.DeleteMessagesByIds(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.DeleteMessagesByIds\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_DeleteMessagesByIds\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteMessagesByIds\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteMessagesByIds\",\"RPC_Chat.DeleteMessagesByIds\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetMessagesAsReceived\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetMessagesAsReceived{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetMessagesAsReceived(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetMessagesAsReceived\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetMessagesAsReceived\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetMessagesAsReceived\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetMessagesAsReceived\",\"RPC_Chat.SetMessagesAsReceived\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"EditMessage\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_EditMessage{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.EditMessage(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.EditMessage\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_EditMessage\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_EditMessage\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_EditMessage\",\"RPC_Chat.EditMessage\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetChatList\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetChatList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetChatList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetChatList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetChatList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatList\",\"RPC_Chat.GetChatList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetChatHistoryToOlder\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetChatHistoryToOlder{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetChatHistoryToOlder(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetChatHistoryToOlder\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetChatHistoryToOlder\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatHistoryToOlder\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatHistoryToOlder\",\"RPC_Chat.GetChatHistoryToOlder\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetFreshAllDirectMessagesList\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetFreshAllDirectMessagesList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetFreshAllDirectMessagesList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetFreshAllDirectMessagesList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetFreshAllDirectMessagesList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetFreshAllDirectMessagesList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetFreshAllDirectMessagesList\",\"RPC_Chat.GetFreshAllDirectMessagesList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Other\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Other\n\t\trpc := rpcHandler.RPC_Other\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Other\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"Echo\": //each pb_service_method\n\t\t\tload := &PB_OtherParam_Echo{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.Echo(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Other.Echo\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_OtherResponse_Echo\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_OtherResponse_Echo\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_OtherResponse_Echo\",\"RPC_Other.Echo\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Sync\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Sync\n\t\trpc := rpcHandler.RPC_Sync\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Sync\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"GetGeneralUpdates\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_GetGeneralUpdates{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetGeneralUpdates(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.GetGeneralUpdates\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_GetGeneralUpdates\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetGeneralUpdates\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetGeneralUpdates\",\"RPC_Sync.GetGeneralUpdates\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetNotifyUpdates\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_GetNotifyUpdates{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetNotifyUpdates(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.GetNotifyUpdates\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_GetNotifyUpdates\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetNotifyUpdates\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetNotifyUpdates\",\"RPC_Sync.GetNotifyUpdates\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncDirectUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncDirectUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncDirectUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncDirectUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncDirectUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncDirectUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncDirectUpdateId\",\"RPC_Sync.SetLastSyncDirectUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncGeneralUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncGeneralUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncGeneralUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncGeneralUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncGeneralUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncGeneralUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncGeneralUpdateId\",\"RPC_Sync.SetLastSyncGeneralUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncNotifyUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncNotifyUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncNotifyUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncNotifyUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncNotifyUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncNotifyUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncNotifyUpdateId\",\"RPC_Sync.SetLastSyncNotifyUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_UserOffline\":\n\n\t\t//rpc,ok := rpcHandler.RPC_UserOffline\n\t\trpc := rpcHandler.RPC_UserOffline\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_UserOffline\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"BlockUser\": //each pb_service_method\n\t\t\tload := &PB_UserParam_BlockUser{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.BlockUser(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.BlockUser\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_BlockUser\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_BlockUser\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_BlockUser\",\"RPC_UserOffline.BlockUser\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UnBlockUser\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UnBlockUser{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UnBlockUser(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UnBlockUser\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UnBlockUser\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UnBlockUser\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UnBlockUser\",\"RPC_UserOffline.UnBlockUser\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UpdateAbout\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UpdateAbout{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UpdateAbout(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UpdateAbout\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UpdateAbout\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateAbout\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateAbout\",\"RPC_UserOffline.UpdateAbout\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UpdateUserName\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UpdateUserName{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UpdateUserName(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UpdateUserName\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UpdateUserName\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateUserName\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateUserName\",\"RPC_UserOffline.UpdateUserName\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"ChangePrivacy\": //each pb_service_method\n\t\t\tload := &PB_UserParam_ChangePrivacy{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.ChangePrivacy(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.ChangePrivacy\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponseOffline_ChangePrivacy\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponseOffline_ChangePrivacy\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponseOffline_ChangePrivacy\",\"RPC_UserOffline.ChangePrivacy\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"ChangeAvatar\": //each pb_service_method\n\t\t\tload := &PB_UserParam_ChangeAvatar{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.ChangeAvatar(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.ChangeAvatar\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_ChangeAvatar\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_ChangeAvatar\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_ChangeAvatar\",\"RPC_UserOffline.ChangeAvatar\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_User\":\n\n\t\t//rpc,ok := rpcHandler.RPC_User\n\t\trpc := rpcHandler.RPC_User\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_User\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"CheckUserName\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.CheckUserName(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_User.CheckUserName\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName\",\"RPC_User.CheckUserName\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetBlockedList\": //each pb_service_method\n\t\t\tload := &PB_UserParam_BlockedList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetBlockedList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_User.GetBlockedList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_BlockedList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_BlockedList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_BlockedList\",\"RPC_User.GetBlockedList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tdefault:\n\t\tnoDevErr(errors.New(\"rpc dosent exisit for: \" + cmd.Command))\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err != nil {\n\t\tlog.Fatal(\"rpc.Client.Call:\", err)\n\t}\n}", "func RunAPI(server *Server, quit qu.C) {\n\tnrh := RPCHandlers\n\tgo func() {\n\t\tD.Ln(\"starting up node cAPI\")\n\t\tvar e error\n\t\tvar res interface{}\n\t\tfor {\n\t\t\tselect { \n\t\t\tcase msg := <-nrh[\"addnode\"].Call:\n\t\t\t\tif res, e = nrh[\"addnode\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.AddNodeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan AddNodeRes) <-AddNodeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"createrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"createrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.CreateRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan CreateRawTransactionRes) <-CreateRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"decoderawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"decoderawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.DecodeRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.TxRawDecodeResult); ok { \n\t\t\t\t\tmsg.Ch.(chan DecodeRawTransactionRes) <-DecodeRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"decodescript\"].Call:\n\t\t\t\tif res, e = nrh[\"decodescript\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.DecodeScriptCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.DecodeScriptResult); ok { \n\t\t\t\t\tmsg.Ch.(chan DecodeScriptRes) <-DecodeScriptRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"estimatefee\"].Call:\n\t\t\t\tif res, e = nrh[\"estimatefee\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.EstimateFeeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan EstimateFeeRes) <-EstimateFeeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"generate\"].Call:\n\t\t\t\tif res, e = nrh[\"generate\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GenerateRes) <-GenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getaddednodeinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getaddednodeinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetAddedNodeInfoCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetAddedNodeInfoResultAddr); ok { \n\t\t\t\t\tmsg.Ch.(chan GetAddedNodeInfoRes) <-GetAddedNodeInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getbestblock\"].Call:\n\t\t\t\tif res, e = nrh[\"getbestblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBestBlockResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBestBlockRes) <-GetBestBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getbestblockhash\"].Call:\n\t\t\t\tif res, e = nrh[\"getbestblockhash\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBestBlockHashRes) <-GetBestBlockHashRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblock\"].Call:\n\t\t\t\tif res, e = nrh[\"getblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockVerboseResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockRes) <-GetBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockchaininfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockchaininfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockChainInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockChainInfoRes) <-GetBlockChainInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockcount\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockcount\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(int64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockCountRes) <-GetBlockCountRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockhash\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockhash\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockHashCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockHashRes) <-GetBlockHashRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockheader\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockheader\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockHeaderCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockHeaderVerboseResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockHeaderRes) <-GetBlockHeaderRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblocktemplate\"].Call:\n\t\t\t\tif res, e = nrh[\"getblocktemplate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockTemplateCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockTemplateRes) <-GetBlockTemplateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcfilter\"].Call:\n\t\t\t\tif res, e = nrh[\"getcfilter\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetCFilterCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCFilterRes) <-GetCFilterRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcfilterheader\"].Call:\n\t\t\t\tif res, e = nrh[\"getcfilterheader\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetCFilterHeaderCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCFilterHeaderRes) <-GetCFilterHeaderRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getconnectioncount\"].Call:\n\t\t\t\tif res, e = nrh[\"getconnectioncount\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(int32); ok { \n\t\t\t\t\tmsg.Ch.(chan GetConnectionCountRes) <-GetConnectionCountRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcurrentnet\"].Call:\n\t\t\t\tif res, e = nrh[\"getcurrentnet\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCurrentNetRes) <-GetCurrentNetRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getdifficulty\"].Call:\n\t\t\t\tif res, e = nrh[\"getdifficulty\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetDifficultyCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetDifficultyRes) <-GetDifficultyRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getgenerate\"].Call:\n\t\t\t\tif res, e = nrh[\"getgenerate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetHeadersCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan GetGenerateRes) <-GetGenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"gethashespersec\"].Call:\n\t\t\t\tif res, e = nrh[\"gethashespersec\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetHashesPerSecRes) <-GetHashesPerSecRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getheaders\"].Call:\n\t\t\t\tif res, e = nrh[\"getheaders\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetHeadersCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetHeadersRes) <-GetHeadersRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.InfoChainResult0); ok { \n\t\t\t\t\tmsg.Ch.(chan GetInfoRes) <-GetInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getmempoolinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getmempoolinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMempoolInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetMempoolInfoRes) <-GetMempoolInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getmininginfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getmininginfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMiningInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetMiningInfoRes) <-GetMiningInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getnettotals\"].Call:\n\t\t\t\tif res, e = nrh[\"getnettotals\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetNetTotalsResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetNetTotalsRes) <-GetNetTotalsRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getnetworkhashps\"].Call:\n\t\t\t\tif res, e = nrh[\"getnetworkhashps\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetNetworkHashPSCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetPeerInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetNetworkHashPSRes) <-GetNetworkHashPSRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getpeerinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getpeerinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetPeerInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetPeerInfoRes) <-GetPeerInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getrawmempool\"].Call:\n\t\t\t\tif res, e = nrh[\"getrawmempool\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetRawMempoolCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetRawMempoolRes) <-GetRawMempoolRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"getrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetRawTransactionRes) <-GetRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"gettxout\"].Call:\n\t\t\t\tif res, e = nrh[\"gettxout\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetTxOutCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetTxOutRes) <-GetTxOutRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"help\"].Call:\n\t\t\t\tif res, e = nrh[\"help\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.HelpCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan HelpRes) <-HelpRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"node\"].Call:\n\t\t\t\tif res, e = nrh[\"node\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.NodeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan NodeRes) <-NodeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"ping\"].Call:\n\t\t\t\tif res, e = nrh[\"ping\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan PingRes) <-PingRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"resetchain\"].Call:\n\t\t\t\tif res, e = nrh[\"resetchain\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan ResetChainRes) <-ResetChainRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"restart\"].Call:\n\t\t\t\tif res, e = nrh[\"restart\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan RestartRes) <-RestartRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"searchrawtransactions\"].Call:\n\t\t\t\tif res, e = nrh[\"searchrawtransactions\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SearchRawTransactionsCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.SearchRawTransactionsResult); ok { \n\t\t\t\t\tmsg.Ch.(chan SearchRawTransactionsRes) <-SearchRawTransactionsRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"sendrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"sendrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SendRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan SendRawTransactionRes) <-SendRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"setgenerate\"].Call:\n\t\t\t\tif res, e = nrh[\"setgenerate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SetGenerateCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan SetGenerateRes) <-SetGenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"stop\"].Call:\n\t\t\t\tif res, e = nrh[\"stop\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan StopRes) <-StopRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"submitblock\"].Call:\n\t\t\t\tif res, e = nrh[\"submitblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SubmitBlockCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan SubmitBlockRes) <-SubmitBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"uptime\"].Call:\n\t\t\t\tif res, e = nrh[\"uptime\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMempoolInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan UptimeRes) <-UptimeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"validateaddress\"].Call:\n\t\t\t\tif res, e = nrh[\"validateaddress\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.ValidateAddressCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.ValidateAddressChainResult); ok { \n\t\t\t\t\tmsg.Ch.(chan ValidateAddressRes) <-ValidateAddressRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"verifychain\"].Call:\n\t\t\t\tif res, e = nrh[\"verifychain\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VerifyChainCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan VerifyChainRes) <-VerifyChainRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"verifymessage\"].Call:\n\t\t\t\tif res, e = nrh[\"verifymessage\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VerifyMessageCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan VerifyMessageRes) <-VerifyMessageRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"version\"].Call:\n\t\t\t\tif res, e = nrh[\"version\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VersionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(map[string]btcjson.VersionResult); ok { \n\t\t\t\t\tmsg.Ch.(chan VersionRes) <-VersionRes{&r, e} } \n\t\t\tcase <-quit.Wait():\n\t\t\t\tD.Ln(\"stopping wallet cAPI\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (r *rpcServerService) doCall(serviceMethod string, args []byte) ([]byte,\n error) {\n\n glog.V(3).Infof(\"rpc: doCall to %s\", serviceMethod)\n glog.V(4).Infof(\"rpc: doCall to %s with %v\", serviceMethod, args)\n\n dot := strings.LastIndex(serviceMethod, \".\")\n if dot < 0 {\n err := fmt.Errorf(\"rpc: service/method ill-formed: \" + serviceMethod)\n glog.Error(err)\n return nil, err\n }\n serviceName := serviceMethod[:dot]\n methodName := serviceMethod[dot+1:]\n // Look up the request.\n serviceInf, ok := r.serviceMap.Get(serviceName)\n if !ok || serviceInf == nil {\n err := errors.New(\"rpc: can't find service \" + serviceName)\n glog.Error(err)\n return nil, err\n }\n service, okType := serviceInf.(*rpcServiceMap)\n if !okType || service == nil {\n err := errors.New(\"rpc: unexpected type error for service \" + serviceName)\n glog.Error(err)\n return nil, err\n }\n mtype := service.method[methodName]\n if mtype == nil {\n err := errors.New(\"rpc: can't find method \" + serviceMethod)\n glog.Error(err)\n return nil, err\n }\n argv := reflect.New(mtype.argType)\n errJSON := json.Unmarshal(args, argv.Interface())\n if errJSON != nil {\n glog.Error(\"error in unmarshal: \", errJSON)\n return nil, errJSON\n }\n glog.V(4).Infof(\"rpc: json unmarshalled request is: %s -> %#v\", args, argv)\n replyv := reflect.New(mtype.replyType.Elem())\n\n glog.V(3).Infof(\"rpc: calling service %v method %v with %v\",\n service, mtype, argv)\n\n errCall := service.callService(mtype, argv.Elem(), replyv)\n if errCall != nil {\n glog.V(3).Infof(\"rpc call returned error: \", errCall)\n return nil, errCall\n }\n reply, errRep := json.Marshal(replyv.Interface())\n if errRep != nil {\n glog.Error(\"rpc reply marshall error: \", errRep)\n return nil, errRep\n }\n glog.V(3).Info(\"rpc reply: \", string(reply))\n return reply, nil\n}", "func main() {\n\n\t// The command line arguments. args[1] is the supervisor address,\n\t// args[2] is the port to run on\n\targs := os.Args\n\n\t// If the right number of arguments weren't passed, ask for them.\n\tif len(args) != 3 {\n\t\tfmt.Println(\"Please pass the hostname of the supervisor and the outgoing port.\" +\n\t\t\t\"eg. http://stu.cs.jmu.edu:4001 4031\")\n\t\tos.Exit(1)\n\t}\n\n\tresp, err := http.Post(args[1]+\"/register\", \"text/plain\", strings.NewReader(args[2]))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\n\t// This gives what the supervisor thinks the worker is, which is useful for debugging.\n\t_ = data.JsonToWorker(buf.Bytes())\n\n\t// If there is a request for /newjob,\n\t// the new_job routine will handle it.\n\thttp.HandleFunc(\"/newjob\", new_job)\n\n\t// Listen on a port.\n\tlog.Fatal(http.ListenAndServe(\":\"+args[2], nil))\n}", "func rpc_Go(method string, args Triplet, resp *Response, ip string, port int, cs chan *rpc.Call) interface{} {\n\ttempClient, err := jsonrpc.Dial(serverInfo1.Protocol, ip+\":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t(*resp).client = tempClient\n\ttempClient.Go(\"DICT3.\"+method, args, resp, cs)\n\treturn nil\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\tw := worker{}\n\tw.mapf = mapf\n\tw.reducef = reducef\n\tw.register()\n\tw.check()\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\n}", "func bitcoinRPC(arguments *bitcoinArguments, reply *bitcoinReply) error {\n\n\ts, err := json.Marshal(arguments)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalBitcoinData.log.Debugf(\"rpc send: %s\", s)\n\n\tpostData := bytes.NewBuffer(s)\n\n\trequest, err := http.NewRequest(\"POST\", globalBitcoinData.url, postData)\n\tif nil != err {\n\t\treturn err\n\t}\n\trequest.SetBasicAuth(globalBitcoinData.username, globalBitcoinData.password)\n\n\tresponse, err := globalBitcoinData.client.Do(request)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, &reply)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalBitcoinData.log.Debugf(\"rpc receive: %s\", body)\n\n\treturn nil\n}", "func (w *worker) Invoke(args interface{}) error { return ErrNotImplement }", "func bitcoinRPC(arguments *bitcoinArguments, reply *bitcoinReply) error {\n\n\ts, err := json.Marshal(arguments)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Tracef(\"rpc send: %s\", s)\n\n\tpostData := bytes.NewBuffer(s)\n\n\trequest, err := http.NewRequest(\"POST\", globalData.url, postData)\n\tif nil != err {\n\t\treturn err\n\t}\n\trequest.SetBasicAuth(globalData.username, globalData.password)\n\n\tresponse, err := globalData.client.Do(request)\n\tif nil != err {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Tracef(\"rpc response body: %s\", body)\n\n\terr = json.Unmarshal(body, &reply)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tglobalData.log.Debugf(\"rpc receive: %s\", body)\n\n\treturn nil\n}", "func (p *Engine) Worker() {\n\n}", "func Worker(mapf func(string, string) []Pair, reducef func(string, []string) string) {\n\tclient := MakeRpcClient()\n\tdefer client.Close()\n\tfor {\n\t\t// 对端的 server 如果退出了,下面这个会有什么反应\n\t\ttask := Task{TaskKind: ReduceTaskFlag, TaskId: \"10\"}\n\n\t\t// fmt.Println(\"request task\")\n\t\tstatus := client.Call(\"Coordinator.RequestTask\", struct{}{}, &task)\n\t\t// fmt.Println(\"Get response\", task)\n\t\tif status == false {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch task.TaskKind {\n\t\tcase MapTaskFlag:\n\t\t\t// fmt.Println(\"get map task \", task.TaskId)\n\t\t\tintermediate := mapf(task.File, readFileToString(task.File))\n\t\t\t// fmt.Println(\"map task done\")\n\t\t\tsort.Sort(ByKey(intermediate))\n\t\t\tr := MapResult{TaskId: task.TaskId, Items: divideIntoItems(intermediate)}\n\t\t\tclient.Call(\"Coordinator.UploadMapResult\", r, nil)\n\t\t\t// fmt.Println(\"map result upload\")\n\n\t\tcase ReduceTaskFlag:\n\t\t\tLog(\"get reduce task \", task.TaskId)\n\t\t\tfilename := fmt.Sprint(\"mr-out-\", task.TaskId)\n\t\t\tf, _ := os.Create(filename)\n\t\t\tdefer f.Close()\n\t\t\targFile, _ := os.Open(task.File)\n\t\t\treader := bufio.NewReader(argFile)\n\n\t\t\tfor {\n\t\t\t\tend, k, vs := readFrom(reader)\n\t\t\t\tif end {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tLog(\"reduce func call\", k)\n\t\t\t\t// fmt.Println(\"key: \", k, \"values: \", vs)\n\n\t\t\t\tv := reducef(k, vs)\n\t\t\t\tfmt.Fprintf(f, \"%v %v\\n\", k, v)\n\t\t\t}\n\t\t\tLog(\"reduce task \", task.TaskId, \"done\")\n\n\t\t\tresult := ReduceResult{TaskId: task.TaskId, Filename: filename}\n\t\t\tclient.Call(\"Coordinator.UploadReduceResult\", result, nil)\n\t\t\tLog(\"reduce task\", task.TaskId, \"result upload\")\n\n\t\tcase ShutdownFlag:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *Server) call(req *Request) *Response {\n\t// TODO: simplfy this function, or split into several functions\n\tdot := strings.LastIndex(req.Method, \".\") // split req.Method like \"type.Method\"\n\tif dot < 0 {\n\t\terr := errors.New(\"rpc: service/method request ill-formed: \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(ParseErr, err.Error(), err))\n\t}\n\n\tserviceName := req.Method[:dot]\n\tmethodName := req.Method[dot+1:]\n\n\t// method existed or not\n\tsvci, ok := s.m.Load(serviceName)\n\tif !ok {\n\t\terr := errors.New(\"rpc: can't find service \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(MethodNotFound, err.Error(), nil))\n\t}\n\tsvc := svci.(*service)\n\tmtype := svc.method[methodName]\n\tif mtype == nil {\n\t\terr := errors.New(\"rpc: can't find method \" + req.Method)\n\t\treturn NewResponse(req.ID, nil, NewJsonrpcErr(MethodNotFound, err.Error(), nil))\n\t}\n\n\t// to prepare argv and replyv in reflect.Value\n\t// ref to `net/http/rpc`\n\targIsValue := false // if true, need to indirect before calling.\n\tvar argv reflect.Value\n\tif mtype.ArgType.Kind() == reflect.Ptr {\n\t\targv = reflect.New(mtype.ArgType.Elem())\n\t} else {\n\t\targv = reflect.New(mtype.ArgType)\n\t\targIsValue = true\n\t}\n\n\t// argv guaranteed to be a pointer now.\n\tif argIsValue {\n\t\targv = argv.Elem()\n\t}\n\n\tconvert(req.Params, argv.Interface())\n\t// fmt.Println(argv.Interface())\n\n\treplyv := reflect.New(mtype.ReplyType.Elem())\n\tswitch mtype.ReplyType.Elem().Kind() {\n\tcase reflect.Map:\n\t\treplyv.Elem().Set(reflect.MakeMap(mtype.ReplyType.Elem()))\n\tcase reflect.Slice:\n\t\treplyv.Elem().Set(reflect.MakeSlice(mtype.ReplyType.Elem(), 0, 0))\n\t}\n\n\treturn svc.call(mtype, req, argv, replyv)\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t\tports = Ports{ usedPorts: make(map[int]bool) }\n\t\t\n\n\t\tjob := new(Job)\n\t\tjob.MapFunc = mapf\n\t\tjob.RedFunc = reducef\n\t\tjob.JobType = Mapper\n\n\n\t\tspawnChannel := make(chan int)\n\t\tsomechan := make(chan bool)\n\t\tgo StartRPCClient(spawnChannel, somechan, job)\n\n\t\ttime.Sleep(10*time.Millisecond)\n\t\tgo SpawnReducers(somechan, job)\n\t\tSpawnMappers(spawnChannel, job)\n}", "func main() {\n\n\t// The command line arguments. args[1] is the supervisor address,\n\t// args[2] is the port to run on\n\targs := os.Args\n\n\t// If the right number of arguments weren't passed, ask for them.\n\tif len(args) != 3 {\n\t\tfmt.Println(\"Please pass the hostname of the supervisor and the outgoing port.\" +\n\t\t\t\"eg. http://stu.cs.jmu.edu:4001 4031\")\n\t\tos.Exit(1)\n\t}\n\n\tresp, err := http.Post(args[1]+\"/register\", \"text/plain\", strings.NewReader(args[2]))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\n\t// This gives what the supervisor thinks the worker is, which is useful for debugging.\n\t_ = data.JsonToWorker(buf.Bytes())\n\n\t// Make a directory for this worker, to avoid IO errors from workers writing and reading to\n\t// the same file.\n\tworkerDirectory = args[2]\n\tif _, err = os.Stat(workerDirectory); os.IsNotExist(err) {\n\t\terr = os.Mkdir(args[2], 0777)\n\t\tcheck(err)\n\t}\n\n\t// If there is a request for /newjob,\n\t// the new_job routine will handle it.\n\thttp.HandleFunc(\"/newjob\", new_job)\n\n\t// Listen on a port.\n\tlog.Fatal(http.ListenAndServe(\":\"+args[2], nil))\n}", "func StartServer(servers []string, me int) *KVPaxos {\n // this call is all that's needed to persuade\n // Go's RPC library to marshall/unmarshall\n // struct Op.\n gob.Register(Op{})\n\n kv := new(KVPaxos)\n kv.me = me\n\n // Your initialization code here.\n kv.data = make(map[string]string)\n kv.pendingRead = make(map[int64]*PendingRead)\n kv.applied = -1\n\n rpcs := rpc.NewServer()\n rpcs.Register(kv)\n\n kv.px = paxos.Make(servers, me, rpcs)\n\n // start worker\n kv.StartBackgroundWorker()\n\n os.Remove(servers[me])\n l, e := net.Listen(\"unix\", servers[me]);\n if e != nil {\n log.Fatal(\"listen error: \", e);\n }\n kv.l = l\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n go func() {\n for kv.dead == false {\n conn, err := kv.l.Accept()\n if err == nil && kv.dead == false {\n if kv.unreliable && (rand.Int63() % 1000) < 100 {\n // discard the request.\n conn.Close()\n } else if kv.unreliable && (rand.Int63() % 1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n fmt.Printf(\"shutdown: %v\\n\", err)\n }\n go rpcs.ServeConn(conn)\n } else {\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && kv.dead == false {\n fmt.Printf(\"KVPaxos(%v) accept: %v\\n\", me, err.Error())\n kv.kill()\n }\n }\n }()\n\n return kv\n}", "func RunRPC() error {\n\n\t// Get flags\n\ttraceserviceaccountfile := viper.GetString(\"traceserviceaccountfile\")\n\tif traceserviceaccountfile == \"\" {\n\t\treturn errors.New(\"You must supply a valid service account for tracing using the `traceserviceaccountfile` flag\")\n\t}\n\n\tprojectid := viper.GetString(\"projectid\")\n\tif projectid == \"\" {\n\t\treturn errors.New(\"You must provide a valid project id using the `projectid` argument\")\n\t}\n\n\t// Create a stackdriver exporter for traces.\n\tstackExporter, err := stackdriver.NewExporter(stackdriver.Options{\n\t\tProjectID: projectid,\n\t\tTraceClientOptions: []option.ClientOption{\n\t\t\toption.WithCredentialsFile(traceserviceaccountfile),\n\t\t},\n\t})\n\tif err != nil {\n\t\twerr := errors.Wrap(err, \"stackdriver.NewExporter\")\n\t\tphdlog.Info(logMessage,\n\t\t\t\"\",\n\t\t\tzap.String(\"processStatus\", \"unable to create stackdriver exporter\"),\n\t\t\tzap.String(\"error\", werr.Error()))\n\t\treturn werr\n\t}\n\t// Register the stackdriver exporter.\n\ttrace.RegisterExporter(stackExporter)\n\n\trpcPort := \":\" + viper.GetString(\"rpc-port\")\n\tif rpcPort == \":\" {\n\t\treturn errors.New(\"You must supply a valid port using the 'rpc-port' argument\")\n\t}\n\tlis, err := net.Listen(\"tcp\", rpcPort)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to initialize TCP listen: %v\")\n\t}\n\n\tdefer func() {\n\t\tif ferr := lis.Close(); err != nil {\n\t\t\tphdlog.Error(logMessage, \"\", zap.String(\"error\", ferr.Error()))\n\t\t}\n\t}()\n\n\trpcServer := grpc.NewServer(\n\t\tgrpc.StatsHandler(&ocgrpc.ServerHandler{\n\t\t\tStartOptions: trace.StartOptions{\n\t\t\t\tSampler: trace.AlwaysSample(),\n\t\t\t},\n\t\t}),\n\t\tgrpc.UnaryInterceptor(\n\t\t\tgrpc_middleware.ChainUnaryServer(\n\t\t\t\tgrpcmw.ConversationIDMiddleware(),\n\t\t\t\tgrpcmw.LoggerMiddleware(),\n\t\t\t),\n\t\t),\n\t)\n\tvar service *handlers.RestServiceServer\n\tservice, err = handlers.NewRest()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpb.RegisterRestServiceServer(rpcServer, service)\n\n\tphdlog.Info(logMessage, \"\", zap.String(\"RPC Listening on\", lis.Addr().String()))\n\treturn rpcServer.Serve(lis)\n}", "func main() {\n\t// =====increment.pb.goのやつ======== ​\n\t//listen, err := net.Listen(\"tcp\", \"localhost:5555\")\n\t//if err != nil {\n\t//\tlog.Fatalln(err)\n\t//}\n\t//\n\t//server := grpc.NewServer()\n\t//service := &incrementService{}\n\t//\n\t//pb.RegisterIncrementServiceServer(server, service)\n\t//server.Serve(listen)\n\n\t// =====search.pb.goのやつ========\n\tlisten, err := net.Listen(\"tcp\", \"localhost:5555\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tserver := grpc.NewServer()\n\tservice := &searchService{}\n\t// Register reflection service on gRPC server.\n\treflection.Register(server)\n\tpb.RegisterSearchServiceServer(server, service)\n\t_ = server.Serve(listen)\n}", "func (conn *Connection) RPCall(funcName string, args interface{}, result interface{}) {\n\tconn.client.Call(funcName, args, result)\n\tconn.wg.Done()\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\tfor {\n\t\targs := RPCArgs{}\n\t\treply := RPCReply{}\n\t\tcall(\"Master.GetTask\", &args, &reply)\n\t\tswitch reply.TaskInfo.TaskType {\n\t\tcase Map:\n\t\t\tdoMap(&reply.TaskInfo, mapf)\n\t\tcase Reduce:\n\t\t\tdoReduce(&reply.TaskInfo, reducef)\n\t\tcase Wait:\n\t\t\tfmt.Println(\"Waiting task\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\tcase Done:\n\t\t\tfmt.Println(\"All task done\")\n\t\t\treturn\n\t\t}\n\t\targs.TaskInfo = reply.TaskInfo\n\t\tcall(\"Master.TaskDone\", &args, &reply)\n\t}\n}", "func rpcClient(name, ip string, refInt int, minerInfo *MinerInformation, wg *sync.WaitGroup, threshold float64) {\n\t//Add everything except the connection\n\tc := Client{name, ip, nil, refInt, minerInfo, nil, threshold, int(time.Now().Unix())}\n\t//Save the Client struct in the MinerInfo\n\tc.MinerInfo.Client = &c\n\n\tclientRequests := make(chan RpcRequest)\n\tc.ClientRequests = clientRequests\n\n\t//Start the thread the will keep doing summary requests\n\tgo SummaryHandler(clientRequests, minerInfo, &c, wg)\n\t//Start another thread the will ask the devs requests\n\tgo DevsHandler(clientRequests, minerInfo, &c, wg)\n\n\t//Wait for new requst to make from the clienReequest channel\n\tfor r := range clientRequests {\n\t\t//Create a new connection\n\t\tc.Conn = createConnection(c.IP)\n\n\t\t//If c.Conn is still nil then we couldn't connect\n\t\t//So send back an empty slice of bytes\n\t\tif c.Conn == nil {\n\t\t\tlog.Printf(\"[rpcClient] - Could not connect to the client - %s\\n\",c.Name)\n\t\t\tr.ResultChan <- make([]byte, 0)\n\n\t\t} else {\n\t\t\t//Send the request to the cgminer\n\t\t\tb := sendCommand(&c.Conn, r.Request)\n\t\t\t/* \n\t\t\t * Note:\n\t\t\t *\n\t\t\t * It seems that cgminer close the tcp connection\n\t\t\t * after each call so we need to reset it for i := 0; i < count; i++ {\n\t\t\t \t\n\t\t\t }\n\t\t\t * the next rpc-call\n\t\t\t */\n\t\t\tc.Conn.Close()\n\n\t\t\t//And send back the result\n\t\t\tr.ResultChan <- b\n\t\t}\n\t}\n}", "func (wk *Worker) startRPCServer() {\n\t// TODO: implement me\n\t// Hint: Refer to how the driver's startRPCServer is implemented.\n\t// TODO TODO TODO\n\t//\n\n\t//\n\t// Once shutdown is closed, should the following statement be\n\t// called, meaning the worker RPC server is existing.\n\tserverless.Debug(\"Worker: %v RPC server exist\\n\", wk.address)\n}", "func (f *Function) fwdRPC(ctx context.Context, reqPayload string) (*hpb.HelloReply, error) {\n\tf.RLock()\n\tdefer f.RUnlock()\n\n\tlogger := log.WithFields(log.Fields{\"fID\": f.fID})\n\n\tfuncClient := *f.funcClient\n\n\tlogger.Debug(\"FwdRPC: Forwarding RPC to function instance\")\n\tresp, err := funcClient.SayHello(ctx, &hpb.HelloRequest{Name: reqPayload})\n\tlogger.Debug(\"FwdRPC: Received a response from the function instance\")\n\n\treturn resp, err\n}", "func RPC_Service() {\n\tapi := new(API)\n\terr := rpc.Register(api)\n\tif err != nil {\n\t\tlog.Fatal(\"error registering API\", err)\n\t}\n\trpc.HandleHTTP()\n\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:8080\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"Listener error\", err)\n\t}\n\tlog.Printf(\"serving rpc on port %d\", 8080)\n\thttp.Serve(listener, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(\"error serving: \", err)\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\tgob.Register(MapJob{})\n\tgob.Register(ReduceJob{})\n\tsockname := coordinatorSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func (this *Engine) launchRpcServe() (done chan null.NullStruct) {\n\tvar (\n\t\tprotocolFactory thrift.TProtocolFactory\n\t\tserverTransport thrift.TServerTransport\n\t\ttransportFactory thrift.TTransportFactory\n\t\terr error\n\t\tserverNetwork string\n\t)\n\n\tswitch config.Engine.Rpc.Protocol {\n\tcase \"binary\":\n\t\tprotocolFactory = thrift.NewTBinaryProtocolFactoryDefault()\n\n\tcase \"json\":\n\t\tprotocolFactory = thrift.NewTJSONProtocolFactory()\n\n\tcase \"simplejson\":\n\t\tprotocolFactory = thrift.NewTSimpleJSONProtocolFactory()\n\n\tcase \"compact\":\n\t\tprotocolFactory = thrift.NewTCompactProtocolFactory()\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown protocol: %s\", config.Engine.Rpc.Protocol))\n\t}\n\n\t// client-side Thrift protocol/transport stack must match\n\t// the server-side, otherwise you are very likely to get in trouble\n\tswitch {\n\tcase config.Engine.Rpc.Framed:\n\t\t// each payload is sent over the wire with a frame header containing its size\n\t\ttransportFactory = thrift.NewTFramedTransportFactory(transportFactory)\n\n\tdefault:\n\t\t// there is no BufferedTransport in Java: only FramedTransport\n\t\ttransportFactory = thrift.NewTBufferedTransportFactory(\n\t\t\tconfig.Engine.Rpc.BufferSize)\n\t}\n\n\tswitch {\n\tcase strings.Contains(config.Engine.Rpc.ListenAddr, \"/\"):\n\t\tserverNetwork = \"unix\"\n\t\tif config.Engine.Rpc.SessionTimeout > 0 {\n\t\t\tserverTransport, err = NewTUnixSocketTimeout(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr, config.Engine.Rpc.SessionTimeout)\n\t\t} else {\n\t\t\tserverTransport, err = NewTUnixSocket(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr)\n\t\t}\n\n\tdefault:\n\t\tserverNetwork = \"tcp\"\n\t\tif config.Engine.Rpc.SessionTimeout > 0 {\n\t\t\tserverTransport, err = thrift.NewTServerSocketTimeout(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr, config.Engine.Rpc.SessionTimeout)\n\t\t} else {\n\t\t\tserverTransport, err = thrift.NewTServerSocket(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr)\n\t\t}\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// dial zk before startup servants\n\t// because proxy servant is dependent upon zk\n\tif config.Engine.EtcdSelfAddr != \"\" {\n\t\tif err := etclib.Dial(config.Engine.EtcdServers); err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tlog.Debug(\"etcd connected: %+v\", config.Engine.EtcdServers)\n\t\t}\n\t}\n\n\t// when config loaded, create the servants\n\tthis.svt = servant.NewFunServantWrapper(config.Engine.Servants)\n\tthis.rpcProcessor = rpc.NewFunServantProcessor(this.svt)\n\tthis.svt.Start()\n\n\tthis.rpcServer = NewTFunServer(this,\n\t\tconfig.Engine.Rpc.PreforkMode,\n\t\tthis.rpcProcessor,\n\t\tserverTransport, transportFactory, protocolFactory)\n\tlog.Info(\"RPC server ready at %s:%s\", serverNetwork, config.Engine.Rpc.ListenAddr)\n\n\tthis.launchDashboard()\n\n\tdone = make(chan null.NullStruct)\n\tgo func() {\n\t\tif err = this.rpcServer.Serve(); err != nil {\n\t\t\tlog.Error(\"RPC server: %+v\", err)\n\t\t}\n\n\t\tdone <- null.Null\n\t}()\n\n\treturn done\n}", "func (m *Master) WorkerHandler(args *Args, reply *Reply) error {\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tif args.ReqType == AskForTask {\n\t\t\tm.assignTask(reply)\n\t\t} else {\n\t\t\tm.finishTask(args)\n\t\t}\n\t\twg.Done()\n\t}()\n\twg.Wait()\n\treturn nil\n}", "func Worker(mapf func(string, string) []KeyValue,\n\t\t\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\t// TODO: maybe use a channel for in-process comm?\n\t// determine task state to know which master RPC to call\n\t//reply := CallRegisterIdle()\n\tvar reply *RegisterIdleReply\n\n\t//for workerInfo.State == IDLE || workerInfo.State == COMPLETED {\n\tfor {\n\n\t\tif workerInfo.State == IDLE {\n\t\t\treply = CallRegisterIdle()\n\t\t\tif reply == nil {\n\t\t\t\tworker_logger.Error(\"Got Error!!!!!!\")\n\t\t\t}\n\t\t} else if workerInfo.State == COMPLETED {\n\t\t\treply = CallCompletedTask() // override reply\n\t\t\t//if reply != nil {\n\t\t\t//\tresetWorkerInfo()\n\t\t\t//\tworkerInfo.State = IDLE\n\t\t\t//}\n\t\t\tif reply == nil {\n\t\t\t\tworker_logger.Error(\"Got errror!!!!!!!!\")\n\t\t\t}\n\t\t} else {\n\t\t\tworker_logger.Error(\"Shouldn't be in IN_PROGRESS state here...\")\n\t\t}\n\n\t\t// TODO: maybe don't need a mutex?\n\t\tif reply.MasterCommand == ASSIGN_TASK {\n\n\t\t\tworkerInfo.State = IN_PROGRESS\n\t\t\tworkerInfo.Id = reply.WorkerId\n\t\t\tworkerInfo.TaskType = reply.TaskType\n\t\t\tworkerInfo.TaskId = reply.TaskId\n\t\t\tworkerInfo.InputFileLoc = reply.InputFileLoc\n\t\t\tworkerInfo.NReduce = reply.NReduce\n\t\t\t//workerInfo.Progress = 0.0\n\n\t\t\t// TODO: replace this with broadcaster/observer design\n\t\t\tprogress_ch := make(chan float32)\n\t\t\tdone := make(chan struct{})\n\t\t\theartbeatStoped := make(chan struct {})\n\n\n\t\t\t// Actual computing job goroutine\n\t\t\tgo func() {\n\t\t\t\tif workerInfo.TaskType == MAP {\n\t\t\t\t\tdoMapTask(&workerInfo, mapf, progress_ch)\n\t\t\t\t} else if workerInfo.TaskType == REDUCE {\n\t\t\t\t\tdoReduceTask(&workerInfo, reducef, progress_ch)\n\t\t\t\t}/* else { // None task\n\t\t\t\t\tclose(progress_ch)\n\t\t\t\t}*/\n\n\t\t\t}()\n\n\t\t\t// Heartbeat gorountine\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-done:\n\t\t\t\t\t\t\tworker_logger.Debug(\"heartbeat job received done signal, stopping!\")\n\t\t\t\t\t\t\theartbeatStoped <- struct{}{}\n\t\t\t\t\t\t\tclose(heartbeatStoped)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tCallSendHeartbeat()\n\t\t\t\t\t\t\ttime.Sleep(1*time.Second)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}()\n\n\n\t\t\tfor progress := range progress_ch {\n\t\t\t\tworker_logger.Debug(fmt.Sprintf(\"Task(%s) progress: %f\", workerInfo.TaskId, progress))\n\t\t\t}\n\t\t\tdone <- struct{}{}\n\t\t\tclose(done)\n\t\t\t<- heartbeatStoped\n\n\t\t\t// Set result location & worker state\n\t\t\tworkerInfo.State = COMPLETED\n\n\t\t} else if reply.MasterCommand == STAND_BY {\n\t\t\tworker_logger.Debug(fmt.Sprintf(\"Got masterCommand: %s\", reply.MasterCommand))\n\t\t\ttime.Sleep(500*time.Millisecond)\n\t\t} else if reply.MasterCommand == PLEASE_EXIT {\n\t\t\tworker_logger.Info(fmt.Sprintf(\"Got masterCommand: %s\", reply.MasterCommand))\n\t\t\treturn\n\t\t}\n\n\t}\n\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\n}", "func main() {\n\n\t// Prepare some dependencies:\n\tlogger := logrus.New()\n\tstorer := new(storageMocks.FakeStorer)\n\n\t// Program the storer mock to respond with _something_:\n\tstorer.CreateCruftReturns(\"12345\", nil)\n\tstorer.ReadCruftReturns(nil, storage.ErrNotFound)\n\n\t// Inject the dependencies into a new Handler:\n\thandler := serviceHandler.New(logger, storer)\n\n\t// Make a new GRPC Server (usually I would have this in a common / shared library, and pre-load it with middleware built from our logger / instrumenter / tracer interfaces):\n\tgrpcServer := grpc.NewServer()\n\n\t// Register our Handler and GRPC Server with our generated service-proto code:\n\tserviceProto.RegisterExampleServer(grpcServer, handler)\n\n\t// Listen for connections:\n\tlistener, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Unable to start GRPC server on TCP address %s\", listenAddress)\n\t}\n\n\t// Start the GRPC server:\n\tif err := grpcServer.Serve(listener); err != nil {\n\t\tlogger.Fatalf(\"Unable to start the GRPC server: %v\", err)\n\t}\n}", "func RunRPC() error {\n\tvar servicename = viper.GetString(\"servicename\")\n\tif servicename == \"\" {\n\t\treturn errors.New(\"You must supply a valid servicename for logging using the `servicename` flag\")\n\t}\n\n\tvar rpcPort = viper.GetString(\"rpc-port\")\n\tif rpcPort == \"\" {\n\t\treturn errors.New(\"You must supply a valid port using the 'rpc-port' argument\")\n\t}\n\n\tvar lis, err = net.Listen(\"tcp\", \":\"+rpcPort)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to initialize TCP listen\")\n\t}\n\n\tdefer func() {\n\t\tvar err = lis.Close()\n\t\tif err != nil {\n\t\t\t// log\n\t\t}\n\t}()\n\n\t// Switch on a config file\n\t// switch {}\n\n\tds, err := datastore.New(phdstore.DSConfig{\n\t\tContext: context.Background(),\n\t\tServiceAccountFile: \"/Users/sgg7269/Documents/serviceAccountFiles/ds-serviceaccount.json\",\n\t\tProjectID: \"phdigidev\",\n\t\tNamespace: \"storage_test\",\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"handlers.NewGeosearch\")\n\t}\n\n\t// Try to make a new Geosearch before even starting the server\n\ts, err := handlers.New(ds)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"handlers.NewGeosearch\")\n\t}\n\n\tvar rpcServer = grpc.NewServer(\n\t\tgrpc.StatsHandler(&ocgrpc.ServerHandler{\n\t\t\tStartOptions: trace.StartOptions{\n\t\t\t\tSampler: trace.AlwaysSample(),\n\t\t\t},\n\t\t}))\n\n\tpb.RegisterStorageServer(rpcServer, s)\n\n\t// log\n\treturn rpcServer.Serve(lis)\n}", "func (r *rpcClientService) Call(serviceMethod string, args interface{},\n reply interface{}) error {\n\n if r == nil {\n return fmt.Errorf(\"error in rpc: client is nil\")\n }\n if r.rpcCh == nil {\n return fmt.Errorf(\"error in rpc client setup: channel is nil\")\n }\n buf, errJSON := json.Marshal(args)\n if errJSON != nil {\n glog.Error(\"error in marshaling args:: \", errJSON)\n return fmt.Errorf(\"error in marshaling args:: %v\", errJSON)\n }\n\n replyCh := make(chan *httpRPCRsp)\n state := sendRPCState{Method: serviceMethod, Args: buf, ReplyCh: replyCh}\n\n // send it on the rpc channel to the startClient loop\n glog.V(2).Info(\"sending rpc on channel: \", serviceMethod)\n\n select {\n case r.rpcCh <- &state:\n glog.V(2).Info(\"queued rpc call\")\n case <-r.stopCh:\n glog.V(2).Info(\"abandoning rpc call\")\n return ErrClient\n }\n\n // Now block on the response channel. Timeouts are implemented per request\n // in the client so we do not need to check for timeouts here.\n var rsp *httpRPCRsp\n select {\n case rsp = <-replyCh:\n glog.V(2).Infof(\"received response for rpc Call\")\n case <-r.stopCh:\n glog.V(2).Info(\"abandoning rpc call after sending\")\n return ErrDisconnect\n }\n\n // This can happen when stopCh gets closed due to connection errors.\n if rsp == nil {\n glog.Error(\"error in rpc response\")\n reply = nil\n return ErrDisconnect\n }\n if rsp.Status != nil {\n return rsp.Status\n }\n glog.V(1).Infof(\"rpc response succeeded with size: %d\", len(rsp.Reply))\n glog.V(3).Infof(\"rpc response reply: %+v, size: %d\", rsp.Reply,\n len(rsp.Reply))\n // success, let's unmarshal\n errRsp := json.Unmarshal(rsp.Reply, reply)\n if errRsp != nil {\n glog.Error(\"error unmarshaling RPC reply: \", errRsp)\n return errRsp\n }\n return nil\n}", "func caller(msgType int) MyReply {\n\targs := MyArgs{}\n\targs.MessageType = msgType\n\treply := MyReply{}\n\tcall(\"Master.Handler\", &args, &reply)\n\n\treturn reply\n}", "func rpc_call(reqMethod string, reqParam interface{}, ip string, port int) Node {\n\n\ttempClient, _ := jsonrpc.Dial(serverInfo1.Protocol, ip+\":\"+strconv.Itoa(port))\n\tdefer tempClient.Close()\n\tvar resp Node\n\terr := tempClient.Call(\"DICT3.\"+reqMethod, reqParam, &resp)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Node{}\n\t}\n\treturn resp\n}", "func (client *Client) Do(funcname string, data []byte, flag byte) (handle string, err error) {\n var datatype uint32\n if flag & JOB_LOW == JOB_LOW {\n if flag & JOB_BG == JOB_BG {\n datatype = common.SUBMIT_JOB_LOW_BG\n } else {\n datatype = common.SUBMIT_JOB_LOW\n }\n } else if flag & JOB_HIGH == JOB_HIGH {\n if flag & JOB_BG == JOB_BG {\n datatype = common.SUBMIT_JOB_HIGH_BG\n } else {\n datatype = common.SUBMIT_JOB_HIGH\n }\n } else if flag & JOB_BG == JOB_BG {\n datatype = common.SUBMIT_JOB_BG\n } else {\n datatype = common.SUBMIT_JOB\n }\n\n uid := strconv.Itoa(int(client.ai.Id()))\n l := len(funcname) + len(uid) + len(data) + 2\n rel := make([]byte, 0, l)\n rel = append(rel, []byte(funcname)...) // len(funcname)\n rel = append(rel, '\\x00') // 1 Byte\n rel = append(rel, []byte(uid)...) // len(uid)\n rel = append(rel, '\\x00') // 1 Byte\n rel = append(rel, data...) // len(data)\n client.writeJob(newJob(common.REQ, datatype, rel))\n // Waiting for JOB_CREATED\n select {\n case job := <-client.jobCreated:\n return string(job.Data), nil\n case <-time.After(client.TimeOut):\n return \"\", common.ErrJobTimeOut\n }\n return\n}", "func CallRpc(addr string, rid uint16, sendFun, recvFun func(*common.NetPack)) {\n\tbuf := common.NewNetPackCap(64)\n\tbuf.SetOpCode(rid)\n\tsendFun(buf)\n\tb := PostReq(addr+\"client_rpc\", buf.DataPtr)\n\tif recvFun != nil {\n\t\tb2 := common.Decompress(b)\n\t\trecvFun(common.NewNetPack(b2))\n\t}\n}", "func (r *Runner) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tr.rpc.ServeHTTP(w, req)\n}", "func setUpRPC(nodeRPC string) {\n\trpcServ := new(Service)\n\trpc.Register(rpcServ)\n\trpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\tif err != nil {\n\t\tlog.Fatal(\"listen error:\", err)\n\t}\n\tl, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tfor i := 0; i >= 0; i++ {\n\t\tconn, _ := l.AcceptTCP()\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t\tgo rpc.ServeConn(conn)\n\t\tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tdefer conn.Close()\n\t}\n\tl.Close()\n\n\t// rpcServ := new(FTService)\n\t// rpc.Register(rpcServ)\n\t// rpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\t// if err != nil {\n\t// \tlog.Fatal(\"listen error:\", err)\n\t// }\n\t// l, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\t// if e != nil {\n\t// \tlog.Fatal(\"listen error:\", e)\n\t// }\n\t// for i := 0; i >= 0; i++ {\n\t// \tconn, _ := l.AcceptTCP()\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t// \trpc.ServeConn(conn)\n\t// \tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \t//defer conn.Close()\n\t// }\n\t// l.Close()\n\n}", "func (s *Server) RunRPC(ctx context.Context, wg *sync.WaitGroup) error {\n\twg.Add(1)\n\n\tl, err := net.Listen(\"tcp\", s.GRPCListen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrvr := grpc.NewServer()\n\tpb.RegisterRegistryServer(srvr, s)\n\n\t// Shutdown procedure.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tlog.Println(\"Shutting down gRPC listener\")\n\n\t\tsrvr.GracefulStop()\n\n\t\tif err := l.Close(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\twg.Done()\n\t}()\n\n\t// Background the listener.\n\tgo func() {\n\t\tlog.Printf(\"gRPC up: %s\\n\", s.GRPCListen)\n\t\tif err := srvr.Serve(l); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func main() {\n\n\tconst apiName = \"handle1\"\n\ttStr := `_` + I.ToS(time.Now().UnixNano())\n\tif len(os.Args) > 1 {\n\t\tapp := fiber.New()\n\n\t\tmode := os.Args[1]\n\t\tswitch mode {\n\t\tcase `apiserver`:\n\t\t\tapp.Get(\"/\", func(c *fiber.Ctx) error {\n\t\t\t\treturn c.SendString(I.ToS(rand.Int63()) + tStr)\n\t\t\t})\n\n\t\tcase `apiproxy`:\n\t\t\t// connect as request on request-reply\n\n\t\t\tconst N = 8\n\t\t\tcounter := uint32(0)\n\t\t\tncs := [N]*nats.Conn{}\n\t\t\tmutex := sync.Mutex{}\n\t\t\tconn := func() *nats.Conn {\n\t\t\t\tidx := atomic.AddUint32(&counter, 1) % N\n\t\t\t\tnc := ncs[idx]\n\t\t\t\tif nc != nil {\n\t\t\t\t\treturn nc\n\t\t\t\t}\n\t\t\t\tmutex.Lock()\n\t\t\t\tdefer mutex.Unlock()\n\t\t\t\tif ncs[idx] != nil {\n\t\t\t\t\treturn ncs[idx]\n\t\t\t\t}\n\t\t\t\tnc, err := nats.Connect(\"127.0.0.1\")\n\t\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\t\tncs[idx] = nc\n\t\t\t\treturn nc\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, nc := range ncs {\n\t\t\t\t\tif nc != nil {\n\t\t\t\t\t\tnc.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// handler\n\t\t\tapp.Get(\"/\", func(c *fiber.Ctx) error {\n\t\t\t\tmsg, err := conn().Request(apiName, []byte(I.ToS(rand.Int63())), time.Second)\n\t\t\t\tif L.IsError(err, `nc.Request`) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Use the response\n\t\t\t\treturn c.SendString(string(msg.Data))\n\t\t\t})\n\t\tdefault:\n\t\t}\n\n\t\tlog.Println(mode + ` started ` + tStr)\n\t\tlog.Fatal(app.Listen(\":3000\"))\n\n\t} else {\n\t\t// worker\n\t\tlog.Println(`worker started ` + tStr)\n\n\t\tnc, err := nats.Connect(\"127.0.0.1\")\n\t\tL.PanicIf(err, `nats.Connect`)\n\t\tdefer nc.Close()\n\n\t\tconst queueName = `myqueue`\n\n\t\t//// connect as reply on request-reply (sync)\n\t\t//sub, err := nc.QueueSubscribeSync(apiName, queueName)\n\t\t//L.PanicIf(err, `nc.SubscribeSync`)\n\t\t//\n\t\t////Wait for a message\n\t\t//for {\n\t\t//\tmsg, err := sub.NextMsgWithContext(context.Background())\n\t\t//\tL.PanicIf(err, `sub.NextMsgWithContext`)\n\t\t//\n\t\t//\terr = msg.Respond([]byte(string(msg.Data) + tStr))\n\t\t//\tL.PanicIf(err, `msg.Respond`)\n\t\t//}\n\n\t\t//// channel (async) -- error slow consumer\n\t\t//ch := make(chan *nats.Msg, 1)\n\t\t//_, err = nc.ChanQueueSubscribe(apiName, queueName, ch)\n\t\t//L.PanicIf(err, `nc.ChanSubscribe`)\n\t\t//for {\n\t\t//\tselect {\n\t\t//\tcase msg := <-ch:\n\t\t//\t\tL.PanicIf(msg.Respond([]byte(string(msg.Data)+tStr)), `msg.Respond`)\n\t\t//\t}\n\t\t//}\n\n\t\t// callback (async)\n\t\t_, err = nc.QueueSubscribe(apiName, queueName, func(msg *nats.Msg) {\n\t\t\tres := string(msg.Data) + tStr\n\t\t\tL.PanicIf(msg.Respond([]byte(res)), `msg.Respond`)\n\t\t})\n\n\t\tvar line string\n\t\tfmt.Scanln(&line) // wait for input so not exit\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\t//远程调用Master.Example(args, reply)\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\tfmt.Println(err)\n\treturn false\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\tfor {\n\t\thargs := HandlerArgs{}\n\t\threply := HandlerReply{}\n\n\t\tcall(\"Coordinator.Handler\", &hargs, &hreply)\n\t\t//log.Println(\"hreply\", hreply)\n\t\tif hreply.JobType == \"map\" {\n\n\t\t\tfile, err := os.Open(hreply.MapFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot open %v\", hreply.MapFile)\n\t\t\t}\n\t\t\tcontent, err := ioutil.ReadAll(file)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot read %v\", hreply.MapFile)\n\t\t\t}\n\t\t\tfile.Close()\n\t\t\tkva := mapf(hreply.MapFile, string(content))\n\n\t\t\ttotal := []*json.Encoder{}\n\n\t\t\tfor i := 0; i < hreply.ReduceNum; i++ {\n\t\t\t\ttmp, err := os.Create(fmt.Sprintf(\"mr-%v-%v.json\", hreply.MapIndex, i))\n\t\t\t\tdefer tmp.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tenc := json.NewEncoder(tmp)\n\t\t\t\ttotal = append(total, enc)\n\t\t\t}\n\n\t\t\tfor _, onekva := range kva {\n\t\t\t\tcurr := total[ihash(onekva.Key)%10]\n\t\t\t\tcurr.Encode(&onekva)\n\t\t\t}\n\t\t\tlog.Printf(\"map job mr-%v finished\", hreply.MapIndex)\n\n\t\t\tnargs := NotifyArgs{}\n\t\t\tnreply := NotifyReply{}\n\t\t\tnargs.NotifyType = \"map\"\n\t\t\tnargs.NotifyIndex = hreply.MapIndex\n\n\t\t\tcall(\"Coordinator.Notify\", &nargs, &nreply)\n\n\t\t} else if hreply.JobType == \"reduce\" {\n\n\t\t\tkva := []KeyValue{}\n\t\t\tfor i := 0; i < hreply.MapNum; i++ {\n\t\t\t\ttmp, err := os.Open(fmt.Sprintf(\"mr-%v-%v.json\", i, hreply.ReduceIndex))\n\t\t\t\tdefer tmp.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tdec := json.NewDecoder(tmp)\n\n\t\t\t\tfor {\n\t\t\t\t\tvar kv KeyValue\n\t\t\t\t\tif err := dec.Decode(&kv); err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tkva = append(kva, kv)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsort.Sort(ByKey(kva))\n\t\t\toname := fmt.Sprintf(\"mr-out-%v\", hreply.ReduceIndex)\n\t\t\tofile, _ := os.Create(oname)\n\n\t\t\ti := 0\n\t\t\tfor i < len(kva) {\n\t\t\t\tj := i + 1\n\t\t\t\tfor j < len(kva) && kva[j].Key == kva[i].Key {\n\t\t\t\t\tj++\n\t\t\t\t}\n\t\t\t\tvalues := []string{}\n\t\t\t\tfor k := i; k < j; k++ {\n\t\t\t\t\tvalues = append(values, kva[k].Value)\n\t\t\t\t}\n\t\t\t\toutput := reducef(kva[i].Key, values)\n\n\t\t\t\t// this is the correct format for each line of Reduce output.\n\t\t\t\tfmt.Fprintf(ofile, \"%v %v\\n\", kva[i].Key, output)\n\n\t\t\t\ti = j\n\t\t\t}\n\t\t\tlog.Printf(\"reduce job mr-%v finished\", hreply.ReduceIndex)\n\n\t\t\tnargs := NotifyArgs{}\n\t\t\tnreply := NotifyReply{}\n\t\t\tnargs.NotifyType = \"reduce\"\n\t\t\tnargs.NotifyIndex = hreply.ReduceIndex\n\n\t\t\tcall(\"Coordinator.Notify\", &nargs, &nreply)\n\n\t\t} else if hreply.JobType == \" retry\" {\n\t\t\t//log.Println(\"retry--------------\")\n\t\t} else if hreply.JobType == \"alldone\" {\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\t//log.Println(\"sleeping 1 second\")\n\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t}\n\t}\n\t// uncomment to send the Example RPC to the coordinator.\n\t// CallExample()\n\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\tworkID := RegisterWorker()\n\n\tfor {\n\t\ttask := RequestTask(workID)\n\t\tif !task.Alive {\n\t\t\tfmt.Printf(\"Worker get task is not alive, %d\\n\", workID)\n\t\t\treturn\n\t\t}\n\t\tDoTask(task, workID, mapf, reducef)\n\t}\n\n\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\n}", "func init(){\n\tskeleton.RegisterChanRPC(reflect.TypeOf(&msg.Hello{}), handleHello)\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\tfor{\n\t\tgetNext := GetTask(mapf, reducef)\n\t\tif(!getNext){\n\t\t\tbreak\n\t\t}\n\t}\n\t\n}", "func listenRPC(app *core.App, config standaloneConfig) error {\n\t// Initialize the JSON RPC WebSocket server (but don't start it yet).\n\trpcAddr := fmt.Sprintf(\":%d\", config.RPCPort)\n\trpcHandler := &rpcHandler{\n\t\tapp: app,\n\t}\n\trpcServer, err := rpc.NewServer(rpcAddr, rpcHandler)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tgo func() {\n\t\t// Wait for the server to start listening and select an address.\n\t\tfor rpcServer.Addr() == nil {\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t\tlog.WithField(\"address\", rpcServer.Addr().String()).Info(\"started RPC server\")\n\t}()\n\treturn rpcServer.Listen()\n}", "func (s *Server) RPC(method string, reply interface{}) error {\n\tcodec := &inmemCodec{\n\t\tmethod: method,\n\t\treply: reply,\n\t}\n\tif err := s.rpcServer.ServeRequest(codec); err != nil {\n\t\treturn err\n\t}\n\treturn codec.err\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\tfor {\n\t\ttime.Sleep(time.Second)\n\n\t\treq := GetTaskReq{}\n\t\treq.No = 1\n\t\trsp := GetTaskRsp{}\n\t\tok := call(\"Master.GetTask\", &req, &rsp)\n\t\tif ok {\n\t\t\tfmt.Println(rsp.Status, rsp.TaskID, len(rsp.Filename) > 0)\n\t\t\tif rsp.Status == \"Wait\" {\n\t\t\t\t// do nothing\n\t\t\t} else if rsp.Status == \"Task\" {\n\t\t\t\tdoTask(&req, &rsp, mapf, reducef)\n\t\t\t} else if rsp.Status == \"Exit\" {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"unknow status\\n\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"rpc error\")\n\t\t}\n\n\t}\n\t// uncomment to send the Example RPC to the master.\n\tCallExample()\n\n}", "func main() {\n\n\tif (len(os.Args) != 4 && len(os.Args) != 5) {\n\t\tErrorCommandArguments()\n\t\treturn\n\t}\n\n\tgrpcHostname := os.Args[1]\n\n\tgrpcPort := os.Args[2]\n\n\n\tc, conn := CreateGrpcConnection(grpcHostname, grpcPort)\n\tdefer conn.Close()\n\n\tmodeChoice := os.Args[3]\n\tvar response *grpc_health.Message\n\n\tvar err error \n\tswitch modeChoice {\n\n\tcase \"sayhello\":\n\t\tresponse, err = c.SayHello(context.Background(), &grpc_health.Message{Body: \"Hello From Client! I'll wait for your reply!!!\"})\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when calling SayHello or SayBonjour: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Response from server: %s\", response.Body)\n\t\n\tcase \"clusterhealth\":\n\t\tvar clusterinfo *grpc_health.ClusterInfo\n\t\tclusterinfo, err = c.GetClusterStatus(context.Background(), &grpc_health.Message{Body: \"Asking Cluster status\"})\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when calling GetClusterStatus: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Cluster name: %s\", clusterinfo.Name)\n\t\tlog.Printf(\"Cluster status: %s\", clusterinfo.Status)\n\t\tlog.Printf(\"Cluster nb nodes: %s\", clusterinfo.Nodes)\n\t\n\tcase \"indexhealth\":\n\t\tif (len(os.Args) != 5) {\n\t\t\tErrorCommandArguments()\n\t\t\treturn\n\t\t} \n\t\t\n\t\tindiceName := os.Args[4]\n\t\tvar indiceInfo *grpc_health.IndiceInfo\n\t\tindiceInfo, err = c.GetIndiceStatus(context.Background(), &grpc_health.IndiceName{Indicename: indiceName})\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when calling GetClusterStatus: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Response from server:\")\n\t\tlog.Printf(\"Indice name: %s\", indiceInfo.Indicename)\n\t\tlog.Printf(\"Indice status: %s\", indiceInfo.Status)\n\t\tlog.Printf(\"Indice health: %s\", indiceInfo.Health)\n\t\tlog.Printf(\"Indice uuid: %s\", indiceInfo.Uuid)\n\t\n\tcase \"listindices\":\n\t\tvar listIndices *grpc_health.ListIndices\n\t\tlistIndices, err = c.GetIndicesList(context.Background(), &grpc_health.Message{Body: \"Hello From Client! I'll wait for your reply!!!\"})\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when calling GetIndicesList: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Nb indices : %s\", listIndices.NbIndices)\n\n\t\tnbIndices, err := strconv.Atoi(listIndices.NbIndices)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when converting number of indices: %s\", err)\n\t\t}\n\n\t\tvar indiceInfo *grpc_health.IndiceInfo\n\t\tfor i := 0; i < nbIndices; i++ {\n\t\t\tindiceInfo = listIndices.Indicelist[i]\n\t\t\tlog.Printf(\"Index [ %s ] - Status : %s - Health : %s - Uuid : %s \", indiceInfo.Indicename, indiceInfo.Status, indiceInfo.Health, indiceInfo.Uuid)\n\t\t}\n\t\n\tcase \"createindex\":\n\t\tif (len(os.Args) != 5) {\n\t\t\tErrorCommandArguments()\n\t\t\treturn\n\t\t} \n\t\tindiceName := os.Args[4]\n\t\tresponse, err = c.CreateIndexInCluster(context.Background(), &grpc_health.IndiceName{Indicename: indiceName})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Create index request response : %s\", err)\n\t\t}\n\t\tlog.Printf(\"Create index request succeeded. %s\", response.Body)\n\n\tcase \"deleteindex\":\n\t\tif (len(os.Args) != 5) {\n\t\t\tErrorCommandArguments()\n\t\t\treturn\n\t\t} \n\t\t\n\t\tindiceName := os.Args[4]\n\t\tresponse, err = c.DeleteIndexInCluster(context.Background(), &grpc_health.IndiceName{Indicename: indiceName})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error when deleting index in Cluster: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Delete index request response : %s\", response.Body)\n\t\n\tdefault:\n\t\tErrorCommandArguments()\n\t\treturn\n\n\t}\n\n}", "func main() {\n\tfmt.Println(\"net/rpc Arith server\")\n\tarith := new(nrpc.Arith) // nrpc from import statement // HL\n\trpc.Register(arith)\n\trpc.HandleHTTP()\n\tlis, err := net.Listen(\"tcp\", \":1234\")\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to listen on port 1234: %v\", err)\n\t}\n\n\tgo http.Serve(lis, nil)\n\tselect {} // wait forever\n}", "func main() {\n\n\thandleRequests()\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t//Your worker implementation here.\n\tmJobChan := make(chan MRJob)\n\trJobChan := make(chan MRJob)\n\tctx, cancel := context.WithCancel(context.Background()) // used to manage the MR Job\n\targs := MRArgs{\n\t\tStatus: \"INITIAL\",\n\t}\n\n\tgo requestJob(cancel, args, mJobChan, rJobChan)\n\n\tfor {\n\t\tselect {\n\t\tcase mJob := <-mJobChan:\n\t\t\terr := doMap(mapf, mJob)\n\t\t\tif err != nil {\n\t\t\t\targs.Status = \"FAILED\"\n\t\t\t} else {\n\t\t\t\targs.Status = \"FINISHED\"\n\t\t\t}\n\t\t\targs.MId = mJob.JobNum\n\t\t\targs.RId = -1\n\t\t\targs.JobType = \"MAP\"\n\t\t\tlog.Printf(\"MAP: %v, %v request Job\", args.Status, args.MId)\n\t\t\tgo requestJob(cancel, args, mJobChan, rJobChan)\n\t\tcase rJob := <-rJobChan:\n\t\t\terr := doReduce(reducef, rJob)\n\t\t\tif err != nil {\n\t\t\t\targs.Status = \"FAILED\"\n\t\t\t} else {\n\t\t\t\targs.Status = \"FINISHED\"\n\t\t\t}\n\t\t\targs.MId = -1\n\t\t\targs.RId = rJob.JobNum\n\t\t\targs.JobType = \"REDUCE\"\n\t\t\tlog.Printf(\"REDUCE: %v %v, request Job\", args.Status, args.RId)\n\t\t\tgo requestJob(cancel, args, mJobChan, rJobChan)\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"Worker is stopped\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// uncomment to send the Example RPC to the master.\n\t//CallExample()\n}", "func main() {\n handleRequests()\n}", "func (server *Server) callRPCAndFormatReply(buf []byte, ci *clientInfo, jReq *jsonRequest) (ior *ioReply) {\n\tvar (\n\t\terr error\n\t\treturnValues []reflect.Value\n\t\ttypOfReq reflect.Type\n\t\tdummyReq interface{}\n\t)\n\n\t// Setup the reply structure with common fields\n\tior = &ioReply{}\n\trid := jReq.RequestID\n\tjReply := &jsonReply{MyUniqueID: jReq.MyUniqueID, RequestID: rid}\n\n\tma := server.svrMap[jReq.Method]\n\tif ma != nil {\n\n\t\t// Another unmarshal of buf to find the parameters specific to\n\t\t// this RPC\n\t\ttypOfReq = ma.request.Elem()\n\t\tdummyReq = reflect.New(typOfReq).Interface()\n\n\t\tsReq := svrRequest{}\n\t\tsReq.Params[0] = dummyReq\n\t\terr = json.Unmarshal(buf, &sReq)\n\t\tif err != nil {\n\t\t\tserver.logger.Fatalf(\"Unmarshal sReq: %+v err: %v\", sReq, err)\n\t\t\treturn\n\t\t}\n\t\treq := reflect.ValueOf(dummyReq)\n\t\tcid := reflect.ValueOf(ci.myUniqueID)\n\n\t\t// Create the reply structure\n\t\ttypOfReply := ma.reply.Elem()\n\t\tmyReply := reflect.New(typOfReply)\n\n\t\t// Call the method\n\t\tfunction := ma.methodPtr.Func\n\t\tt := time.Now()\n\t\tif ma.passClientID {\n\t\t\treturnValues = function.Call([]reflect.Value{server.receiver, cid, req, myReply})\n\t\t} else {\n\t\t\treturnValues = function.Call([]reflect.Value{server.receiver, req, myReply})\n\t\t}\n\t\tci.setMethodStats(jReq.Method, uint64(time.Since(t).Microseconds()))\n\n\t\t// The return value for the method is an error.\n\t\terrInter := returnValues[0].Interface()\n\t\tif errInter == nil {\n\t\t\tjReply.Result = myReply.Elem().Interface()\n\t\t} else {\n\t\t\te, ok := errInter.(error)\n\t\t\tif !ok {\n\t\t\t\tserver.logger.Fatalf(\"Call returnValues invalid cast errInter: %+v\", errInter)\n\t\t\t}\n\t\t\tjReply.ErrStr = e.Error()\n\t\t}\n\t} else {\n\t\t// TODO - figure out if this is the correct error\n\n\t\t// Method does not exist\n\t\tjReply.ErrStr = fmt.Sprintf(\"errno: %d\", unix.ENOENT)\n\t}\n\n\t// Convert response into JSON for return trip\n\tior.JResult, err = json.Marshal(jReply)\n\tif err != nil {\n\t\tserver.logger.Fatalf(\"Unable to marshal jReply: %+v err: %v\", jReply, err)\n\t}\n\n\treturn\n}", "func main() {\n initApplicationConfiguration()\n runtime.GOMAXPROCS(2) // in order for the rpc and http servers to work in parallel\n\n go servers.StartRPCServer()\n servers.StartHTTPServer()\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\t// uncomment to send the Example RPC to the coordinator.\n\t// CallExample()\n\n\tfor {\n\t\trequestArgs := RequestTaskArgs{}\n\t\trequestReply := RequestTaskReply{}\n\t\tfinishArgs := FinishTaskArgs{}\n\t\tfinishReply := FinishTaskReply{}\n\t\tif !call(\"Coordinator.RequestTask\", &requestArgs, &requestReply) {\n\t\t\tbreak\n\t\t}\n\t\tfinishArgs.Id = requestReply.Id\n\t\tfinishArgs.Type = requestReply.Type\n\t\tif requestReply.Type == Map {\n\t\t\tmapper(&requestReply, mapf)\n\t\t\tcall(\"Coordinator.FinishTask\", &finishArgs, &finishReply)\n\t\t} else if requestReply.Type == Reduce {\n\t\t\treducer(&requestReply, reducef)\n\t\t\tcall(\"Coordinator.FinishTask\", &finishArgs, &finishReply)\n\t\t} else if requestReply.Type == Exit {\n\t\t\tbreak\n\t\t} else {\n\t\t\tlog.Fatalf(\"unknown task type %v\", requestReply.Type)\n\t\t}\n\t}\n}", "func fire(worker string, rpcname string, args interface{}, reply interface{}, group *sync.WaitGroup, registerChan chan string) {\n\tres := call(worker, rpcname, args, reply)\n\tif res {\n\t\tgroup.Done()\n\t\tregisterChan <- worker\n\t} else {\n\t\tworker := <- registerChan\n\t\tfire(worker, rpcname, args, reply, group, registerChan)\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tc, err := rpc.DialHTTP(\"unix\", \"mr-socket\")\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func (c *Client) rpc(method, u string, req, resp interface{}) (*http.Response, error) {\n\tvar r io.Reader\n\tvar contentType string\n\tswitch req := req.(type) {\n\tcase nil:\n\tcase io.Reader:\n\t\tr = req\n\tcase url.Values:\n\t\tr = strings.NewReader(req.Encode())\n\t\tcontentType = \"application/x-www-form-urlencoded\"\n\tdefault:\n\t\tb, err := json.Marshal(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr = bytes.NewReader(b)\n\t\tcontentType = \"application/json\"\n\t}\n\n\threq, err := http.NewRequest(method, u, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif contentType != \"\" {\n\t\threq.Header.Set(\"Content-Type\", contentType)\n\t}\n\n\thresp, err := c.Do(hreq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer hresp.Body.Close()\n\tif hresp.StatusCode/100 != 2 {\n\t\treturn nil, StatusError(hresp.StatusCode)\n\t}\n\tswitch body := resp.(type) {\n\tcase nil:\n\tcase io.Writer:\n\t\t_, err = io.Copy(body, hresp.Body)\n\tdefault:\n\t\terr = json.NewDecoder(hresp.Body).Decode(body)\n\t}\n\treturn hresp, err\n}", "func inprocSend(rpcCmd common.RpcCmd, requestData interface{}, responseData interface{}) error {\n\tswitch rpcCmd {\n\tcase common.ERpcCmd.CopyJobPartOrder():\n\t\t*(responseData.(*common.CopyJobPartOrderResponse)) = ste.ExecuteNewCopyJobPartOrder(*requestData.(*common.CopyJobPartOrderRequest))\n\n\tcase common.ERpcCmd.ListJobs():\n\t\t*(responseData.(*common.ListJobsResponse)) = ste.ListJobs()\n\n\tcase common.ERpcCmd.ListJobSummary():\n\t\t*(responseData.(*common.ListJobSummaryResponse)) = ste.GetJobSummary(*requestData.(*common.JobID))\n\n\tcase common.ERpcCmd.ListSyncJobSummary():\n\t\t*(responseData.(*common.ListSyncJobSummaryResponse)) = ste.GetSyncJobSummary(*requestData.(*common.JobID))\n\n\tcase common.ERpcCmd.ListJobTransfers():\n\t\t*(responseData.(*common.ListJobTransfersResponse)) = ste.ListJobTransfers(requestData.(common.ListJobTransfersRequest))\n\n\tcase common.ERpcCmd.PauseJob():\n\t\tresponseData = ste.CancelPauseJobOrder(requestData.(common.JobID), common.EJobStatus.Paused())\n\n\tcase common.ERpcCmd.CancelJob():\n\t\t*(responseData.(*common.CancelPauseResumeResponse)) = ste.CancelPauseJobOrder(requestData.(common.JobID), common.EJobStatus.Cancelled())\n\n\tcase common.ERpcCmd.ResumeJob():\n\t\t*(responseData.(*common.CancelPauseResumeResponse)) = ste.ResumeJobOrder(*requestData.(*common.ResumeJobRequest))\n\n\tcase common.ERpcCmd.GetJobFromTo():\n\t\t*(responseData.(*common.GetJobFromToResponse)) = ste.GetJobFromTo(*requestData.(*common.GetJobFromToRequest))\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unrecognized RpcCmd: %q\", rpcCmd.String()))\n\t}\n\treturn nil\n}", "func workerTask() {\n\tworker, err := zmq4.NewSocket(zmq4.REQ)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"ipc://backend.ipc\")\n\tworker.SendMessage(WorkerReady)\n\n\tfor {\n\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tmsg[len(msg)-1] = \"OK\"\n\t\tworker.SendMessage(msg)\n\t}\n\n}", "func (d *Data) DoRPC(req datastore.Request, reply *datastore.Response) error {\n\tswitch req.TypeCommand() {\n\tcase \"set-nextlabel\":\n\t\tif len(req.Command) < 5 {\n\t\t\treturn fmt.Errorf(\"poorly formatted set-nextlabel command, see command-line help\")\n\t\t}\n\n\t\t// Parse the request\n\t\tvar uuidStr, dataName, cmdStr, labelStr string\n\t\treq.CommandArgs(1, &uuidStr, &dataName, &cmdStr, &labelStr)\n\n\t\tuuid, _, err := datastore.MatchingUUID(uuidStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdataservice, err := datastore.GetDataByUUIDName(uuid, dvid.InstanceName(dataName))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlmData, ok := dataservice.(*Data)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"instance %q of uuid %s was not a labelmap instance\", dataName, uuid)\n\t\t}\n\n\t\tnextLabelID, err := strconv.ParseUint(labelStr, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := lmData.SetNextLabelStart(nextLabelID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treply.Text = fmt.Sprintf(\"Set next label ID to %d.\\n\", nextLabelID)\n\t\treturn nil\n\n\tcase \"load\":\n\t\tif len(req.Command) < 5 {\n\t\t\treturn fmt.Errorf(\"poorly formatted load command, see command-line help\")\n\t\t}\n\t\t// Parse the request\n\t\tvar uuidStr, dataName, cmdStr, offsetStr string\n\t\tfilenames, err := req.FilenameArgs(1, &uuidStr, &dataName, &cmdStr, &offsetStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(filenames) == 0 {\n\t\t\treturn fmt.Errorf(\"need to include at least one file to add: %s\", req)\n\t\t}\n\n\t\toffset, err := dvid.StringToPoint(offsetStr, \",\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"illegal offset specification: %s: %v\", offsetStr, err)\n\t\t}\n\n\t\tvar addedFiles string\n\t\tif len(filenames) == 1 {\n\t\t\taddedFiles = filenames[0]\n\t\t} else {\n\t\t\taddedFiles = fmt.Sprintf(\"filenames: %s [%d more]\", filenames[0], len(filenames)-1)\n\t\t}\n\t\tdvid.Debugf(addedFiles + \"\\n\")\n\n\t\tuuid, versionID, err := datastore.MatchingUUID(uuidStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = datastore.AddToNodeLog(uuid, []string{req.Command.String()}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo func() {\n\t\t\tif err = d.LoadImages(versionID, offset, filenames); err != nil {\n\t\t\t\tdvid.Errorf(\"Cannot load images into data instance %q @ node %s: %v\\n\", dataName, uuidStr, err)\n\t\t\t}\n\t\t\tif err := datastore.SaveDataByUUID(uuid, d); err != nil {\n\t\t\t\tdvid.Errorf(\"Could not store metadata changes into data instance %q @ node %s: %v\\n\", dataName, uuidStr, err)\n\t\t\t}\n\t\t}()\n\t\treply.Text = fmt.Sprintf(\"Asynchronously loading %d files into data instance %q @ node %s (errors will be printed in server log) ...\\n\", len(filenames), dataName, uuidStr)\n\t\treturn nil\n\n\tcase \"composite\":\n\t\tif len(req.Command) < 6 {\n\t\t\treturn fmt.Errorf(\"poorly formatted composite command. See command-line help\")\n\t\t}\n\t\treturn d.createComposite(req, reply)\n\n\tcase \"dump\":\n\t\tif len(req.Command) < 6 {\n\t\t\treturn fmt.Errorf(\"poorly formatted dump command. See command-line help\")\n\t\t}\n\t\t// Parse the request\n\t\tvar uuidStr, dataName, cmdStr, dumpType, outPath string\n\t\treq.CommandArgs(1, &uuidStr, &dataName, &cmdStr, &dumpType, &outPath)\n\n\t\tuuid, v, err := datastore.MatchingUUID(uuidStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Setup output file\n\t\tf, err := os.OpenFile(outPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch dumpType {\n\t\tcase \"svcount\":\n\t\t\tgo d.writeSVCounts(f, outPath, v)\n\t\t\treply.Text = fmt.Sprintf(\"Asynchronously writing supervoxel counts for data %q, uuid %s to file: %s\\n\", d.DataName(), uuid, outPath)\n\t\tcase \"mappings\":\n\t\t\tgo d.writeFileMappings(f, outPath, v)\n\t\t\treply.Text = fmt.Sprintf(\"Asynchronously writing mappings for data %q, uuid %s to file: %s\\n\", d.DataName(), uuid, outPath)\n\t\tcase \"indices\":\n\t\t\tgo d.writeIndices(f, outPath, v)\n\t\t\treply.Text = fmt.Sprintf(\"Asynchronously writing label indices for data %q, uuid %s to file: %s\\n\", d.DataName(), uuid, outPath)\n\t\tdefault:\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown command. Data type '%s' [%s] does not support '%s' command\",\n\t\t\td.DataName(), d.TypeName(), req.TypeCommand())\n\t}\n}", "func (s *UserClient) RpcInvoke(req []byte) ([]byte, error) {\n\t// rpc.send\n\terr := s.rpc.Send(req)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\t// rpc.receive\n\treturn s.rpc.Receive()\n}", "func main() {\n\tgwMux := runtime.NewServeMux()\n\tendPoint := \"localhost:8081\"\n\topt := []grpc.DialOption{grpc.WithTransportCredentials(helper.GetClientCreds())}\n\t// prod\n\tif err := pbfiles.RegisterProdServiceHandlerFromEndpoint(context.Background(), gwMux, endPoint, opt); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// order\n\tif err := pbfiles.RegisterOrderServiceHandlerFromEndpoint(context.Background(), gwMux, endPoint, opt); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttpServer := &http.Server{\n\t\tAddr: \":8080\",\n\t\tHandler: gwMux,\n\t}\n\n\tif err := httpServer.ListenAndServe(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func mainHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, HEAD\")\n\n\tif r.Method == \"POST\" {\n\t\tvar req dlRequest\n\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, \"bad request\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// add to queue\n\t\tgo func(qreq *dlRequest) {\n\t\t\tm3u8.DlChan <- &m3u8.WJob{Type: m3u8.ListDL, URL: req.Url, DestPath: req.Path, Filename: req.Filename}\n\t\t}(&req)\n\t\tres := response{req.Url, req.Filename, \"Added to the queue\"}\n\t\tjson.NewEncoder(w).Encode(res)\n\t\treturn\n\t}\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tc, err := rpc.DialHTTP(\"unix\", \"mr-socket\")\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tlog.Fatal(err)\n\treturn false\n}", "func main() {\n\tHandleRequests( )\n}", "func svcHandler()", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\tc, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\t// sockname := masterSock()\n\t// c, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tlog.Println(err)\n\treturn false\n}", "func worker() {\n\tworker, err := zmq4.NewSocket(zmq4.DEALER)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"inproc://backend\")\n\n\tfor {\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tid, content := pop(msg)\n\n\t\treplies := rand.Intn(5)\n\t\tfor reply := 0; reply < replies; reply++ {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(1000)+1) * time.Millisecond)\n\t\t\tworker.SendMessage(id, content)\n\t\t}\n\t}\n}", "func main() {\n\texoRelay := helpers.ConnectExoRelay()\n\texoRelay.RegisterHandler(\"ping\", func(request exorelay.Request) {\n\t\terr := request.Reply(\"pong\", nil)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to send reply: %v\", err)\n\t\t}\n\t})\n\texoRelay.RegisterHandler(\"complex ping\", func(request exorelay.Request) {\n\t\tsearchMessage, err := request.Send(\"search\", nil)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to send search: %v\", err)\n\t\t}\n\t\tresultMessage, err := request.WaitForActivity(searchMessage.ActivityID, time.Second*5)\n\t\tif err != nil || resultMessage.Name != \"result\" {\n\t\t\t_, err = request.Send(\"complex ping error\", nil)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to send complex ping error: %v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terr = request.Reply(\"complex pong\", resultMessage.Payload)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to send complex pong: %v\", err)\n\t\t}\n\t})\n\truntime.Goexit()\n}", "func (sc *SnippetClient) RPC(ctx context.Context, timeout time.Duration, method string, args ...interface{}) (*JSONRPCResponse, error) {\n\t// Create and send the request.\n\treqID := sc.requestID\n\trequest := jsonRPCRequest{ID: reqID, Method: method, Params: make([]interface{}, 0)}\n\tif len(args) > 0 {\n\t\trequest.Params = args\n\t}\n\trequestBytes, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to marshal request to json\")\n\t}\n\ttesting.ContextLog(ctx, \"\\tRPC request: \", string(requestBytes))\n\n\tif err := sc.clientSend(requestBytes); err != nil {\n\t\treturn nil, err\n\t}\n\tsc.requestID++\n\n\t// Receive and process the response.\n\tvar res JSONRPCResponse\n\tb, err := sc.clientReceive(timeout)\n\ttesting.ContextLog(ctx, \"\\tRPC response: \", string(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := json.Unmarshal(b, &res); err != nil {\n\t\treturn nil, err\n\t}\n\tif res.Error != \"\" {\n\t\treturn nil, errors.Errorf(\"response error %v\", res.Error)\n\t}\n\tif res.ID != reqID {\n\t\treturn nil, errors.Errorf(\"response ID mismatch; expected %v, got %v\", reqID, res.ID)\n\t}\n\treturn &res, nil\n}", "func (s *grpcServer) dispatcher(stream grpc.Stream, methodName string,\n\tgetState func() (request proto.Message, response proto.Message, requestAttrs *mixerpb.Attributes, responseAttrs *mixerpb.Attributes, result *rpc.Status),\n\tworker func(ctx context.Context, requestBag *attribute.MutableBag, responseBag *attribute.MutableBag,\n\t\trequest proto.Message, response proto.Message)) error {\n\n\t// tracks attribute state for this stream\n\ttracker := s.attrMgr.NewTracker()\n\tdefer tracker.Done()\n\n\t// used to serialize sending on the grpc stream, since the grpc stream is not multithread-safe\n\tsendLock := &sync.Mutex{}\n\n\troot, ctx := s.tracer.StartRootSpan(stream.Context(), methodName)\n\tdefer root.Finish()\n\n\t// ensure pending stuff is done before leaving\n\twg := sync.WaitGroup{}\n\tdefer wg.Wait()\n\n\tfor {\n\t\trequest, response, requestAttrs, responseAttrs, result := getState()\n\n\t\t// get a single message\n\t\terr := stream.RecvMsg(request)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\tglog.Errorf(\"Stream error %s\", err)\n\t\t\treturn err\n\t\t}\n\n\t\trequestBag, err := tracker.ApplyRequestAttributes(requestAttrs)\n\t\tif err != nil {\n\t\t\tmsg := \"Request could not be processed due to invalid 'attribute_update'.\"\n\t\t\tglog.Error(msg, \"\\n\", err)\n\t\t\tdetails := status.NewBadRequest(\"attribute_update\", err)\n\t\t\t*result = status.InvalidWithDetails(msg, details)\n\n\t\t\tsendLock.Lock()\n\t\t\terr = s.sendMsg(stream, response)\n\t\t\tsendLock.Unlock()\n\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Unable to send gRPC response message: %v\", err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// throw the message into the work queue\n\t\twg.Add(1)\n\t\ts.gp.ScheduleWork(func() {\n\t\t\tspan, ctx2 := s.tracer.StartSpanFromContext(ctx, \"RequestProcessing\")\n\t\t\tspan.LogFields(log.Object(\"gRPC request\", request))\n\n\t\t\tresponseBag := attribute.GetMutableBag(nil)\n\n\t\t\t// do the actual work for the message\n\t\t\tworker(ctx2, requestBag, responseBag, request, response)\n\n\t\t\tsendLock.Lock()\n\t\t\ttracker.GetResponseAttributes(responseBag, responseAttrs)\n\t\t\terr := s.sendMsg(stream, response)\n\t\t\tsendLock.Unlock()\n\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Unable to send gRPC response message: %v\", err)\n\t\t\t}\n\n\t\t\trequestBag.Done()\n\t\t\tresponseBag.Done()\n\n\t\t\tspan.LogFields(log.Object(\"gRPC response\", response))\n\t\t\tspan.Finish()\n\n\t\t\twg.Done()\n\t\t})\n\t}\n}", "func Handler(ctx context.Context) (response Response, err error) {\n\n\tres, err := Worker()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tjsonRes, err := json.Marshal(res)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresponse = Response{\n\t\tStatusCode: 200,\n\t\tIsBase64Encoded: false,\n\t\tBody: string(jsonRes),\n\t\tHeaders: map[string]string{\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t}\n\n\treturn\n}", "func main() {\n\n\twait := make(chan struct{}, 0)\n\tRegisterCallback(\"ping\", pingCB())\n\tRegisterCallback(\"add\", addCB())\n\tRegisterErrorCallback(\"raiseError\", err)\n\tRegisterValue(\"wasmVal\", \"Hello World\")\n\n\t<-wait\n}", "func (c *MainChannelCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n funcName, args := stub.GetFunctionAndParameters()\n\n switch funcName {\n // 任务上传\n case \"requestUpload\":\n return requestUpload(stub, args)\n // 查询任务\n case \"requestQuery\":\n return requestQuery(stub, args)\n // 查询全部任务\n case \"requestQueryArr\":\n return requestQueryArr(stub, args)\n // 难度值上传\n case \"difficultyUpload\":\n return difficultyUpload(stub, args)\n // 难度值查询\n case \"difficultyQuery\":\n return difficultyQuery(stub, args)\n // 难度值统一查询\n case \"difficultyQueryArr\":\n return difficultyQueryArr(stub, args)\n // 判断胜利者\n case \"winnerUpload\":\n return winnerUpload(stub, args)\n // 查询胜利者\n case \"winnerQuery\":\n return winnerQuery(stub, args)\n // 查询全部胜利者\n case \"winnerQueryArr\":\n return winnerQueryArr(stub, args)\n // 子channel上传\n case \"subChannelUpload\":\n return subChannelUpload(stub, args)\n // 子channel查询\n case \"subChannelQuery\":\n return subChannelQuery(stub, args)\n // 数据上传\n case \"dataUpload\":\n return dataUpload(stub, args)\n // 查询数据\n case \"dataQuery\":\n return dataQuery(stub, args)\n // 数据统一查询\n case \"dataQueryArr\":\n return dataQueryArr(stub, args)\n // 奖励发放\n case \"rewardsUpload\":\n return rewardsUpload(stub, args)\n // 奖励获取\n case \"rewardsReceive\":\n return rewardsReceive(stub, args)\n }\n\n\treturn shim.Success(nil)\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func call(rpcname string, args interface{}, reply interface{}) bool {\n\t// c, err := rpc.DialHTTP(\"tcp\", \"127.0.0.1\"+\":1234\")\n\tsockname := masterSock()\n\tc, err := rpc.DialHTTP(\"unix\", sockname)\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func Tribes_Interpreter(mypayload TribePayload) {\n\n\tmycommand := GetJSONCommand(mypayload.TPbuffer)\n\n\tswitch mycommand {\n\n\tcase \"NOOP\":\n\t\tbreak // doing nothing\n\t\t//\n\t\t// Implementation of single post exchange\n\tcase \"HEREPOST\":\n\t\t// herepost just returns the requested post\n\t\terr := Tribes_BE_POST(mypayload.TPbuffer[0:mypayload.TPsize])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[UDP-INT] Cannot execute HEREPOST: %s \", err.Error())\n\t\t}\n\t\t// each function should have the full buffer when starting\n\t\t// the ones with BE are saving something.\n\t\t// the ones with FE are answeing back (so they need to know who to answer\n\t\t// all FE functions will return a []byte to shoot with Shoot_JSON\n\tcase \"GIMMEPOST\":\n\t\t// gimmepost just requires to send a post back\n\t\t// giving the messageID as argument\n\t\t// those functions starting with GIMME are asked to reply to the peer\n\t\t//\n\t\t// Implementation of PEERS exchange\n\tcase \"HEREPEERS\":\n\t\terr := Tribes_BE_PEERS(mypayload.TPbuffer[0:mypayload.TPsize])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[UDP-INT] Cannot execute HEREPEERS: %s \", err.Error())\n\t\t}\n\t\t// herepeers gives a list of known peers\n\tcase \"GIMMEPEERS\":\n\t\t// asks for a list of known peers\n\t\t//\n\t\t// Implementation of GROUPS exchange\n\tcase \"HEREGROUPS\":\n\t\terr := Tribes_BE_Groups(mypayload.TPbuffer[0:mypayload.TPsize])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[UDP-GRP] Cannot execute HEREGROUPS: %s \", err.Error())\n\t\t}\n\t\t// Receives the list of active groups\n\tcase \"GIMMEGROUPS\":\n\t\t// Asks for the list of active groups\n\t\t//\n\t\t// Implementation of group index: to have a list of messageIDs for a group\n\tcase \"HEREINDEX\":\n\t\t// Gives a list of MessageIDs on a specified group\n\tcase \"GIMMEINDEX\":\n\t\t// Asks for a list of posts in a specified group\n\t\t//\n\n\t// whatever else is lost\n\tdefault:\n\t\tbreak\n\n\t}\n\n}" ]
[ "0.7156787", "0.6577217", "0.64477545", "0.641192", "0.63666284", "0.626826", "0.6256493", "0.62502176", "0.6194835", "0.6175413", "0.6148562", "0.61108136", "0.61039346", "0.6088125", "0.60439765", "0.60274255", "0.6023933", "0.6007078", "0.6005092", "0.59684", "0.5964987", "0.59534013", "0.59521836", "0.5927745", "0.59199333", "0.5916734", "0.59151846", "0.5908927", "0.5904615", "0.58925956", "0.5882311", "0.58778423", "0.58463424", "0.58396214", "0.58340883", "0.5833281", "0.5832981", "0.5808847", "0.57886094", "0.5779866", "0.57731766", "0.57726955", "0.57718945", "0.5754373", "0.5748684", "0.5742634", "0.574169", "0.57286745", "0.57185954", "0.57085127", "0.5701395", "0.57011336", "0.5690231", "0.56855845", "0.56736267", "0.5666172", "0.5650119", "0.56471586", "0.56410074", "0.56341946", "0.56279314", "0.5623783", "0.562038", "0.5619151", "0.5612726", "0.5608251", "0.5605575", "0.56036156", "0.55928993", "0.55902594", "0.5589791", "0.5587827", "0.5579227", "0.5578904", "0.55718714", "0.55577934", "0.5553368", "0.5552868", "0.55458975", "0.55366975", "0.55337155", "0.55315554", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55306524", "0.55256516" ]
0.0
-1
start a thread that listens for RPCs from worker.go
func (m *Master) server() { rpc.Register(m) rpc.HandleHTTP() //l, e := net.Listen("tcp", ":1234") sockname := masterSock() os.Remove(sockname) l, e := net.Listen("unix", sockname) if e != nil { log.Fatal("listen error:", e) } go http.Serve(l, nil) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (wk *Worker) startRPCServer() {\n\t// TODO: implement me\n\t// Hint: Refer to how the driver's startRPCServer is implemented.\n\t// TODO TODO TODO\n\t//\n\n\t//\n\t// Once shutdown is closed, should the following statement be\n\t// called, meaning the worker RPC server is existing.\n\tserverless.Debug(\"Worker: %v RPC server exist\\n\", wk.address)\n}", "func listenRPC(app *core.App, config standaloneConfig) error {\n\t// Initialize the JSON RPC WebSocket server (but don't start it yet).\n\trpcAddr := fmt.Sprintf(\":%d\", config.RPCPort)\n\trpcHandler := &rpcHandler{\n\t\tapp: app,\n\t}\n\trpcServer, err := rpc.NewServer(rpcAddr, rpcHandler)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tgo func() {\n\t\t// Wait for the server to start listening and select an address.\n\t\tfor rpcServer.Addr() == nil {\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t\tlog.WithField(\"address\", rpcServer.Addr().String()).Info(\"started RPC server\")\n\t}()\n\treturn rpcServer.Listen()\n}", "func startServer(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", MyHandle.Host, MyHandle.Port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to startServer: %v\", err)\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\tapi.RegisterGoChatServer(grpcServer, &chatServer{})\n\n\terr = grpcServer.Serve(listener)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func (s *Server) RunRPC(ctx context.Context, wg *sync.WaitGroup) error {\n\twg.Add(1)\n\n\tl, err := net.Listen(\"tcp\", s.GRPCListen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrvr := grpc.NewServer()\n\tpb.RegisterRegistryServer(srvr, s)\n\n\t// Shutdown procedure.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tlog.Println(\"Shutting down gRPC listener\")\n\n\t\tsrvr.GracefulStop()\n\n\t\tif err := l.Close(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\twg.Done()\n\t}()\n\n\t// Background the listener.\n\tgo func() {\n\t\tlog.Printf(\"gRPC up: %s\\n\", s.GRPCListen)\n\t\tif err := srvr.Serve(l); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (r *runtime) startGRPCServer() {\n\tr.logger.Info(\"starting GRPC server\")\n\tr.grpcServer = newGRPCServer(r.config.BrokerBase.GRPC, linmetric.BrokerRegistry)\n\n\t// bind grpc handlers\n\tr.rpcHandler = &rpcHandler{\n\t\thandler: query.NewTaskHandler(\n\t\t\tr.config.Query,\n\t\t\tr.factory.taskServer,\n\t\t\tquery.NewIntermediateTaskProcessor(*r.node, r.config.Query.Timeout.Duration(),\n\t\t\t\tr.stateMgr, r.srv.taskManager, r.srv.transportManager),\n\t\t\tr.queryPool,\n\t\t),\n\t}\n\n\tprotoCommonV1.RegisterTaskServiceServer(r.grpcServer.GetServer(), r.rpcHandler.handler)\n\n\tgo serveGRPCFn(r.grpcServer)\n}", "func run() error {\n\tlistenOn := \"127.0.0.1:8080\"\n\tlistener, err := net.Listen(\"tcp\", listenOn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to listen on %s: %w\", listenOn, err)\n\t}\n\n\tserver := grpc.NewServer()\n\tuserv1.RegisterUserServiceServer(server, &userServiceServer{})\n\tlog.Println(\"Listening on\", listenOn)\n\n\tif err := server.Serve(listener); err != nil {\n\t\treturn fmt.Errorf(\"failed to serve gRPC server: %w\", err)\n\t}\n\n\treturn nil\n}", "func startServer(t testing.TB, h jsonrpc2.Handler) net.Listener {\n\tlistener, err := net.Listen(\"tcp\", bindAddr)\n\tif err != nil {\n\t\tt.Fatal(\"Listen:\", err)\n\t}\n\tgo func() {\n\t\tif err := serve(context.Background(), listener, h); err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tt.Fatal(\"jsonrpc2.Serve:\", err)\n\t\t}\n\t}()\n\treturn listener\n}", "func (t *gRPCTransport) start() {\n\t// start Communicate RPC\n\tif t.l() {\n\t\tt.logger.Info(\"starting gRPC server\")\n\t}\n\tgo func() {\n\t\terr := t.grpcServer.Serve(t.lis)\n\t\tif err != nil && t.l() {\n\t\t\tt.logger.Error(\"gRPC serve ended with error\", zap.Error(err))\n\t\t}\n\t}()\n\n\t// connect to peers' RaftProtocolServers\n\tdone := make(chan struct{})\n\tfor _, p := range t.peers {\n\t\tgo func(p *peer) {\n\t\t\tp.connectLoop()\n\t\t\tdone <- struct{}{}\n\t\t}(p)\n\t}\n\tfor range t.peers {\n\t\t<-done\n\t}\n\tfor _, p := range t.peers {\n\t\tgo p.loop()\n\t}\n\tif t.l() {\n\t\tt.logger.Info(\"connected to all peers\")\n\t}\n\n\t// start sendLoop\n\tgo t.sendLoop()\n}", "func (this *Engine) launchRpcServe() (done chan null.NullStruct) {\n\tvar (\n\t\tprotocolFactory thrift.TProtocolFactory\n\t\tserverTransport thrift.TServerTransport\n\t\ttransportFactory thrift.TTransportFactory\n\t\terr error\n\t\tserverNetwork string\n\t)\n\n\tswitch config.Engine.Rpc.Protocol {\n\tcase \"binary\":\n\t\tprotocolFactory = thrift.NewTBinaryProtocolFactoryDefault()\n\n\tcase \"json\":\n\t\tprotocolFactory = thrift.NewTJSONProtocolFactory()\n\n\tcase \"simplejson\":\n\t\tprotocolFactory = thrift.NewTSimpleJSONProtocolFactory()\n\n\tcase \"compact\":\n\t\tprotocolFactory = thrift.NewTCompactProtocolFactory()\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown protocol: %s\", config.Engine.Rpc.Protocol))\n\t}\n\n\t// client-side Thrift protocol/transport stack must match\n\t// the server-side, otherwise you are very likely to get in trouble\n\tswitch {\n\tcase config.Engine.Rpc.Framed:\n\t\t// each payload is sent over the wire with a frame header containing its size\n\t\ttransportFactory = thrift.NewTFramedTransportFactory(transportFactory)\n\n\tdefault:\n\t\t// there is no BufferedTransport in Java: only FramedTransport\n\t\ttransportFactory = thrift.NewTBufferedTransportFactory(\n\t\t\tconfig.Engine.Rpc.BufferSize)\n\t}\n\n\tswitch {\n\tcase strings.Contains(config.Engine.Rpc.ListenAddr, \"/\"):\n\t\tserverNetwork = \"unix\"\n\t\tif config.Engine.Rpc.SessionTimeout > 0 {\n\t\t\tserverTransport, err = NewTUnixSocketTimeout(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr, config.Engine.Rpc.SessionTimeout)\n\t\t} else {\n\t\t\tserverTransport, err = NewTUnixSocket(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr)\n\t\t}\n\n\tdefault:\n\t\tserverNetwork = \"tcp\"\n\t\tif config.Engine.Rpc.SessionTimeout > 0 {\n\t\t\tserverTransport, err = thrift.NewTServerSocketTimeout(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr, config.Engine.Rpc.SessionTimeout)\n\t\t} else {\n\t\t\tserverTransport, err = thrift.NewTServerSocket(\n\t\t\t\tconfig.Engine.Rpc.ListenAddr)\n\t\t}\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// dial zk before startup servants\n\t// because proxy servant is dependent upon zk\n\tif config.Engine.EtcdSelfAddr != \"\" {\n\t\tif err := etclib.Dial(config.Engine.EtcdServers); err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tlog.Debug(\"etcd connected: %+v\", config.Engine.EtcdServers)\n\t\t}\n\t}\n\n\t// when config loaded, create the servants\n\tthis.svt = servant.NewFunServantWrapper(config.Engine.Servants)\n\tthis.rpcProcessor = rpc.NewFunServantProcessor(this.svt)\n\tthis.svt.Start()\n\n\tthis.rpcServer = NewTFunServer(this,\n\t\tconfig.Engine.Rpc.PreforkMode,\n\t\tthis.rpcProcessor,\n\t\tserverTransport, transportFactory, protocolFactory)\n\tlog.Info(\"RPC server ready at %s:%s\", serverNetwork, config.Engine.Rpc.ListenAddr)\n\n\tthis.launchDashboard()\n\n\tdone = make(chan null.NullStruct)\n\tgo func() {\n\t\tif err = this.rpcServer.Serve(); err != nil {\n\t\t\tlog.Error(\"RPC server: %+v\", err)\n\t\t}\n\n\t\tdone <- null.Null\n\t}()\n\n\treturn done\n}", "func (twrkr *twerk) startWorker() {\n\n\tgo func() {\n\t\ttwrkr.waitOnWorld()\n\t\ttwrkr.liveWorkersNum.Incr()\n\t\tdefer func() {\n\t\t\ttwrkr.waitOnWorld()\n\t\t\ttwrkr.liveWorkersNum.Decr()\n\t\t}()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase job, _ := <-twrkr.jobListener:\n\t\t\t\ttwrkr.waitOnWorld()\n\t\t\t\ttwrkr.currentlyWorkingNum.Incr()\n\t\t\t\treturnValues := twrkr.callable.CallFunction(job.arguments)\n\t\t\t\tif len(returnValues) > 0 {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tjob.returnTo <- returnValues\n\t\t\t\t\t\tclose(job.returnTo)\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\ttwrkr.waitOnWorld()\n\t\t\t\ttwrkr.currentlyWorkingNum.Decr()\n\t\t\tcase <-twrkr.broadcastDie:\n\t\t\t\t// somebody requested that we die\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n}", "func (g *GRPC) Run() error {\n\tvar err error\n\tg.listener, err = net.Listen(connProtocol, fmt.Sprintf(\":%s\", g.port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo g.serve()\n\treturn nil\n}", "func (f *framework) startHTTP() {\n\tf.log.Printf(\"serving grpc on %s\\n\", f.ln.Addr())\n\terr := f.task.CreateServer().Serve(f.ln)\n\tselect {\n\tcase <-f.httpStop:\n\t\tf.log.Printf(\"grpc stops serving\")\n\tdefault:\n\t\tif err != nil {\n\t\t\tf.log.Fatalf(\"grpc.Serve returns error: %v\\n\", err)\n\t\t}\n\t}\n}", "func (w *worker) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tw.workerPool <- w.JobChannel\n\n\t\t\tjob := <-w.JobChannel\n\t\t\thandler, err := w.CommandHandler.GetHandler(job)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !job.IsValid() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err = handler.Handle(job); err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func init(){\n\tskeleton.RegisterChanRPC(reflect.TypeOf(&msg.Hello{}), handleHello)\n}", "func main() {\n\t\n\tlog.Println(\"start of twitter-streamer server -- twitter-streamer .....\")\n\n\tlistener, err := net.Listen(\"tcp\",\"localhost\"+port) // setup listener\n\tif err != nil {\n\t\tlog.Fatalf(\"Server, failed on listen: %v\",err)\n\t}\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterTweetServiceServer(grpcServer, new(server)) // register the service\n\n\tlog.Printf(\"server listening on port -> %s\\n\",port)\n\t\n\tif err := grpcServer.Serve(listener); err != nil { // listen serve client connections\n\t\tlog.Fatalf(\"Server, failed to server: %v\",err)\n\t}\n}", "func (r *RPCServer) Start() (err error) {\n\t// register the shared methods\n\trpc.Register(&shared.Handler{\n\t\tStore: r.store,\n\t})\n\n\tlog.Print(\"Starting RPC server on port: \", r.port)\n\tr.listener, err = net.Listen(\"tcp\", r.port)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trpc.Accept(r.listener)\n\n\treturn\n}", "func main() {\n\trequests = make(chan *Message, 50)\n\n\t//Initialize Server\n\tnotListening := make(chan bool)\n\t//log.Printf(\"STATUS: %v INBRANCH: %v FCOUNT: %v\", ThisNode.SN, (*ThisNode.inBranch).Weight, ThisNode.findCount)\n\tgo func(nl chan bool) {\n\t\tdefer func() {\n\t\t\tnl <- true\n\t\t}()\n\t\tl, err := net.Listen(\"tcp\", PORT)\n\t\tfmt.Println(\"Listening\")\n\t\tLogger.Println(\"Listening\")\n\t\tif err != nil {\n\t\t\tLogger.Fatal(err)\n\t\t}\n\n\t\tfor {\n\t\t\tconn, err := l.Accept()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\t// Handle the connection in a new goroutine.\n\t\t\tgo serveConn(conn, requests)\n\t\t}\n\t}(notListening)\n\n\t//Process incomming messages\n\tgo processMessage(requests)\n\n\tif wakeup {\n\t\ttime.Sleep(time.Second * 11)\n\t\tThisNode.Wakeup()\n\t}\n\n\t//Wait until listening routine sends signal\n\t<-notListening\n}", "func setUpRPC(nodeRPC string) {\n\trpcServ := new(Service)\n\trpc.Register(rpcServ)\n\trpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\tif err != nil {\n\t\tlog.Fatal(\"listen error:\", err)\n\t}\n\tl, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tfor i := 0; i >= 0; i++ {\n\t\tconn, _ := l.AcceptTCP()\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t\tgo rpc.ServeConn(conn)\n\t\tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tdefer conn.Close()\n\t}\n\tl.Close()\n\n\t// rpcServ := new(FTService)\n\t// rpc.Register(rpcServ)\n\t// rpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\t// if err != nil {\n\t// \tlog.Fatal(\"listen error:\", err)\n\t// }\n\t// l, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\t// if e != nil {\n\t// \tlog.Fatal(\"listen error:\", e)\n\t// }\n\t// for i := 0; i >= 0; i++ {\n\t// \tconn, _ := l.AcceptTCP()\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t// \trpc.ServeConn(conn)\n\t// \tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \t//defer conn.Close()\n\t// }\n\t// l.Close()\n\n}", "func (w *Worker) Listen() (err error) {\n\tif w.WorkerID == \"\" || w.RequestID == \"\" {\n\t\treturn errors.Errorf(\"workerID and requestID required\")\n\t}\n\tstream, err := w.eventStream()\n\tif err == nil {\n\t\tif err = stream.Start(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer stream.Stop()\n\t\tstream.Send(&rpc.StreamingMessage{\n\t\t\tContent: &rpc.StreamingMessage_StartStream{\n\t\t\t\tStartStream: &rpc.StartStream{\n\t\t\t\t\tWorkerId: w.WorkerID,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tch := w.getChannel(stream)\n\t\tmsg, ok := stream.Recv()\n\t\tfor ok {\n\t\t\tswitch msgT := msg.Content.(type) {\n\t\t\tcase *rpc.StreamingMessage_StartStream:\n\t\t\t\tch.StartStream(msg.RequestId, msgT.StartStream)\n\t\t\tcase *rpc.StreamingMessage_WorkerInitRequest:\n\t\t\t\tch.InitRequest(msg.RequestId, msgT.WorkerInitRequest)\n\t\t\tcase *rpc.StreamingMessage_WorkerHeartbeat:\n\t\t\t\tch.Heartbeat(msg.RequestId, msgT.WorkerHeartbeat)\n\t\t\tcase *rpc.StreamingMessage_WorkerTerminate:\n\t\t\t\tch.Terminate(msg.RequestId, msgT.WorkerTerminate)\n\t\t\tcase *rpc.StreamingMessage_WorkerStatusRequest:\n\t\t\t\tch.StatusRequest(msg.RequestId, msgT.WorkerStatusRequest)\n\t\t\tcase *rpc.StreamingMessage_FileChangeEventRequest:\n\t\t\t\tch.FileChangeEventRequest(msg.RequestId, msgT.FileChangeEventRequest)\n\t\t\tcase *rpc.StreamingMessage_FunctionLoadRequest:\n\t\t\t\tch.FunctionLoadRequest(msg.RequestId, msgT.FunctionLoadRequest)\n\t\t\tcase *rpc.StreamingMessage_InvocationRequest:\n\t\t\t\tch.InvocationRequest(msg.RequestId, msgT.InvocationRequest)\n\t\t\tcase *rpc.StreamingMessage_InvocationCancel:\n\t\t\t\tch.InvocationCancel(msg.RequestId, msgT.InvocationCancel)\n\t\t\tcase *rpc.StreamingMessage_FunctionEnvironmentReloadRequest:\n\t\t\t\tch.FunctionEnvironmentReloadRequest(msg.RequestId, msgT.FunctionEnvironmentReloadRequest)\n\t\t\t}\n\t\t\tmsg, ok = stream.Recv()\n\t\t}\n\t}\n\treturn\n}", "func (w *Worker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t// Add ourselves into the worker queue.\n\t\t\tw.WorkerQueue <- w.Work\n\n\t\t\tselect {\n\t\t\tcase work := <-w.Work:\n\t\t\t\t// Receive a work request.\n\t\t\t\tvar ris Response\n\t\t\t\tris.RequestId = work.RequestId\n\t\t\t\tris.Result, ris.Correct, ris.NSV = generateTrainset(work.TsToAnalyze, w.TsData, w.Output)\n\t\t\t\twork.Response <- ris\n\t\t\tcase <-w.QuitChan:\n\t\t\t\t// We have been asked to stop.\n\t\t\t\tlog.Printf(\"worker%d stopping\\n\", w.ID)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func Run(ctx context.Context, port string) struct{} {\n\n\t//The server to get up\n\tli, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Server stopped: %v\", err)\n\t}\n\n\t//Passing the server to grpc\n\ts := &Server{}\n\tgrpcServer := grpc.NewServer()\n\tsubscribe.RegisterSubscribeServiceServer(grpcServer, s)\n\tgrpcServer.Serve(li)\n\n\tfmt.Printf(\"Server up on port: %v\\n\", err)\n\treturn <-ctx.Done()\n}", "func (gw *GrpcWrapper) Start() error {\n\tif gw.ln != nil {\n\t\treturn nil\n\t}\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", gw.port))\n\tif err != nil {\n\t\tgw.logger.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"port\": gw.port,\n\t\t}).Error(\"net.Listen() error\")\n\t\treturn err\n\t}\n\tgw.ln = ln\n\n\tgw.logger.WithFields(log.Fields{\"port\": gw.port}).Info(\"TCP net listener initialized\")\n\n\tserver := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))\n\tfor _, handlerFunc := range gw.handlerFuncs {\n\t\thandlerFunc(server)\n\t}\n\tgw.server = server\n\tgw.grpcAwaiter = make(chan error)\n\n\tgo func() {\n\t\tgw.logger.Infof(\"Serving gRPC on :%d\", gw.port)\n\t\terr := gw.server.Serve(ln)\n\t\tgw.grpcAwaiter <- err\n\t\tif err != nil {\n\t\t\tgw.logger.WithFields(log.Fields{\"error\": err.Error()}).Error(\"gRPC serve() error\")\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (w *worker) start() {\n\tatomic.StoreInt32(&w.running, 1)\n\tw.startCh <- struct{}{}\n}", "func worker() {\n\tworker, err := zmq4.NewSocket(zmq4.DEALER)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"inproc://backend\")\n\n\tfor {\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tid, content := pop(msg)\n\n\t\treplies := rand.Intn(5)\n\t\tfor reply := 0; reply < replies; reply++ {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(1000)+1) * time.Millisecond)\n\t\t\tworker.SendMessage(id, content)\n\t\t}\n\t}\n}", "func workerTask() {\n\tworker, err := zmq4.NewSocket(zmq4.REQ)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"ipc://backend.ipc\")\n\tworker.SendMessage(WorkerReady)\n\n\tfor {\n\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tmsg[len(msg)-1] = \"OK\"\n\t\tworker.SendMessage(msg)\n\t}\n\n}", "func (s *serv) Start() {\n\ts.running = true\n\n\tsem := make(chan byte)\n\n\tgo func() {\n\t\t// Start listening\n\t\ts.listen()\n\t\tsem <- 0\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tp := <-s.pks\n\t\t\t// Dispatch work\n\t\t\tswitch p.(type) {\n\t\t\tcase *network.MessagePacket:\n\t\t\t\t_ = p.(*network.MessagePacket)\n\t\t\tcase *network.ConnectionPacket:\n\t\t\t\t_ = p.(*network.ConnectionPacket)\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n\n\t<-sem\n}", "func main() {\n\tgob.Register(&net.TCPAddr{})\n\n\tknownFiles = make(map[string][]string)\n\trand.Seed(time.Now().UnixNano())\n\n\targs := os.Args[1:]\n\tserverIP := args[0]\n\tServerInterface := new(MyServer)\n\tserverRPC := rpc.NewServer()\n\tregisterServer(serverRPC, ServerInterface)\n\tl, e := net.Listen(\"tcp\", serverIP)\n\tif e != nil {\n\t\tlog.Fatal(\"server error:\", e)\n\t\treturn\n\t}\n\n\tfor {\n\t\tconn, _ := l.Accept()\n\t\tgo serverRPC.ServeConn(conn)\n\t}\n}", "func startupServer(t *testing.T) (lightning *glightning.Lightning, requestQ, replyQ chan []byte) {\n\ttmpfile, err := ioutil.TempFile(\"\", \"rpc.socket\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tos.Remove(tmpfile.Name())\n\n\trequestQueue := make(chan []byte)\n\treplyQueue := make(chan []byte)\n\tok := make(chan bool)\n\n\tgo func(socket string, t *testing.T, requestQueue, replyQueue chan []byte, ok chan bool) {\n\t\tln, err := net.Listen(\"unix\", socket)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfor {\n\t\t\tok <- true\n\t\t\tinconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tgo listen(inconn, requestQueue, t)\n\t\t\tgo writer(inconn, replyQueue, t)\n\t\t}\n\t}(tmpfile.Name(), t, requestQueue, replyQueue, ok)\n\n\t// block until the socket is listening\n\t<-ok\n\n\tlightning = glightning.NewLightning()\n\tlightning.StartUp(\"\", tmpfile.Name())\n\treturn lightning, requestQueue, replyQueue\n}", "func (s *Server) serve(lis net.Listener) {\n\ts.wg.Add(1)\n\tgo func() {\n\t\tlog.Infof(\"Listening on %s\", lis.Addr())\n\t\terr := s.httpServer.Serve(lis)\n\t\tlog.Tracef(\"Finished serving RPC: %v\", err)\n\t\ts.wg.Done()\n\t}()\n}", "func main() {\n\t// create a listener on TCP port 7777\n\tlis, err := net.Listen(\"tcp\", \":7777\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\t// create a server instance\n\ts := api.Server{}\n\n\t// create the TLS creds\n\tcreds, err := credentials.NewServerTLSFromFile(\"cert/server.crt\", \"cert/server.key\")\n\tif err != nil {\n\t\tlog.Fatalf(\"could not load TLS keys: %s\", err)\n\t}\n\n\t// add credentials to the gRPC options\n\topts := []grpc.ServerOption{grpc.Creds(creds)}\n\n\t// create a gRPC server object\n\tgrpcServer := grpc.NewServer(opts...)\n\n\t// attach the Ping service to the server\n\tapi.RegisterPingServer(grpcServer, &s)\n\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", \":9091\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tdao := database.CreateDAO(database.CreateConn())\n\tsvc := service.CreateService(dao)\n\n\tgrpcServer := grpc.NewServer()\n\n\t// attach the Ping service to the server\n\tpb.RegisterDBServer(grpcServer, &svc)\n\t// start the server\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %s\", err)\n\t}\n}", "func LaunchRpcServer() {\n\t// Setup replica server\n\taddy, err := net.ResolveTCPAddr(\"tcp\", \"0.0.0.0:\"+strconv.Itoa(config.Replication.Rpc_server_port_num))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Set listener\n\tinbound, err := net.ListenTCP(\"tcp\", addy)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Launch\n\tlog.Println(\"RPC Server Listening to... http://0.0.0.0:\" + strconv.Itoa(config.Replication.Rpc_server_port_num))\n\tlistener := new(Listener)\n\trpc.Register(listener)\n\trpc.Accept(inbound)\n\n}", "func (m *Manager) Start(srv *server.TCP) {\n\tm.serverMutex.Lock()\n\tdefer m.serverMutex.Unlock()\n\n\tm.server = srv\n\n\tm.messageWorkerPool.Start()\n\tm.messageRequestWorkerPool.Start()\n}", "func StartServer(servers []string, me int) *KVPaxos {\n // this call is all that's needed to persuade\n // Go's RPC library to marshall/unmarshall\n // struct Op.\n gob.Register(Op{})\n\n kv := new(KVPaxos)\n kv.me = me\n\n // Your initialization code here.\n kv.data = make(map[string]string)\n kv.pendingRead = make(map[int64]*PendingRead)\n kv.applied = -1\n\n rpcs := rpc.NewServer()\n rpcs.Register(kv)\n\n kv.px = paxos.Make(servers, me, rpcs)\n\n // start worker\n kv.StartBackgroundWorker()\n\n os.Remove(servers[me])\n l, e := net.Listen(\"unix\", servers[me]);\n if e != nil {\n log.Fatal(\"listen error: \", e);\n }\n kv.l = l\n\n // please do not change any of the following code,\n // or do anything to subvert it.\n\n go func() {\n for kv.dead == false {\n conn, err := kv.l.Accept()\n if err == nil && kv.dead == false {\n if kv.unreliable && (rand.Int63() % 1000) < 100 {\n // discard the request.\n conn.Close()\n } else if kv.unreliable && (rand.Int63() % 1000) < 200 {\n // process the request but force discard of reply.\n c1 := conn.(*net.UnixConn)\n f, _ := c1.File()\n err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)\n if err != nil {\n fmt.Printf(\"shutdown: %v\\n\", err)\n }\n go rpcs.ServeConn(conn)\n } else {\n go rpcs.ServeConn(conn)\n }\n } else if err == nil {\n conn.Close()\n }\n if err != nil && kv.dead == false {\n fmt.Printf(\"KVPaxos(%v) accept: %v\\n\", me, err.Error())\n kv.kill()\n }\n }\n }()\n\n return kv\n}", "func (s *server) Start() {\n\t// A duplicator for notifications intended for all clients runs\n\t// in another goroutines. Any such notifications are sent to\n\t// the allClients channel and then sent to each connected client.\n\t//\n\t// Use a sync.Once to insure no extra duplicators run.\n\tgo duplicateOnce.Do(clientResponseDuplicator)\n\n\tlog.Trace(\"Starting RPC server\")\n\n\tserveMux := http.NewServeMux()\n\tconst rpcAuthTimeoutSeconds = 10\n\thttpServer := &http.Server{\n\t\tHandler: serveMux,\n\n\t\t// Timeout connections which don't complete the initial\n\t\t// handshake within the allowed timeframe.\n\t\tReadTimeout: time.Second * rpcAuthTimeoutSeconds,\n\t}\n\tserveMux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif err := s.checkAuth(r); err != nil {\n\t\t\tlog.Warnf(\"Unauthorized client connection attempt\")\n\t\t\thttp.Error(w, \"401 Unauthorized.\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\ts.ServeRPCRequest(w, r)\n\t})\n\tserveMux.HandleFunc(\"/frontend\", func(w http.ResponseWriter, r *http.Request) {\n\t\tauthenticated := false\n\t\tif err := s.checkAuth(r); err != nil {\n\t\t\t// If auth was supplied but incorrect, rather than simply being\n\t\t\t// missing, immediately terminate the connection.\n\t\t\tif err != ErrNoAuth {\n\t\t\t\tlog.Warnf(\"Disconnecting improperly authorized websocket client\")\n\t\t\t\thttp.Error(w, \"401 Unauthorized.\", http.StatusUnauthorized)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tauthenticated = true\n\t\t}\n\n\t\t// A new Server instance is created rather than just creating the\n\t\t// handler closure since the default server will disconnect the\n\t\t// client if the origin is unset.\n\t\twsServer := websocket.Server{\n\t\t\tHandler: websocket.Handler(func(ws *websocket.Conn) {\n\t\t\t\ts.WSSendRecv(ws, r.RemoteAddr, authenticated)\n\t\t\t}),\n\t\t}\n\t\twsServer.ServeHTTP(w, r)\n\t})\n\tfor _, listener := range s.listeners {\n\t\ts.wg.Add(1)\n\t\tgo func(listener net.Listener) {\n\t\t\tlog.Infof(\"RPCS: RPC server listening on %s\", listener.Addr())\n\t\t\thttpServer.Serve(listener)\n\t\t\tlog.Tracef(\"RPCS: RPC listener done for %s\", listener.Addr())\n\t\t\ts.wg.Done()\n\t\t}(listener)\n\t}\n}", "func main() {\n\n\tlis ,err := net.Listen(\"tcp\",fmt.Sprintf(\":%d\", 1368))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tserver := grpc.NewServer()\n\trpc.RegisterUserServiceServer(server, &service.UserService{})\n\n\terr = server.Serve(lis)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (a *agent) listen(wg *sync.WaitGroup) {\n\tLog().Debugf(\"Starting EventLoop on %d-%s\", a.ID, a.Label)\n\tfor e := range a.packetChan {\n\t\t// Receive a work request.\n\t\tmetrics.set(METRIC_CONNECTION_TRANSIT, a.conf.PipelineName, a.Label, len(a.packetChan))\n\t\tif err := a.processor.Receive(e); err != nil {\n\t\t\tLog().Errorf(\"agent %s: %s\", a.conf.Type, err.Error())\n\t\t}\n\t\tmetrics.increment(METRIC_PROC_IN, a.conf.PipelineName, a.Label)\n\t}\n\twg.Done()\n}", "func (w *worker) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tw.WorkerQueue <- w.Job\n\n\t\t\tselect {\n\t\t\tcase job := <-w.Job:\n\t\t\t\tlog.Printf(\"worker %d: %s\", w.ID, job.User.Login)\n\t\t\t\tjob.User.run()\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (h *Hub) Serve() error {\n\th.startTime = time.Now()\n\n\tip, err := util.GetPublicIP()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkersPort, err := util.ParseEndpointPort(h.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientPort, err := util.ParseEndpointPort(h.grpcEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkersEndpt := ip.String() + \":\" + workersPort\n\tclientEndpt := ip.String() + \":\" + clientPort\n\n\tsrv, err := frd.NewServer(h.ethKey, workersEndpt, clientEndpt)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = srv.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv.Serve()\n\n\tlistener, err := net.Listen(\"tcp\", h.endpoint)\n\n\tif err != nil {\n\t\tlog.G(h.ctx).Error(\"failed to listen\", zap.String(\"address\", h.endpoint), zap.Error(err))\n\t\treturn err\n\t}\n\tlog.G(h.ctx).Info(\"listening for connections from Miners\", zap.Stringer(\"address\", listener.Addr()))\n\n\tgrpcL, err := net.Listen(\"tcp\", h.grpcEndpoint)\n\tif err != nil {\n\t\tlog.G(h.ctx).Error(\"failed to listen\",\n\t\t\tzap.String(\"address\", h.grpcEndpoint), zap.Error(err))\n\t\tlistener.Close()\n\t\treturn err\n\t}\n\tlog.G(h.ctx).Info(\"listening for gRPC API connections\", zap.Stringer(\"address\", grpcL.Addr()))\n\t// TODO: fix this possible race: Close before Serve\n\th.minerListener = listener\n\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\th.externalGrpc.Serve(grpcL)\n\t}()\n\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\tfor {\n\t\t\tconn, err := h.minerListener.Accept()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo h.handleInterconnect(h.ctx, conn)\n\t\t}\n\t}()\n\th.wg.Wait()\n\n\treturn nil\n}", "func (s *Server) Run() <-chan error {\n\tvar chErr chan error\n\tlog.Infoln(fmt.Sprintf(\"gRPC server has started at port %d\", s.port))\n\tgo func() {\n\t\tif err := s.server.Serve(s.listener); err != nil {\n\t\t\tchErr <- err\n\t\t}\n\t}()\n\treturn chErr\n}", "func (w Worker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t// register the current worker into the worker queue.\n\t\t\tw.WorkerPool <- w.JobChannel\n\n\t\t\tselect {\n\t\t\tcase job := <-w.JobChannel:\n\n\t\t\t\t// we have received a work request.\n\t\t\t\tlog.Println(job.payload.HealthCheck())\n\n\t\t\tcase <-w.QuitChan:\n\t\t\t\t// we have received a signal to stop\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (w *worker) startWorker() {\n\tzap.L().Info(\"Starting InfluxDBworker\")\n\tfor {\n\t\tselect {\n\t\tcase event := <-w.events:\n\t\t\tw.processEvent(event)\n\t\tcase <-w.stop:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (g GrpcServer) Start() {\n\tgo func() {\n\t\tg.errCh <- g.server.Serve(g.listener)\n\t}()\n}", "func (tc *textileClient) start(ctx context.Context, cfg config.Config) error {\n\ttc.cfg = cfg\n\tauth := common.Credentials{}\n\tvar opts []grpc.DialOption\n\n\topts = append(opts, grpc.WithInsecure())\n\topts = append(opts, grpc.WithPerRPCCredentials(auth))\n\n\tvar threads *threadsClient.Client\n\tvar buckets *bucketsClient.Client\n\tvar netc *nc.Client\n\n\t// by default it goes to local threads now\n\thost := \"127.0.0.1:3006\"\n\n\tlog.Debug(\"Creating buckets client in \" + host)\n\tif b, err := bucketsClient.NewClient(host, opts...); err != nil {\n\t\tcmd.Fatal(err)\n\t} else {\n\t\tbuckets = b\n\t}\n\n\tlog.Debug(\"Creating threads client in \" + host)\n\tif t, err := threadsClient.NewClient(host, opts...); err != nil {\n\t\tcmd.Fatal(err)\n\t} else {\n\t\tthreads = t\n\t}\n\n\tif n, err := nc.NewClient(host, opts...); err != nil {\n\t\tcmd.Fatal(err)\n\t} else {\n\t\tnetc = n\n\t}\n\n\ttc.bucketsClient = buckets\n\ttc.threads = threads\n\ttc.netc = netc\n\n\ttc.isRunning = true\n\n\t// Attempt to connect to the Hub\n\t_, err := tc.getHubCtx(ctx)\n\tif err != nil {\n\t\tlog.Error(\"Could not connect to Textile Hub. Starting in offline mode.\", err)\n\t} else {\n\t\ttc.isConnectedToHub = true\n\t}\n\n\ttc.Ready <- true\n\treturn nil\n}", "func run(c context.Context, getCommands CommandFactory, daemonServices []DaemonService, sessionServices []trafficmgr.SessionService) error {\n\tcfg, err := client.LoadConfig(c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load config: %w\", err)\n\t}\n\tc = client.WithConfig(c, cfg)\n\tc = dgroup.WithGoroutineName(c, \"/\"+ProcessName)\n\tc, err = logging.InitContext(c, ProcessName, logging.RotateDaily, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Listen on domain unix domain socket or windows named pipe. The listener must be opened\n\t// before other tasks because the CLI client will only wait for a short period of time for\n\t// the socket/pipe to appear before it gives up.\n\tgrpcListener, err := client.ListenSocket(c, ProcessName, client.ConnectorSocketName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = client.RemoveSocket(grpcListener)\n\t}()\n\tdlog.Debug(c, \"Listener opened\")\n\n\tdlog.Info(c, \"---\")\n\tdlog.Infof(c, \"Telepresence %s %s starting...\", titleName, client.DisplayVersion())\n\tdlog.Infof(c, \"PID is %d\", os.Getpid())\n\tdlog.Info(c, \"\")\n\n\t// Don't bother calling 'conn.Close()', it should remain open until we shut down, and just\n\t// prefer to let the OS close it when we exit.\n\n\tsr := scout.NewReporter(c, \"connector\")\n\tcliio := &broadcastqueue.BroadcastQueue{}\n\n\ts := &service{\n\t\tscout: sr,\n\t\tconnectRequest: make(chan *rpc.ConnectRequest),\n\t\tconnectResponse: make(chan *rpc.ConnectInfo),\n\t\tmanagerProxy: trafficmgr.NewManagerProxy(),\n\t\tloginExecutor: auth.NewStandardLoginExecutor(cliio, sr),\n\t\tuserNotifications: func(ctx context.Context) <-chan string { return cliio.Subscribe(ctx) },\n\t\ttimedLogLevel: log.NewTimedLevel(cfg.LogLevels.UserDaemon.String(), log.SetLevel),\n\t\tgetCommands: getCommands,\n\t}\n\tif err := logging.LoadTimedLevelFromCache(c, s.timedLogLevel, s.procName); err != nil {\n\t\treturn err\n\t}\n\n\tg := dgroup.NewGroup(c, dgroup.GroupConfig{\n\t\tSoftShutdownTimeout: 2 * time.Second,\n\t\tEnableSignalHandling: true,\n\t\tShutdownOnNonError: true,\n\t})\n\n\tquitOnce := sync.Once{}\n\ts.quit = func() {\n\t\tquitOnce.Do(func() {\n\t\t\tg.Go(\"quit\", func(_ context.Context) error {\n\t\t\t\tcliio.Close()\n\t\t\t\treturn nil\n\t\t\t})\n\t\t})\n\t}\n\n\tg.Go(\"server-grpc\", func(c context.Context) (err error) {\n\t\topts := []grpc.ServerOption{}\n\t\tcfg := client.GetConfig(c)\n\t\tif !cfg.Grpc.MaxReceiveSize.IsZero() {\n\t\t\tif mz, ok := cfg.Grpc.MaxReceiveSize.AsInt64(); ok {\n\t\t\t\topts = append(opts, grpc.MaxRecvMsgSize(int(mz)))\n\t\t\t}\n\t\t}\n\t\ts.svc = grpc.NewServer(opts...)\n\t\trpc.RegisterConnectorServer(s.svc, s)\n\t\tmanager.RegisterManagerServer(s.svc, s.managerProxy)\n\t\tfor _, ds := range daemonServices {\n\t\t\tdlog.Infof(c, \"Starting additional daemon service %s\", ds.Name())\n\t\t\tif err := ds.Start(c, sr, s.svc, s.withSession); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tsc := &dhttp.ServerConfig{Handler: s.svc}\n\t\tdlog.Info(c, \"gRPC server started\")\n\t\tif err = sc.Serve(c, grpcListener); err != nil && c.Err() != nil {\n\t\t\terr = nil // Normal shutdown\n\t\t}\n\t\tif err != nil {\n\t\t\tdlog.Errorf(c, \"gRPC server ended with: %v\", err)\n\t\t} else {\n\t\t\tdlog.Debug(c, \"gRPC server ended\")\n\t\t}\n\t\treturn err\n\t})\n\n\tg.Go(\"config-reload\", s.configReload)\n\tg.Go(\"session\", func(c context.Context) error {\n\t\treturn s.manageSessions(c, sessionServices)\n\t})\n\n\t// background-systema runs a localhost HTTP server for handling callbacks from the\n\t// Ambassador Cloud login flow.\n\tg.Go(\"background-systema\", s.loginExecutor.Worker)\n\n\t// background-metriton is the goroutine that handles all telemetry reports, so that calls to\n\t// metriton don't block the functional goroutines.\n\tg.Go(\"background-metriton\", s.scout.Run)\n\n\terr = g.Wait()\n\tif err != nil {\n\t\tdlog.Error(c, err)\n\t}\n\treturn err\n}", "func (s *Service) run() {\n\n\t// Create a communicator for sending and receiving packets.\n\tcommunicator := comm.NewCommunicator(s.config.PollInterval, s.config.Port)\n\tdefer communicator.Stop()\n\n\t// Create a ticker for sending pings.\n\tpingTicker := time.NewTicker(s.config.PingInterval)\n\tdefer pingTicker.Stop()\n\n\t// Create a ticker for timeout checks.\n\tpeerTicker := time.NewTicker(s.config.PeerTimeout)\n\tdefer peerTicker.Stop()\n\n\t// Create the packet that will be sent to all peers.\n\tpkt := &comm.Packet{\n\t\tID: s.config.ID,\n\t\tUserData: s.config.UserData,\n\t}\n\n\t// Continue processing events until explicitly stopped.\n\tfor {\n\t\tselect {\n\t\tcase p := <-communicator.PacketChan:\n\t\t\ts.processPacket(p)\n\t\tcase <-pingTicker.C:\n\t\t\tcommunicator.Send(pkt)\n\t\tcase <-peerTicker.C:\n\t\t\ts.processPeers()\n\t\tcase <-s.stopChan:\n\t\t\treturn\n\t\t}\n\t}\n}", "func Run() {\n\tgo listen()\n}", "func (s *JRPCServer) Start() {\n\thttpCall := s.httpSrv.On(s.endpointURL)\n\thttpCall.Forever()\n\thttpCall.handlerFunc = func(w http.ResponseWriter, req *http.Request) error {\n\t\t// ctx := context.Background()\n\t\ts.guard.Lock()\n\t\tdefer s.guard.Unlock()\n\t\tjReq := btcjson.Request{}\n\t\tbuf, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to decode jRPC request: %v\", err)\n\t\t}\n\t\terr = req.Body.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\t\tmustUnmarshal(buf, &jReq)\n\t\tcall, err := s.findCall(jReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// put unmarshalled JRPC request into a context\n\t\tctx := context.WithValue(req.Context(), jRPCRequestKey, jReq)\n\t\treturn call.execute(w, req.WithContext(ctx))\n\t}\n\ts.httpSrv.Start()\n}", "func (s *GrpcServer) startGrpcService() {\n\t// Start listening for requests\n\treflection.Register(s.server)\n\tlogrus.Infof(\"%s gRPC Server ready on %s\", s.name, s.Address())\n\twaitForServer := make(chan bool)\n\ts.goServe(waitForServer)\n\t<-waitForServer\n\ts.running = true\n}", "func main() {\n\tflag.Parse()\n\tfmt.Println(\"start the program\")\n\t// fmt.Println(*serverAddr)\n\n\tfor {\n\t\t// start the app\n\t\twaitc := make(chan struct{}) // a wait lock\n\n\t\t// start the server thread\n\t\tgo func() {\n\t\t\tfmt.Println(\"start the server\")\n\t\t\tserver.InitFileServer()\n\t\t\tdefer close(waitc)\n\t\t}()\n\n\t\t// start the client thread\n\t\t// go func() {\n\t\t// \tfor {\n\t\t// \t\tmsg := <-msgc // a message to send\n\t\t// \t\tclient.InitChatClient(*myTitle, serverAddr)\n\n\t\t// \t\terr := client.Chat(msg)\n\t\t// \t\tif err != nil {\n\t\t// \t\t\t// restart the client\n\t\t// \t\t\tfmt.Printf(\"send Err: %v\", err)\n\t\t// \t\t}\n\t\t// \t}\n\t\t// }()\n\n\t\t// start the input thread\n\t\t// go input()\n\n\t\t<-waitc\n\t\t// finished in this round restart the app\n\t\tfmt.Println(\"restart the app\")\n\t}\n}", "func (w *Worker) Start() {\n\tw.commandsPipe = NewCommandPipe()\n\tw.responsesPipe = NewResponsePipe(w.maxResponsePipeBufferSize)\n\tvar err error\n\tw.cmd = exec.Command(w.commandName, w.args...)\n\tw.responsesPipe.Register(w.cmd)\n\tw.commandsPipe.Register(w.cmd)\n\n\tch := w.responsesPipe.Channel()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase data := <-ch:\n\t\t\t\tlog.Print(\"GOT FROM PIPE \", data)\n\t\t\t\tvar ans WorkerStatus\n\t\t\t\tvar err error\n\t\t\t\terr = json.Unmarshal([]byte(data), &ans)\n\t\t\t\tlog.Print(\"DECODED FROM PIPE: \", ans)\n\t\t\t\tif err != nil {\n\t\t\t\t\tans.TaskID = w.taskID\n\t\t\t\t\tans.worker = w\n\t\t\t\t\tans.Error = err.Error()\n\t\t\t\t\t// TODO\n\t\t\t\t\tlog.Print(\"ERROR: failed to parse worker response: \", err)\n\n\t\t\t\t} else {\n\t\t\t\t\tans.TaskID = w.taskID\n\t\t\t\t\tans.worker = w\n\t\t\t\t}\n\t\t\t\tw.lastEvent = ans\n\t\t\t\tw.workerEvent <- &ans\n\n\t\t\t}\n\t\t}\n\t}()\n\terr = w.cmd.Start()\n\tif err != nil {\n\t\tlog.Print(\"ERROR: \", err) // TODO\n\t}\n\tgo func() {\n\t\terr := w.cmd.Wait()\n\t\tif err != nil {\n\t\t\tswitch terr := err.(type) {\n\t\t\tcase *exec.ExitError:\n\t\t\t\tw.workerEvent <- &WorkerStatus{\n\t\t\t\t\tTaskID: w.taskID,\n\t\t\t\t\tworker: w,\n\t\t\t\t\tError: terr.Error(), // TODO\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tw.workerEvent <- &WorkerStatus{\n\t\t\t\t\tTaskID: w.taskID,\n\t\t\t\t\tworker: w,\n\t\t\t\t\tError: err.Error(),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n}", "func main() {\n\tvar addr string\n\tflag.StringVar(&addr, \"e\", \":4040\", \"service address endpoint\")\n\tflag.Parse()\n\n\t// create local addr for socket\n\tladdr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\t// announce service using ListenTCP\n\t// which a TCPListener.\n\tl, err := net.ListenTCP(\"tcp\", laddr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer l.Close()\n\tfmt.Println(\"listening at (tcp)\", laddr.String())\n\n\t// req/response loop\n\tfor {\n\t\t// use TCPListener to block and wait for TCP\n\t\t// connection request using AcceptTCP which creates a TCPConn\n\t\tconn, err := l.AcceptTCP()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"failed to accept conn:\", err)\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(\"connected to: \", conn.RemoteAddr())\n\n\t\tgo handleConnection(conn)\n\t}\n}", "func (w *rpcServer) Start() error {\n\treceiver, err := w.session.NewReceiver(\n\t\tamqp.LinkSourceAddress(queueAddress(w.queue)),\n\t\tamqp.LinkCredit(w.concurrency),\n\t\tamqp.LinkSourceDurability(amqp.DurabilityUnsettledState),\n\t\tamqp.LinkSourceExpiryPolicy(amqp.ExpiryNever),\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.stopping = false\n\tmessages := make(chan *amqp.Message)\n\n\tgo w.receiveMessages(receiver, messages)\n\tgo w.processIncomingMessage(messages)\n\n\treturn nil\n}", "func (e *Engine) syncRPC() {\n\t// TODO(jsing): Make this default to IPv6, if configured.\n\taddr := &net.TCPAddr{\n\t\tIP: e.config.Node.IPv4Addr,\n\t\tPort: e.config.SyncPort,\n\t}\n\tln, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Listen failed: %v\", err)\n\t}\n\n\tgo e.syncServer.serve(ln)\n\n\t<-e.shutdownRPC\n\tln.Close()\n\te.shutdownRPC <- true\n}", "func callWorker(worker, name string, args interface{}, reply interface{}) bool {\n\treturn call(worker, \"RPCWorker.\"+name, args, reply)\n}", "func startPollWorker(site *ElectionSite) *pollWorker {\n\n\tworker := &pollWorker{site: site,\n\t\tballot: nil,\n\t\tkillch: make(chan bool, 1), // make sure sender won't block\n\t\tlistench: make(chan *Ballot, 1)} // make sure sender won't block\n\n\tgo worker.listen()\n\n\treturn worker\n}", "func main() {\n\tvar (\n\t\trepository = storage.NewInMemory()\n\t\tportServer = service.NewPortServer(repository)\n\t)\n\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot start the server: %s\", err)\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\n\tproto.RegisterStorageServer(grpcServer, portServer)\n\n\tlog.Printf(\"starting GRPC server on %s\", listener.Addr().String())\n\tif err := grpcServer.Serve(listener); err != nil {\n\t\tlog.Fatalf(\"failed to start the server: %s\", err)\n\t}\n}", "func (s *Service) Run(setupBody ServiceSetupCallback) error {\n\tif !atomic.CompareAndSwapInt32(&s.running, 0, 1) {\n\t\treturn ErrAlreadyRunning\n\t}\n\tdefer func() {\n\t\tatomic.StoreInt32(&s.running, 0)\n\t}()\n\n\ts.l.Lock()\n\tif s.stopped {\n\t\ts.l.Unlock()\n\t\treturn io.EOF\n\t}\n\ts.l.Unlock()\n\n\tconn, err := net.Dial(\"tcp\", s.url.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tconn.(*net.TCPConn).SetNoDelay(true)\n\n\treq, _ := http.NewRequest(\"RPCCONNECT\", s.url.String(), nil)\n\treq.SetBasicAuth(s.user, s.pwd)\n\treq.Header.Set(\"User-Agent\", userAgent)\n\terr = req.Write(conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconnr := bufio.NewReader(conn)\n\trwc := &minirwc{Conn: conn, bufreader: connr}\n\tresp, err := http.ReadResponse(connr, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\tif resp.StatusCode == 401 {\n\t\t\treturn ErrRevRpcUnauthorized\n\t\t}\n\t\tvar message = \"\"\n\t\tif resp.StatusCode == 400 {\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err == nil {\n\t\t\t\tmessage = string(body)\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\treturn &HttpError{StatusCode: resp.StatusCode, Message: message}\n\t}\n\n\trpcServer := rpc.NewServer()\n\terr = setupBody(rpcServer)\n\trpcServer.RegisterName(\"revrpc\", &RevrpcSvc{service: s})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcodec := newJsonServerCodec(rwc)\n\n\ts.l.Lock()\n\tif s.stopped {\n\t\tcodec.Close()\n\t\ts.l.Unlock()\n\t\treturn io.EOF\n\t}\n\ts.codec = codec\n\ts.l.Unlock()\n\n\trpcServer.ServeCodec(codec)\n\n\treturn io.EOF\n}", "func Run() error {\n\tgo StartServer()\n\n\tlis, err := net.Listen(\"tcp\", \":50051\")\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := grpc.NewServer()\n\n\tklessapi.RegisterKlessAPIServer(s, &apiserver.APIServer{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n\treturn nil\n}", "func (w *worker) start() {\n\tgo func() {\n\t\tresult, err := w.resolve()\n\t\tfor req := range w.reqs {\n\t\t\treq.SetResult(result, err)\n\t\t}\n\t\tw.joinChan <- true\n\t}()\n}", "func startServer(config types.Config, v *Vibranium) *grpc.Server {\n\ts, err := net.Listen(\"tcp\", config.Bind)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\topts := []grpc.ServerOption{grpc.MaxConcurrentStreams(100)}\n\tgrpcServer := grpc.NewServer(opts...)\n\tpb.RegisterCoreRPCServer(grpcServer, v)\n\tgo grpcServer.Serve(s)\n\tlog.Info(\"Cluster started successfully.\")\n\treturn grpcServer\n}", "func main() {\n\tflag.Parse()\n\tfmt.Println(\"start the program\")\n\n\t// go myServer()\n\t// go myClient()\n\n\tfor {\n\t\t// start the app\n\t\twaitc := make(chan struct{}) // a wait lock\n\n\t\t// start the server thread\n\t\tgo func() {\n\t\t\tfmt.Println(\"start the server\")\n\t\t\tserver.InitFileServer()\n\t\t\tdefer close(waitc)\n\t\t}()\n\n\t\t// start the client thread\n\t\t// go func() {\n\t\t// \t// for {\n\t\t// \tserverAddr, server := filesource.SearchAddressForThefile(\"Liben.jpg\")\n\t\t// \tfmt.Println(*serverAddr)\n\t\t// \tfmt.Println(*server)\n\t\t// \tclient.InitFileClient(serverAddr, server)\n\t\t// \tclient.DownloadFile(\"Liben.jpg\")\n\t\t// \t// }\n\t\t// }()\n\n\t\t// start the input thread\n\t\t// go input()\n\n\t\t<-waitc\n\t\t// finished in this round restart the app\n\t\tfmt.Println(\"restart the app\")\n\t}\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on port [%s]: %v\", port, err)\n\t}\n\ts := grpc.NewServer()\n\tpb.RegisterColorGeneratorServer(s, &server{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"Failed to start the server: %v\", err)\n\t}\n}", "func (m *Master) server() {\n\trpc.Register(m)\n\trpc.HandleHTTP()\n\tos.Create(\"mr-socket\")\n\n\tl, e := net.Listen(\"tcp\", \"0.0.0.0:8080\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tlog.Printf(\"Server is running at %s\\n\", l.Addr().String())\n\tgo http.Serve(l, nil)\n}", "func main() {\n initApplicationConfiguration()\n runtime.GOMAXPROCS(2) // in order for the rpc and http servers to work in parallel\n\n go servers.StartRPCServer()\n servers.StartHTTPServer()\n}", "func main() {\n\tport := os.Getenv(\"PORT\")\n\tlog.Printf(\"Starting a device model grpc service in port \" + port)\n\tlis, err := net.Listen(\"tcp\", \":\"+port)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"faild to listen: %v\", err)\n\t}\n\tctn, err := registry.NewContainer()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to build container: %v\", err)\n\t}\n\n\tserver := grpc.NewServer()\n\t// Start the device model service rpc\n\trpc.Apply(server, ctn)\n\n\tgo func() {\n\t\tlog.Printf(\"start grpc server port: %s\", port)\n\t\tserver.Serve(lis)\n\t}()\n\n\tquit := make(chan os.Signal)\n\tsignal.Notify(quit, os.Interrupt)\n\t<-quit\n\tlog.Println(\"stopping grpc server...\")\n\tserver.GracefulStop()\n\tctn.Clean()\n}", "func StartWorker(g handlers.Gwp) {\n\tapp.Logger(nil).Info(\"START\")\n\tfitchers, err := models.GetFetchers(app.API.DB)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tapp.Logger(nil).Info(\"URL: \", fitchers)\n\n\tfor _, fitcher := range fitchers {\n\t\tAddFetcher(fitcher.Id, fitcher.Url, fitcher.Interval)\n\t}\n\n}", "func RPC_Service() {\n\tapi := new(API)\n\terr := rpc.Register(api)\n\tif err != nil {\n\t\tlog.Fatal(\"error registering API\", err)\n\t}\n\trpc.HandleHTTP()\n\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:8080\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"Listener error\", err)\n\t}\n\tlog.Printf(\"serving rpc on port %d\", 8080)\n\thttp.Serve(listener, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(\"error serving: \", err)\n\t}\n}", "func main() {\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\tForceColors: true,\n\t\tFullTimestamp: true,\n\t})\n\tmlog := logrus.WithFields(logrus.Fields{\n\t\t\"component\": componentName,\n\t\t\"version\": env.Version(),\n\t})\n\n\tgrpc_logrus.ReplaceGrpcLogger(mlog.WithField(\"component\", componentName+\"_grpc\"))\n\tmlog.Infof(\"Starting %s\", componentName)\n\n\tgrpcServer, err := createGRPCServer(mlog)\n\tif err != nil {\n\t\tmlog.WithError(err).Fatal(\"failed to create grpc server\")\n\t}\n\t// Start go routines\n\tgo handleExitSignals(grpcServer, mlog)\n\tserveGRPC(env.ServiceAddr(), grpcServer, mlog)\n}", "func (s *Server) listen(listener net.Listener) {\n\tfor {\n\t\t// Accept a connection\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tif s.shutdown {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.logger.Printf(\"[ERR] consul.rpc: failed to accept RPC conn: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo s.handleConn(conn, false)\n\t\tmetrics.IncrCounter([]string{\"rpc\", \"accept_conn\"}, 1)\n\t}\n}", "func (server *RPCServer) Start() {\n\trpcServer := rpc.NewServer()\n\trpcServer.RegisterName(\"Server\", server.handler) //register the handler's methods as the server\n\n\thttpServer := &http.Server{}\n\thttpServer.Handler = rpcServer\n\n\tgo httpServer.Serve(server.listener)\n}", "func (s *Server) startGRPC() {\n\tlistener, err := net.Listen(\"tcp\", s.grpcAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating listen socket: %v\", err)\n\t}\n\n\tgrpcServer := s.service.GRPCServer()\n\n\t// Set up graceful shutdown\n\tgo func() {\n\t\t<-s.ctx.Done()\n\t\tlog.Printf(\"Shutting down gRPC interface\")\n\t\tgrpcServer.GracefulStop()\n\t}()\n\n\t// Start gRPC server\n\tgo func() {\n\t\tlog.Printf(\"Starting gRPC at '%s'\", s.grpcAddr)\n\t\ts.grpcStarted.Done()\n\t\terr = grpcServer.Serve(listener)\n\t\tlog.Printf(\"Starting 2\")\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"gRPC interface returned error: %v\", err)\n\t\t}\n\t\tlog.Printf(\"gRPC interface: shut down\")\n\t\ts.grpcStopped.Done()\n\t}()\n\n}", "func main() {\n\n\tconst apiName = \"handle1\"\n\ttStr := `_` + I.ToS(time.Now().UnixNano())\n\tif len(os.Args) > 1 {\n\t\tapp := fiber.New()\n\n\t\tmode := os.Args[1]\n\t\tswitch mode {\n\t\tcase `apiserver`:\n\t\t\tapp.Get(\"/\", func(c *fiber.Ctx) error {\n\t\t\t\treturn c.SendString(I.ToS(rand.Int63()) + tStr)\n\t\t\t})\n\n\t\tcase `apiproxy`:\n\t\t\t// connect as request on request-reply\n\n\t\t\tconst N = 8\n\t\t\tcounter := uint32(0)\n\t\t\tncs := [N]*nats.Conn{}\n\t\t\tmutex := sync.Mutex{}\n\t\t\tconn := func() *nats.Conn {\n\t\t\t\tidx := atomic.AddUint32(&counter, 1) % N\n\t\t\t\tnc := ncs[idx]\n\t\t\t\tif nc != nil {\n\t\t\t\t\treturn nc\n\t\t\t\t}\n\t\t\t\tmutex.Lock()\n\t\t\t\tdefer mutex.Unlock()\n\t\t\t\tif ncs[idx] != nil {\n\t\t\t\t\treturn ncs[idx]\n\t\t\t\t}\n\t\t\t\tnc, err := nats.Connect(\"127.0.0.1\")\n\t\t\t\tL.PanicIf(err, `nats.Connect`)\n\t\t\t\tncs[idx] = nc\n\t\t\t\treturn nc\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, nc := range ncs {\n\t\t\t\t\tif nc != nil {\n\t\t\t\t\t\tnc.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// handler\n\t\t\tapp.Get(\"/\", func(c *fiber.Ctx) error {\n\t\t\t\tmsg, err := conn().Request(apiName, []byte(I.ToS(rand.Int63())), time.Second)\n\t\t\t\tif L.IsError(err, `nc.Request`) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Use the response\n\t\t\t\treturn c.SendString(string(msg.Data))\n\t\t\t})\n\t\tdefault:\n\t\t}\n\n\t\tlog.Println(mode + ` started ` + tStr)\n\t\tlog.Fatal(app.Listen(\":3000\"))\n\n\t} else {\n\t\t// worker\n\t\tlog.Println(`worker started ` + tStr)\n\n\t\tnc, err := nats.Connect(\"127.0.0.1\")\n\t\tL.PanicIf(err, `nats.Connect`)\n\t\tdefer nc.Close()\n\n\t\tconst queueName = `myqueue`\n\n\t\t//// connect as reply on request-reply (sync)\n\t\t//sub, err := nc.QueueSubscribeSync(apiName, queueName)\n\t\t//L.PanicIf(err, `nc.SubscribeSync`)\n\t\t//\n\t\t////Wait for a message\n\t\t//for {\n\t\t//\tmsg, err := sub.NextMsgWithContext(context.Background())\n\t\t//\tL.PanicIf(err, `sub.NextMsgWithContext`)\n\t\t//\n\t\t//\terr = msg.Respond([]byte(string(msg.Data) + tStr))\n\t\t//\tL.PanicIf(err, `msg.Respond`)\n\t\t//}\n\n\t\t//// channel (async) -- error slow consumer\n\t\t//ch := make(chan *nats.Msg, 1)\n\t\t//_, err = nc.ChanQueueSubscribe(apiName, queueName, ch)\n\t\t//L.PanicIf(err, `nc.ChanSubscribe`)\n\t\t//for {\n\t\t//\tselect {\n\t\t//\tcase msg := <-ch:\n\t\t//\t\tL.PanicIf(msg.Respond([]byte(string(msg.Data)+tStr)), `msg.Respond`)\n\t\t//\t}\n\t\t//}\n\n\t\t// callback (async)\n\t\t_, err = nc.QueueSubscribe(apiName, queueName, func(msg *nats.Msg) {\n\t\t\tres := string(msg.Data) + tStr\n\t\t\tL.PanicIf(msg.Respond([]byte(res)), `msg.Respond`)\n\t\t})\n\n\t\tvar line string\n\t\tfmt.Scanln(&line) // wait for input so not exit\n\t}\n}", "func listenClientRPCs() {\n\tkvServer := rpc.NewServer()\n\tkv := new(KVServer)\n\tkvServer.Register(kv)\n\tl, err := net.Listen(\"tcp\", listenClientIpPort)\n\tcheckError(\"Error in listenClientRPCs(), net.Listen()\", err, true)\n\tfmt.Println(\"Listening for client RPC calls on:\", listenClientIpPort)\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tcheckError(\"Error in listenClientRPCs(), l.Accept()\", err, true)\n\t\tkvServer.ServeConn(conn)\n\t}\n}", "func run() {\n\tlogs.Start()\n\n\t// Send all data for the centralized database\n\tgo store.push()\n\tstore.Lock()\n\tdefer store.Unlock()\n\n\t// Creating the listener\n\tconfigData := config.GetConfig()\n\twatcher(configData)\n}", "func (pr *Prober) start(ctx context.Context) {\n\t// Start the default server\n\tsrv := &http.Server{}\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tsrv.Close()\n\t}()\n\tgo func() {\n\t\tsrv.Serve(pr.serverListener)\n\t\tos.Exit(1)\n\t}()\n\n\tdataChan := make(chan *metrics.EventMetrics, 1000)\n\n\tgo func() {\n\t\tvar em *metrics.EventMetrics\n\t\tfor {\n\t\t\tem = <-dataChan\n\t\t\tvar s = em.String()\n\t\t\tif len(s) > logger.MaxLogEntrySize {\n\t\t\t\tglog.Warningf(\"Metric entry for timestamp %v dropped due to large size: %d\", em.Timestamp, len(s))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Replicate the surfacer message to every surfacer we have\n\t\t\t// registered. Note that s.Write() is expected to be\n\t\t\t// non-blocking to avoid blocking of EventMetrics message\n\t\t\t// processing.\n\t\t\tfor _, surfacer := range pr.surfacers {\n\t\t\t\tsurfacer.Write(context.Background(), em)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Start a goroutine to export system variables\n\tgo sysvars.Start(ctx, dataChan, time.Millisecond*time.Duration(pr.c.GetSysvarsIntervalMsec()), pr.c.GetSysvarsEnvVar())\n\n\t// Start servers, each in its own goroutine\n\tfor _, s := range pr.Servers {\n\t\tgo s.Start(ctx, dataChan)\n\t}\n\n\t// Start RDS server if configured.\n\tif pr.rdsServer != nil {\n\t\tgo pr.rdsServer.Start(ctx, dataChan)\n\t}\n\n\t// Start RTC reporter if configured.\n\tif pr.rtcReporter != nil {\n\t\tgo pr.rtcReporter.Start(ctx)\n\t}\n\n\tif pr.c.GetDisableJitter() {\n\t\tfor _, p := range pr.Probes {\n\t\t\tgo p.Start(ctx, dataChan)\n\t\t}\n\t\treturn\n\t}\n\tpr.startProbesWithJitter(ctx, dataChan)\n}", "func main() {\n handleRequests()\n}", "func listen(addr string, srcvr ...interface{}) error {\n\tvar err error\n\tfor _, v := range srcvr {\n\t\tif err = rpc.Register(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Error: accept rpc connection\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tgo func(conn net.Conn) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tlog.Println(\"Error: Rpc Call Recover\", err, string(debug.Stack()))\n\t\t\t\t}\n\t\t\t}()\n\t\t\tbuf := bufio.NewWriter(conn)\n\t\t\tsrv := &gobServerCodec{\n\t\t\t\trwc: conn,\n\t\t\t\tdec: gob.NewDecoder(conn),\n\t\t\t\tenc: gob.NewEncoder(buf),\n\t\t\t\tencBuf: buf,\n\t\t\t}\n\t\t\tdefer srv.Close()\n\t\t\terr = rpc.ServeRequest(srv)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"Error: rpc server\", err.Error())\n\t\t\t}\n\t\t}(conn)\n\t}\n}", "func main() {\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to start gRPC server: %v\", err)\n\t}\n\n\t// Creates a new gRPC server\n\tsrvr := grpc.NewServer()\n\tds := crawlerDS{visitedUrls: make(map[string]bool),\n\t\turlOnChannel: make(map[string]bool),\n\t\tsiteURLIndex: make(map[string]*linkIndex),\n\t\tsiteIndex: 0,\n\t\tfinishedUrls: make(chan string),\n\t\tsiteIndexURL: make(map[int]string),\n\t\twaitingUrls: make(chan linkIndex),\n\t\tterminate: make([]*chan int, 0)}\n\n\twg.Add(1)\n\tgo ds.startCrawling()\n\n\tpb.RegisterCrawlerServer(srvr, &server{spiderPtr: &ds})\n\tsrvr.Serve(lis)\n}", "func (w Worker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t// register the current worker into the worker queue.\n\t\t\tw.WorkerPool <- w.JobChannel\n\n\t\t\tselect {\n\t\t\tcase job := <-w.JobChannel:\n\t\t\t\t// we have received a work request.\n\t\t\t\tif err := job.Do(); err != nil {\n\t\t\t\t\tlog.Printf(\"Error job.Do() : %v\\n\", err.Error())\n\t\t\t\t}\n\n\t\t\tcase <-w.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func spawnListener(addr string) {\n\tfmt.Println(addr)\n\n\tbRPC := new(BrokerRPCServer)\n\tserver := rpc.NewServer()\n\tserver.Register(bRPC)\n\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", \"0.0.0.0:8000\")\n\t// tcpAddr, err := net.ResolveTCPAddr(\"tcp\", config.BrokerIP)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, err.Error())\n\t}\n\n\tlistener, err := net.ListenTCP(\"tcp\", tcpAddr)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, err.Error())\n\t}\n\n\tfmt.Printf(\"Serving Server at: %v\\n\", config.BrokerIP)\n\n\tvrpc.ServeRPCConn(server, listener, logger, loggerOptions)\n}", "func handleRpcConnection() {\n\n\tfortuneServerRPC := new(FortuneServerRPC)\n\trpc.Register(fortuneServerRPC)\n\n\ttcpAddress, err := net.ResolveTCPAddr(\"tcp\", fserverTcpG)\n\thandleError(err)\n\n\t// Listen for Tcp connections\n\tln, err := net.ListenTCP(\"tcp\", tcpAddress)\n\thandleError(err)\n\n\tfor {\n\n\t\tconn, err := ln.AcceptTCP()\n\t\thandleError(err)\n\t\tgo rpc.ServeConn(conn)\n\t}\n\n\tln.Close()\n}", "func (h *Host) threadedListen(closeChan chan struct{}) {\n\tdefer close(closeChan)\n\n\t// Receive connections until an error is returned by the listener. When an\n\t// error is returned, there will be no more calls to receive.\n\tfor {\n\t\t// Block until there is a connection to handle.\n\t\tconn, err := h.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tgo h.threadedHandleConn(conn)\n\n\t\t// Soft-sleep to ratelimit the number of incoming connections.\n\t\tselect {\n\t\tcase <-h.tg.StopChan():\n\t\tcase <-time.After(rpcRatelimit):\n\t\t}\n\t}\n}", "func main() {\n\tvar (\n\t\terr error\n\t\tlis net.Listener\n\t)\n\tif lis, err = net.Listen(\"tcp\", env.MustHget(\"mail\", \"addr\")); err != nil {\n\t\tdie(err)\n\t}\n\n\tsrv := grpc.NewServer()\n\tpb.RegisterMailServiceServer(srv, &mailServer{})\n\tif err = srv.Serve(lis); err != nil {\n\t\tdie(err)\n\t}\n}", "func (s *grpcServer) Run(ctx context.Context, ready func()) error {\n\tlogger := log.WithContext(ctx)\n\ts.server.Init(ctx, nil)\n\tlistener, err := net.Listen(\"tcp\", s.cfg.Address)\n\tif err != nil {\n\t\tlogger.WithError(err).WithField(\"address\", s.cfg.Address).Error(\"unable to listen tcp address\")\n\t\treturn err\n\t}\n\n\tlogger.Info(\"starting of grpc server...\")\n\ts.server.Init(ctx, nil)\n\tmaster.RegisterMasterServer(s.server.server, s.server)\n\tif err := s.server.server.Serve(listener); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func init() {\r\n\tmux := http.NewServeMux()\r\n\trpcserver.RegisterRPCFuncs(mux, Routes)\r\n\twm := rpcserver.NewWebsocketManager(Routes, nil)\r\n\tmux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)\r\n\tgo func() {\r\n\t\t_, err := rpcserver.StartHTTPServer(tcpAddr, mux)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}()\r\n\r\n\tmux2 := http.NewServeMux()\r\n\trpcserver.RegisterRPCFuncs(mux2, Routes)\r\n\twm = rpcserver.NewWebsocketManager(Routes, nil)\r\n\tmux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)\r\n\tgo func() {\r\n\t\t_, err := rpcserver.StartHTTPServer(unixAddr, mux2)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}()\r\n\r\n\t// wait for servers to start\r\n\ttime.Sleep(time.Second * 2)\r\n\r\n}", "func (svr *Server) Start() (err error) {\n\n\tfor {\n\t\tcliConn, err := svr.listener.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// save connection\n\t\tsvr.mtx.Lock()\n\t\tsvr.connList.PushBack(cliConn)\n\t\tsvr.mtx.Unlock()\n\n\t\tsvr.logger.Debug(\"Accept new connection\", \"RemoteAddr\", cliConn.RemoteAddr())\n\t\tgo svr.readRequest(cliConn)\n\t}\n}", "func (c *raftClient) run(ctx context.Context, wg *sync.WaitGroup, n *Node) {\n\tdefer wg.Done()\n\n\tn.logger.Debugw(\"remote node client worker start running\", c.logKV()...)\n\n\t// Add grpc client interceptor for logging, and metrics collection (if enabled). We do not use payload logging\n\t// because it is currently nailed to InfoLevel.\n\tgcl := n.logger.Named(\"GRPC_C\").Desugar()\n\tunaryInterceptorChain := []grpc.UnaryClientInterceptor{}\n\tif c.node.verboseLogging {\n\t\tunaryInterceptorChain = append(unaryInterceptorChain,\n\t\t\tgrpc_zap.UnaryClientInterceptor(\n\t\t\t\tgcl, grpc_zap.WithLevels(func(code codes.Code) zapcore.Level { return zapcore.DebugLevel })))\n\t}\n\n\tif n.messaging.clientUnaryInterceptorForMetrics != nil {\n\t\tunaryInterceptorChain = append(unaryInterceptorChain, n.messaging.clientUnaryInterceptorForMetrics)\n\t}\n\n\t// Prepend our options such that they can be overridden by the client options if they overlap.\n\toptions := []grpc.DialOption{\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithKeepaliveParams(keepalive.ClientParameters{\n\t\t\tTime: time.Second * defaultInactivityTriggeredPingSeconds,\n\t\t\tTimeout: time.Second * defaultTimeoutAfterPingSeconds,\n\t\t}),\n\t\tgrpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(unaryInterceptorChain...))}\n\n\t// Append client provided dial options specifically for this client to server connection.\n\tif n.config.clientDialOptionsFn != nil {\n\t\toptions = append(options, n.config.clientDialOptionsFn(n.messaging.server.localAddr, c.remoteAddress)...)\n\t}\n\n\tconn, err := grpc.DialContext(ctx, c.remoteAddress, options...)\n\tif err != nil {\n\t\tif ctx.Err() == nil {\n\t\t\t// This is not a shutdown. We have taken a fatal error (i.e. this is not a transient error). Possibly\n\t\t\t// a misconfiguration of the options, for example. We will return a fatal error.\n\t\t\tn.logger.Errorw(\"remote node client worker aborting\", append(c.logKV(), raftErrKeyword, err)...)\n\t\t\tn.signalFatalError(raftErrorf(\n\t\t\t\tRaftErrorClientConnectionUnrecoverable, \"grpc client connection to remote node, err [%v]\", err))\n\t\t}\n\t\treturn\n\t}\n\n\tdefer func() { _ = conn.Close() }()\n\n\tn.logger.Debugw(\"remote node client worker connected\",\n\t\tappend(c.logKV(), \"connState\", conn.GetState().String())...)\n\tc.grpcClient = raft_pb.NewRaftServiceClient(conn)\n\n\tfor {\n\t\tselect {\n\t\tcase e := <-c.eventChan.channel:\n\t\t\t// The event handler carries all the context necessary, and equally handles the\n\t\t\t// feedback based on the outcome of the event.\n\t\t\te.handle(ctx)\n\n\t\tcase <-ctx.Done():\n\t\t\t// We're done. By this point we will have cleaned up and we're ready to go.\n\t\t\tn.logger.Debugw(\"remote node client worker shutting down\", c.logKV()...)\n\t\t\treturn\n\t\t}\n\n\t}\n\n}", "func servidor(in chan Request, fim chan int) {\r\n\t\t\r\n\tfor {\r\n\t\t// le requisicao do cliente\r\n\t\treq := <-in\r\n\r\n\t\t// acha uma thread disponivel para \r\n\t\t// enviar a requisicao\r\n\t\tvar canal Thread = achaCanal()\r\n\r\n\t\t// envia requisicao para a thread\r\n\t\tcanal.thr <- req\r\n\t}\r\n}", "func StartRPC() {\n\t/*\n\t * Will register the user auth rpc with rpc package\n\t * We will listen to the http with rpc of auth module\n\t * Then we will start listening to the rpc port\n\t */\n\t//Registering the auth model with the rpc package\n\trpc.Register(new(aConfig.RPCAuth))\n\n\t//registering the handler with http\n\trpc.HandleHTTP()\n\tl, e := net.Listen(\"tcp\", \":\"+RPCPort)\n\tif e != nil {\n\t\tlog.Fatal(\"Error while listening to the rpc port\", e.Error())\n\t}\n\tgo http.Serve(l, nil)\n}", "func (stub *RunnerStub) StartListeningAndBlock(ctx context.Context, commandrunner <-chan int) error {\n\n\tstub.channel.NatsNativeConn.Subscribe(stub.channel.NatsPublishName, func(msg *natsio.Msg) {\n\t\tcarrier := requests.RequestCarrier{}\n\n\t\tif err := json.Unmarshal(msg.Data, &carrier); err != nil {\n\t\t\tlog := fmt.Errorf(\"[Error]: stub: unable to unmarshal command from json: %s\", err)\n\t\t\tfmt.Println(log)\n\t\t}\n\n\t\tswitch carrier.CarrierForType {\n\t\tcase requests.RunnerCancel:\n\t\t\tstub.cancellationHandler()\n\t\tcase requests.RunnerHealth:\n\t\t\tisHealthy := stub.healthyHandler()\n\t\t\trply := requests.NewRunnerHealthRequest()\n\t\t\trply.IsHealthy = isHealthy\n\t\t\tcarrier.Data = rply\n\n\t\t\tif json, err := json.Marshal(carrier); err != nil {\n\t\t\t\tmsg.Respond(json)\n\t\t\t} else {\n\t\t\t\tlog := fmt.Errorf(\"[Error]: stub: unable to marshal command from json: %s\", err)\n\t\t\t\tfmt.Println(log)\n\t\t\t}\n\t\t}\n\t})\n\n\tselect {\n\tcase <-commandrunner:\n\t}\n\treturn nil\n}", "func Run() (err error) {\n\n\t// Register Message Queue handler\n\thandler := mq.MsgHandler{Handler: msgHandler, UserData: nil}\n\tsbi.handlerId, err = sbi.mqLocal.RegisterHandler(handler)\n\tif err != nil {\n\t\tlog.Error(\"Failed to register local Msg Queue listener: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Registered local Msg Queue listener\")\n\n\treturn nil\n}", "func (s *Server) Start(ctx context.Context, cfg config.Config) error {\n\ts.mtx.Lock()\n\n\tcmtCfg := tmrpcserver.DefaultConfig()\n\tcmtCfg.MaxOpenConnections = int(cfg.API.MaxOpenConnections)\n\tcmtCfg.ReadTimeout = time.Duration(cfg.API.RPCReadTimeout) * time.Second\n\tcmtCfg.WriteTimeout = time.Duration(cfg.API.RPCWriteTimeout) * time.Second\n\tcmtCfg.MaxBodyBytes = int64(cfg.API.RPCMaxBodyBytes)\n\n\tlistener, err := tmrpcserver.Listen(cfg.API.Address, cmtCfg.MaxOpenConnections)\n\tif err != nil {\n\t\ts.mtx.Unlock()\n\t\treturn err\n\t}\n\n\ts.listener = listener\n\ts.mtx.Unlock()\n\n\t// configure grpc-web server\n\tif cfg.GRPC.Enable && cfg.GRPCWeb.Enable {\n\t\tvar options []grpcweb.Option\n\t\tif cfg.API.EnableUnsafeCORS {\n\t\t\toptions = append(options,\n\t\t\t\tgrpcweb.WithOriginFunc(func(origin string) bool {\n\t\t\t\t\treturn true\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\twrappedGrpc := grpcweb.WrapServer(s.GRPCSrv, options...)\n\t\ts.Router.PathPrefix(\"/\").Handler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\tif wrappedGrpc.IsGrpcWebRequest(req) {\n\t\t\t\twrappedGrpc.ServeHTTP(w, req)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Fall back to grpc gateway server.\n\t\t\ts.GRPCGatewayRouter.ServeHTTP(w, req)\n\t\t}))\n\t}\n\n\t// register grpc-gateway routes (after grpc-web server as the first match is used)\n\ts.Router.PathPrefix(\"/\").Handler(s.GRPCGatewayRouter)\n\n\terrCh := make(chan error)\n\n\t// Start the API in an external goroutine as Serve is blocking and will return\n\t// an error upon failure, which we'll send on the error channel that will be\n\t// consumed by the for block below.\n\tgo func(enableUnsafeCORS bool) {\n\t\ts.logger.Info(\"starting API server...\", \"address\", cfg.API.Address)\n\n\t\tif enableUnsafeCORS {\n\t\t\tallowAllCORS := handlers.CORS(handlers.AllowedHeaders([]string{\"Content-Type\"}))\n\t\t\terrCh <- tmrpcserver.Serve(s.listener, allowAllCORS(s.Router), servercmtlog.CometLoggerWrapper{Logger: s.logger}, cmtCfg)\n\t\t} else {\n\t\t\terrCh <- tmrpcserver.Serve(s.listener, s.Router, servercmtlog.CometLoggerWrapper{Logger: s.logger}, cmtCfg)\n\t\t}\n\t}(cfg.API.EnableUnsafeCORS)\n\n\t// Start a blocking select to wait for an indication to stop the server or that\n\t// the server failed to start properly.\n\tselect {\n\tcase <-ctx.Done():\n\t\t// The calling process canceled or closed the provided context, so we must\n\t\t// gracefully stop the API server.\n\t\ts.logger.Info(\"stopping API server...\", \"address\", cfg.API.Address)\n\t\treturn s.Close()\n\n\tcase err := <-errCh:\n\t\ts.logger.Error(\"failed to start API server\", \"err\", err)\n\t\treturn err\n\t}\n}", "func startHTTPServer(name string, waitChan chan<- WaitEntry, server *http.Server) {\n\tgo func() {\n\t\terr := server.ListenAndServe()\n\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\twaitChan <- WaitEntry{\n\t\t\t\tname: name,\n\t\t\t\terr: fmt.Errorf(\"error running http server: %s\", err.Error()),\n\t\t\t}\n\t\t}\n\t}()\n}", "func (c *Connection) Worker() {\n\n\tfor {\n\t\tselect {\n\t\tcase _ = <-c.workerctx.Done():\n\t\t\treturn\n\t\tcase inData := <-c.In:\n\t\t\theader, _ := wire.GetHeader(inData)\n\n\t\t\tif header.CmdType == wire.CMD_EXIT {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\n\t\t\tlogg.Debug(\"processing server cmd\")\n\n\t\t\tcmdFunc, ok := cmd.CommandBuffer[header.CmdType]\n\t\t\tif !ok {\n\t\t\t\tlogg.Log(\"Command not implemented\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnewctx1, _ := context.WithCancel(c.workerctx)\n\t\t\tgo cmdFunc(inData, c.Out, newctx1)\n\t\t}\n\t}\n\n}", "func main() {\n\t// Listen an actual port.\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", 9093))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\tdefer lis.Close()\n\n\t// Create a HTTP server for prometheus.\n\thttpServer := &http.Server{Handler: promhttp.HandlerFor(reg, promhttp.HandlerOpts{}), Addr: fmt.Sprintf(\"0.0.0.0:%d\", 9092)}\n\n\t// Create a gRPC Server with gRPC interceptor.\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.StreamInterceptor(grpcMetrics.StreamServerInterceptor()),\n\t\tgrpc.UnaryInterceptor(grpcMetrics.UnaryServerInterceptor()),\n\t)\n\n\t// Create a new api server.\n\tdemoServer := newDemoServer()\n\n\t// Register your service.\n\tpb.RegisterDemoServiceServer(grpcServer, demoServer)\n\n\t// Initialize all metrics.\n\tgrpcMetrics.InitializeMetrics(grpcServer)\n\n\t// Start your http server for prometheus.\n\tgo func() {\n\t\tif err := httpServer.ListenAndServe(); err != nil {\n\t\t\tlog.Fatal(\"Unable to start a http server.\")\n\t\t}\n\t}()\n\n\t// Start your gRPC server.\n\tlog.Fatal(grpcServer.Serve(lis))\n}", "func main() {\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalf(\"Usage: %s <port to listen on>\", os.Args[0])\n\t}\n\tport := os.Args[1]\n\n\tfile, _ := os.Open(\"config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := Config{}\n\terr := decoder.Decode(&config)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get configuration: %v\", err)\n\t}\n\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%s\", port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\ts := api.Server{\n\t\tn: config.every_nth_request_slow,\n\t\tdelay: config.seconds_delay,\n\t}\n\tgrpcServer := grpc.NewServer()\n\tapi.RegisterRandomStrServer(grpcServer, &s)\n\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %s\", err)\n\t}\n}", "func (w *worker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t// consume done ,then worker reenter workerPool\n\t\t\tw.workerPool <- w.taskChannel\n\t\t\tselect {\n\t\t\tcase task := <-w.taskChannel:\n\t\t\t\t// received a work request and consume it\n\t\t\t\tif err := task.Consume(); err != nil {\n\t\t\t\t\tlog.Printf(\"Task Consume fail: %v\", err.Error())\n\t\t\t\t}\n\t\t\tcase <-w.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func Start() {\n\t{\n\t\t// Creating a grpc server, use WithInsecure to allow http connections\n\t\tgrpcServer := grpc.NewServer()\n\n\t\t// Creates an instance of Info\n\t\tinfoService := services.NewInfo()\n\n\t\t// Creates an instance of Node\n\t\tnodeService := services.NewNode()\n\n\t\t// This helps clients determine which services are available to call\n\t\treflection.Register(grpcServer)\n\n\t\t// Similar to registering handlers for http\n\t\tprotos.RegisterInfoServer(grpcServer, infoService)\n\n\t\tprotos.RegisterNodeServer(grpcServer, nodeService)\n\n\t\tl, err := net.Listen(\"tcp\", Address)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Unable to listen %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Listen for requests\n\t\tklog.Infof(\"Starting server at : %v \", Address)\n\t\terr = grpcServer.Serve(l)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Unable to Serve %v\", err)\n\t\t}\n\n\t}\n}", "func StartServer(cleanUpChan chan int){\n\tGrpcServer = &Server{\n CleanUpChan:cleanUpChan ,\n\t GrpcServer: grpc.NewServer(),\n\t}\n\tregisterGrpcServices(GrpcServer.GrpcServer)\n\tif err := GrpcServer.GrpcServer.Serve(getListner(port)); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Run(ctx context.Context, network, address string) error {\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := listener.Close(); err != nil {\n\t\t\tlog.Fatalf(\"Failed to close %s %s: %v\", network, address, err)\n\t\t}\n\t}()\n\n\tserver := grpc.NewServer()\n\tpb.RegisterEchoServiceServer(server, newEchoServer())\n\n\tgo func() {\n\t\tdefer server.GracefulStop()\n\t\t<-ctx.Done()\n\t}()\n\treturn server.Serve(listener)\n}" ]
[ "0.64228386", "0.6311771", "0.61102027", "0.60433155", "0.58660907", "0.58396554", "0.5837046", "0.5835587", "0.5806269", "0.58008647", "0.5780179", "0.5770865", "0.57657355", "0.5763558", "0.5762116", "0.57530826", "0.57442045", "0.57440096", "0.57366097", "0.5727227", "0.5720068", "0.5719461", "0.5716348", "0.57118237", "0.57102615", "0.5709161", "0.57078487", "0.56971794", "0.56933683", "0.5693036", "0.569176", "0.5691574", "0.56809855", "0.5662304", "0.5661858", "0.5655399", "0.56498736", "0.56361365", "0.5634696", "0.56049514", "0.5603366", "0.5599928", "0.5593171", "0.5589113", "0.5578144", "0.5553698", "0.5540472", "0.5540227", "0.55319524", "0.5531017", "0.5528274", "0.5524018", "0.5523449", "0.552284", "0.5519628", "0.5511653", "0.55009437", "0.5492727", "0.5488525", "0.5485432", "0.54832685", "0.547846", "0.5468756", "0.5463479", "0.5463081", "0.5462983", "0.5459293", "0.5452982", "0.54502296", "0.5448126", "0.544778", "0.5440759", "0.5439389", "0.5430851", "0.54242337", "0.54225546", "0.5422146", "0.54216444", "0.5420302", "0.54202574", "0.5415169", "0.54114485", "0.5408017", "0.5400847", "0.53938115", "0.5392032", "0.5391077", "0.53890574", "0.53788537", "0.5377101", "0.5376344", "0.5371586", "0.5364387", "0.5359369", "0.535893", "0.53568506", "0.5341484", "0.53382826", "0.53350455", "0.53308225", "0.5329204" ]
0.0
-1
main/mrmaster.go calls Done() periodically to find out if the entire job has finished.
func (m *Master) Done() bool { ret := false if (m.taskPhase == ExitPhase) { ret = true } // Your code here. return ret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Master) Done() bool {\n\tret := false\n\tfmt.Printf(\"MapTasks: %v\\n\", m.mapTasks)\n\tfmt.Printf(\"RedTasks: %v\\n\", m.reduceTasks)\n\tfmt.Printf(\"nReduce: %d, nMap: %d\\n\", m.nReduce, m.nMap)\n\t// Your code here.\n\t// all tasks have finished\n\tif m.hasGenerateReduceTasks && m.nReduce <= 0 && m.nMap <= 0 {\n\t\tret = true\n\t\tfmt.Println(\"The job has finished!\")\n\t}\n\treturn ret\n}", "func (m *Master) Done() bool {\n\t// Your code here.\n\treturn m.jobs.empty(ReduceJob)\n}", "func (m *Master) Done() bool {\n\tsuccNum := atomic.LoadInt64(&m.JobManager.SuccNum)\n\tif succNum == int64(m.Rnum) {\n\t\tclose(m.JobManager.Jobs) // 安全关闭\n\t\tclose(m.JobManager.RShuffleChan)\n\t\treturn true\n\t}\n\treturn false\n}", "func (m *Master) Done() bool {\n\t// Your code here.\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tnum_active_client := len(m.clients)\n\tfmt.Println(\"Active clients: \" + strconv.Itoa(num_active_client))\n\n\tdone := true\n\tfor job, job_status := range m.jobs {\n\t\tfmt.Println(job + \": \" + job_status)\n\t\tif job_status != \"done\" {\n\t\t\tdone = false\n\t\t}\n\t}\n\treturn done\n}", "func (m *Master) Done() bool {\n\tret := false\n\tfor _, worker := range m.WorkerMap {\n\t\t// ping to worker\n\t\t_, err := rpc.DialHTTP(\"tcp\", worker.Host + fmt.Sprintf(\":%d\", worker.Port))\n\t\tif err != nil {\n\t\t\tm.mu.Lock()\n\t\t\tdelete(m.WorkerMap, worker.ID)\n\t\t\tm.mu.Unlock()\n\n\t\t\tlog.Printf(\"worker %s died!\\n\", worker.ID)\n\t\t\tlog.Println(\"re-assign task to other worker\")\n\t\t\tif m.NumMapperCompleted < len (m.MapperTask) {\n\t\t\t\tfor _, mTask := range m.MapperTask {\n\t\t\t\t\tif mTask.WorkerID == worker.ID {\n\t\t\t\t\t\tmTask.Status = Idle\n\t\t\t\t\t\tm.mu.Lock()\n\t\t\t\t\t\tm.MapperTask[mTask.ID] = mTask\n\t\t\t\t\t\tm.mu.Unlock()\n\t\t\t\t\t\tlog.Println(\"mapper task hold by worker has released. Task ID: \", mTask.ID)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif m.NumReduceCompleted < len (m.ReducerTask) {\n\t\t\t\tfor _, rTask := range m.ReducerTask {\n\t\t\t\t\tif rTask.WorkerID == worker.ID {\n\t\t\t\t\t\trTask.Status = Idle\n\t\t\t\t\t\tm.mu.Lock()\n\t\t\t\t\t\tm.ReducerTask[int(rTask.ID)] = rTask\n\t\t\t\t\t\tm.mu.Unlock()\n\t\t\t\t\t\tlog.Println(\"reducer task hold by worker has released. Task ID: \", rTask.ID)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"worker %s is running \\n\", worker.ID)\n\t\t}\n\t}\n\t// tasks completed\n\tif m.NumReduceCompleted == m.NReduce {\n\t\tret = true\n\t}\n\treturn ret\n}", "func (m *Master) Done() bool {\r\n\tret := false\r\n\r\n\t// Your code here.\r\n\t// wg.Wait()\r\n\r\n\tret = <-m.done\r\n\r\n\tm.mux.Lock()\r\n\tif len(m.failedReduceFinish) != 0 {\r\n\t\t// log.Printf(\"Crashed Workers: %v\\n\", m.failedReduceFinish)\r\n\t\tfor _, taskNo := range m.failedReduceFinish {\r\n\t\t\tfilename := \"mr-out-\" + strconv.Itoa(taskNo)\r\n\t\t\terr := os.Remove(filename)\r\n\t\t\tif err != nil {\r\n\t\t\t\t// log.Println(\"Delete file failed: \", filename)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tm.mux.Unlock()\r\n\r\n\treturn ret\r\n}", "func (m *Master) Done() bool {\n\t// Re-issue map tasks if the master waits for more than ten seconds.\n\tfor i, v := range m.mapStates {\n\t\tif v.state == 0 {\n\t\t\treturn false\n\t\t}\n\t\tif v.state == 1 {\n\t\t\telapsed := time.Since(v.t)\n\t\t\tif elapsed > time.Second*10 {\n\t\t\t\tm.mapStates[i].state = 0\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\t// Re-issue reduce tasks if the master waits for more than ten seconds.\n\tfor i, v := range m.reduceStates {\n\t\tif v.state == 0 {\n\t\t\treturn false\n\t\t}\n\t\tif v.state == 1 {\n\t\t\telapsed := time.Since(v.t)\n\t\t\tif elapsed > time.Second*10 {\n\t\t\t\tm.reduceStates[i].state = 0\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\t// All map and reduce tasks are finished.\n\treturn true\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\t// clear timeout task\n\tfor i, taskPatchTime := range m.todoMapTask {\n\t\tif taskPatchTime != 0 && taskPatchTime+10 < time.Now().Unix() {\n\t\t\tfmt.Printf(\"MapTask Timeout: TaskID:%d\\n\", i)\n\t\t\tm.todoMapTask[i] = 0\n\t\t}\n\t}\n\tfor i, taskPatchTime := range m.todoReduceTask {\n\t\tif taskPatchTime != 0 && taskPatchTime+10 < time.Now().Unix() {\n\t\t\tfmt.Printf(\"ReduceTask Timeout: TaskID:%d\\n\", i)\n\t\t\tm.todoReduceTask[i] = 0\n\t\t}\n\t}\n\n\tret = len(m.todoMapTask) == 0 && len(m.todoReduceTask) == 0\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\n\t// Your code here.\n\n\treturn m.end\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\t// show taskSummary\n\tlogger.Debug(fmt.Sprintf(\"TaskSummary:\\n%s\", m.printTaskSummary()))\n\n\t// Increment SinceLastHeartbeat field for each in-progress tasks\n\tm.increaseSinceLastHeartbeat()\n\n\t// Stop and reschedule task for task with SinceLastHeartbeat > 10\n\t// TODO: Implement fail recovery\n\tdeadTasks, ok := m.checkDeadWorker()\n\tif ok {\n\t\t// fail recovery\n\t\tfor _, dTaskInfo := range deadTasks {\n\t\t\tlogger.Debug(\"Fail recovery for deadWOrker() and deadTask() ...\")\n\t\t\tm.mu.Lock()\n\t\t\tm.aliveWorkerCount -= 1\n\t\t\tm.deadWorkerCount += 1\n\t\t\tm.mu.Unlock()\n\t\t\tm.resetTaskToIdle(dTaskInfo.TaskId)\n\t\t}\n\n\t}\n\n\t// Check if there is any undo task left\n\tif m.checkAllTaskFinished() {\n\t\tret = true\n\t}\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tret := false\n\t// Your code here.\n\tm.mutex.Lock()\n\tret = m.isFinished_\n\tm.mutex.Unlock()\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tif m.reduceFinished == m.reduceTasks {\n\t\tret = true\n\t}\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tif m.State == Success {\n\t\treturn true\n\t}\n\n\t// Your code here.\n\tif m.State == Map {\n\t\treturn false\n\t}\n\tfor _, v := range m.ReduceTask {\n\t\tif v.Status != Finish {\n\t\t\treturn false\n\t\t}\n\t}\n\tm.State = Success\n\treturn true\n}", "func (m *Master) Done() bool {\n\n\t// Your code here.\n\treturn m.ReduceFinish\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tm.Mutex.Lock()\n\tdefer m.Mutex.Unlock()\n\tif m.Phase == Reduce && len(m.Undone) == 0 && len(m.Doing) == 0 {\n\t\tret = true\n//\t\tlog.Printf(\"all tasks finished\")\n\t}\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\n\tif !m.isAllMapCompleted() {\n\t\tm.Mux.Lock()\n\t\tfor i := 0; i < m.M; i += 1 {\n\t\t\tif m.IsIdleMaps[i] == 1 {\n\t\t\t\tif time.Now().Unix() - m.MapTasksTime[i] > TIMEOUT {\n\t\t\t\t\tm.IsIdleMaps[i] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tm.Mux.Unlock()\n\t} else {\n\t\tm.Mux.Lock()\n\t\tfor i := 0; i < m.R; i += 1 {\n\t\t\tif m.IsIdleReduces[i] == 1 {\n\t\t\t\tif time.Now().Unix() - m.ReduceTasksTime[i] > TIMEOUT {\n\t\t\t\t\tm.IsIdleReduces[i] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tm.Mux.Unlock()\n\t}\n\n\tfor i := 0; i < m.R; i += 1 {\n\t\tif m.IsIdleReduces[i] != 2 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (m *Master) Done() bool {\n\t// ret := (JobDown == m.phase)\n\n\t// Your code here.\n\treturn JobDown == m.phase\n}", "func (m *Master) Done() bool {\n\n\t// Your code here.\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\treturn m.state == TearDown\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tif len(m.completedTasks[0])==m.M && len(m.completedTasks[1])==m.R {\n\t\tret = true\n\t}\n\treturn ret\n}", "func (m *Master) Done() bool {\n\t// Your code here.\n\n\treturn m.done\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tif m.remainReduceCount == 0 {\n\t\tret = true\n\t}\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tif m.done {\n\t\tfmt.Println(\"All task finished. Exiting...\")\n\t}\n\treturn m.done\n}", "func (m *Master) Done() bool {\n\t// Your code here.\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\treturn m.done\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tif len(m.DoneReduceTask) == m.NReduce {\n\t\tret = true\n\t}\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tfor _, val := range m.RTasks {\n\t\tif val.status == IDLE || val.status == RUNNING {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *Master) haveDone() bool {\n\tret := true\n\tt := time.Now().Unix()\n\tj := 0\n\tfor j < len(m.reduceTasks) {\n\t\tif m.reduceTasks[j].state == 1 {\n\t\t\tif t-m.reduceTasks[j].emittime >= TIMEOUT {\n\t\t\t\tm.reduceTasks[j].state = 0\n\t\t\t}\n\t\t}\n\t\tj++\n\t}\n\ti := 0\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state == 0 {\n\t\t\tm.nextreducetask = i\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\tfor _, reduceTask := range m.reduceTasks {\n\t\tif reduceTask.state != 2 {\n\t\t\tret = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif ret {\n\t\tm.done = true\n\t}\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\treturn m.mapDone && m.reduceDone\n}", "func (m *Master) Done() bool {\n\tm.RWMutexLock.Lock()\n\tdefer m.RWMutexLock.Unlock()\n\tret := m.reduceFinished\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tret := false\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tret = m.haveDone()\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tm.accessLock.Lock()\n\tdefer m.accessLock.Unlock()\n\tret := len(m.completedReduces) == m.nReduce\n\treturn ret\n}", "func (m *Master) mapfinished() bool {\n\tt := time.Now().Unix()\n\tret := true\n\tj := 0\n\tfor j < len(m.mapTasks) {\n\t\tif m.mapTasks[j].state == 1 {\n\t\t\tif t-m.mapTasks[j].emittime >= TIMEOUT {\n\t\t\t\tm.mapTasks[j].state = 0\n\t\t\t}\n\t\t}\n\t\tj++\n\t}\n\ti := 0\n\tfor i < len(m.mapTasks) {\n\t\tif m.mapTasks[i].state == 0 {\n\t\t\tm.nextmaptask = i\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\tfor _, mapTask := range m.mapTasks {\n\t\tif mapTask.state != 2 {\n\t\t\tret = false\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}", "func (m *Master) Done() bool {\n\tret := false\n\n\t// Your code here.\n\tif m.M.ToDo <= 0 && m.R.ToDo <= 0 {\n\t\tret = true\n\t}\n\n\treturn ret\n}", "func (mr *MapReduce) RunMaster() []int {\n\tnumMapJobs := mr.nMap\n\tnumReduceJobs := mr.nReduce\n\tvar w sync.WaitGroup\n\n\tfor mapJob := 0; mapJob < numMapJobs; mapJob++ {\n\t\tavailableWorker := <-mr.registerChannel\n\t\tfmt.Println(\"USING WORKER\", availableWorker, \"for Map Job\")\n\t\tw.Add(1)\n\t\tgo func(worker string, i int) {\n\t\t\tdefer w.Done()\n\t\t\tvar reply DoJobReply\n\t\t\targs := &DoJobArgs{mr.file, Map, i, mr.nReduce}\n\t\t\tok := call(worker, \"Worker.DoJob\", args, &reply)\n\t\t\tif !ok {\n\t\t\t\tfmt.Println(\"Map Job\", i, \"has FAILED\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Map Job\", i, \"is SUCCESS\")\n\t\t\t}\n\t\t\tmr.registerChannel <- worker\n\t\t}(availableWorker, mapJob)\n\t}\n\n\tw.Wait()\n\tfmt.Println(\"DONE WITH ALL MAP JOBS\")\n\n\tfor reduceJob := 0; reduceJob < numReduceJobs; reduceJob++ {\n\t\tavailableWorker := <-mr.registerChannel\n\t\tfmt.Println(\"USING WORKER\", availableWorker, \"for Reduce Job\")\n\t\tw.Add(1)\n\t\tgo func(worker string, i int) {\n\t\t\tdefer w.Done()\n\t\t\tvar reply DoJobReply\n\t\t\targs := &DoJobArgs{mr.file, Reduce, i, mr.nMap}\n\t\t\tok := call(worker, \"Worker.DoJob\", args, &reply)\n\t\t\tif !ok {\n\t\t\t\tfmt.Println(\"Reduce Job\", i, \"has FAILED\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Reduce Job\", i, \"is SUCCESS\")\n\t\t\t}\n\t\t\tmr.registerChannel <- worker\n\t\t}(availableWorker, reduceJob)\n\t}\n\n\tw.Wait()\n\tfmt.Println(\"DONE WITH ALL REDUCE JOBS\")\n\n\treturn mr.KillWorkers()\n}", "func (op *RunJobOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (op *RunReportJobOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (mdb *memdbSlice) checkAllWorkersDone() bool {\n\n\t//if there are mutations in the cmdCh, workers are\n\t//not yet done\n\tif mdb.getCmdsCount() > 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (p *SQLResourcesRetrieveContinuousBackupInformationPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *MongoDBResourcesRetrieveContinuousBackupInformationPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (op *UpdateJobOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (mr *MapReduce) RunMaster() *list.List {\n\t// Your code here\n\tsendList := list.New()\t\t// list of jobs that need to be dispatched\n\tjobList := list.New()\t\t// list of jobs that are waiting to finish\n\tdoneChan := make(chan string)\t// dispatcher thread signals on this channel when worker finishes job successfully\n\tfailChan := make(chan struct {jobNumber int; worker string})\t// dispatched thread signals here when worker fails to process request\n\t\n\t\n\t// Add all map jobs to lists\n\tfor i := 0; i < mr.nMap; i++ {\n\t\tsendList.PushBack(i)\n\t\tjobList.PushBack(i)\n\t}\n\t\n\t// Dispatch all map jobs and wait for them to finish\n\te := sendList.Front()\n\tfor jobList.Len() > 0 {\n\t\t// dispatch jobs if any are waiting\n\t\tif e != nil {\n\t\t\tif (mr.SendJob(mr.file, Map, e.Value.(int), mr.nReduce, doneChan, failChan) == true) {\n\t\t\t\tp := e\n\t\t\t\te = e.Next()\t\t// move to next job \n\t\t\t\tsendList.Remove(p)\t// and remove current job from list only if current job successfully sent\n\t\t\t}\n\t\t}\t\n\t\t\n\t\tselect {\n\t\tcase worker := <- mr.registerChannel:\t// process new worker registrations\n\t\t\tmr.Workers[worker] = &WorkerInfo{worker, -1, false, false}\n\t\t\tfmt.Printf(\"Registered worker %v\\n\", mr.Workers[worker])\n\t\t\t\n\t\tcase worker := <- doneChan:\t\t\t\t// take finished jobs off the jobList and mark the worker as free\n\t\t\tmr.Workers[worker].busy = false\n\t\t\tjobList.Remove(FindListElement(jobList, mr.Workers[worker].currentJobNumber))\n\t\t\tmr.Workers[worker].currentJobNumber = -1\n\t\t\t\n\t\tcase failure := <- failChan:\t\t\t// if any job fails, re-add the job to the sendList and mark the worker as failed \n\t\t\tsendList.PushBack(failure.jobNumber)\n\t\t\tmr.Workers[failure.worker].failed = true\n\t\t\t\n\t\t}\n\t\t\n\t}\n\t\n\tsendList.Init()\t// clear the lists\n\tjobList.Init()\n\t\n\t// Add all reduce jobs to the lists\n\tfor i := 0; i < mr.nReduce; i++ {\n\t\tsendList.PushBack(i)\n\t\tjobList.PushBack(i)\n\t}\n\t\n\t// Dispatch all reduce jobs and wait for them to finish\n\te = sendList.Front()\n\tfor jobList.Len() > 0 {\n\t\t// dispatch jobs if any are waiting\n\t\tif e != nil {\n\t\t\tif (mr.SendJob(mr.file, Reduce, e.Value.(int), mr.nMap, doneChan, failChan) == true) {\n\t\t\t\tp := e\n\t\t\t\te = e.Next()\t\t// move to next job \n\t\t\t\tsendList.Remove(p)\t// and remove current job from list only if current job successfully sent\n\t\t\t}\n\t\t}\t\n\t\t\n\t\tselect {\n\t\tcase worker := <- mr.registerChannel:\t// process new worker registrations\n\t\t\tmr.Workers[worker] = &WorkerInfo{worker, -1, false, false}\n\t\t\tfmt.Printf(\"Registered worker %v\\n\", mr.Workers[worker])\n\t\t\t\n\t\tcase worker := <- doneChan:\t\t\t\t// take finished jobs off the jobList and mark the worker as free\n\t\t\tmr.Workers[worker].busy = false\n\t\t\tjobList.Remove(FindListElement(jobList, mr.Workers[worker].currentJobNumber))\n\t\t\tmr.Workers[worker].currentJobNumber = -1\n\t\t\t\n\t\tcase failure := <- failChan:\t\t\t// if any job fails, re-add the job to the sendList and mark the worker as failed \n\t\t\tsendList.PushBack(failure.jobNumber)\n\t\t\tmr.Workers[failure.worker].failed = true\n\t\t}\n\t\t\n\t}\n\t\n\treturn mr.KillWorkers()\t\t// kill the workers and return\n}", "func (p *SQLResourcesClientRetrieveContinuousBackupInformationPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (c *Coordinator) Done() bool {\n\treturn c.MapAllDone && c.ReduceAllDone\n}", "func (m *Master) checkComplete(taskType string, taskNum int) {\n\n\ttime.Sleep(10 * time.Second)\n\tm.mu.Lock()\n\tif taskType == \"map\" {\n\t\tif m.mapState[taskNum].Value == \"in-progress\" {\n\t\t\tm.mapState[taskNum].Value = \"idle\"\n\t\t}\n\t} else {\n\t\tif m.reduceState[taskNum] == \"in-progress\" {\n\t\t\tm.reduceState[taskNum] = \"idle\"\n\t\t}\n\t}\n\tm.mu.Unlock()\n}", "func (p *MongoDBResourcesClientRetrieveContinuousBackupInformationPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func msmtFinished(currSrvBytes *uint) bool {\n\tif *currSrvBytes >= *msmtTotalBytes {\n\t\t// debug fmt.Println(\"\\nServer received everything from client: Msmt finished\")\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (fdb *fdbSlice) checkAllWorkersDone() bool {\n\n\t//if there are mutations in the cmdCh, workers are\n\t//not yet done\n\tif len(fdb.cmdCh) > 0 {\n\t\treturn false\n\t}\n\n\t//worker queue is empty, make sure both workers are done\n\t//processing the last mutation\n\tfor i := 0; i < NUM_WRITER_THREADS_PER_SLICE; i++ {\n\t\tfdb.workerDone[i] <- true\n\t\t<-fdb.workerDone[i]\n\t}\n\treturn true\n}", "func (g *Glob) Finished() bool {\n\treturn g.Empty()\n}", "func (s *commonFTSSimulator) Finished() bool {\n\treturn s.madeDocuments >= s.maxDocuments\n}", "func (op *UpdateReplicationOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (op *CreateJobOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (j *Job) done() { j.isDone <- true }", "func (p *ManagedClustersRunCommandPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *DeploymentsStartJFRPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (m *Master) Done() chan struct{} {\n\treturn m.done\n}", "func (op *StopReplicationOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (p *NotebookWorkspacesStartPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *DeploymentsRestartPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (op *DeleteJobOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (op *CreateReplicationOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (turingMachine *TuringMachine) HasFinished() bool {\n return turingMachine.hasFinished\n}", "func (c *Coordinator) Done() bool {\n\tc.mapLock.Lock()\n\tc.reduceLock.Lock()\n\tret := c.mapDoneTasks == len(c.mapTasks) &&\n\t\tc.reduceDoneTasks == len(c.reduceTasks)\n\tc.reduceLock.Unlock()\n\tc.mapLock.Unlock()\n\treturn ret\n}", "func (p *ManagedClustersStartPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (c *Coordinator) Done() bool {\n\tc.jobLock.Lock()\n\tdefer c.jobLock.Unlock()\n\n\treturn c.phase == CoordinatorPhaseDone\n}", "func (p *CassandraClustersUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func jobCompleted(job JobType) bool {\n\t// Call numerxData server to check the status of this job\n\t// return true if we get:\n\t// \t\t[“step”=”metaindexstatus”, “status”=”success”]\n\t//\tor [“step”=“eventindexstatus”, “status” = “success”]\n\t/*\n\t\t[\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"metaindexstatus\",\"Status\":\"success\",\"Timestamp\":1465589455508,\"Notes\":\"\"},\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"parsedmeta\",\"Status\":\"success\",\"Timestamp\":1465588843502,\"Notes\":\"\"},\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"rawmeta\",\"Status\":\"success\",\"Timestamp\":1465588543502,\"Notes\":\"\"}\n\t\t]\n\t*/\n\t// uri string, resource string, params map[string]string\n\tvar params map[string]string = make(map[string]string)\n\tparams[\"id\"] = job.JobId\n\trequest, err := fileUploadStatusRequest(baseUrl, \"/status\", params)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false // let the caller func to handle retries\n\t}\n\n\tif verbose {\n\t\tlog.Println(\"RQ URL: \", request.URL)\n\t\tlog.Println(\"RQ Headers: \", request.Header)\n\t\tlog.Println(\"RQ Body: \", request)\n\t}\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false // let the caller func to handle retries\n\t} else {\n\t\t/* JSON\n\t\t[\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"metaindexstatus\",\"Status\":\"success\",\"Timestamp\":1465589455508,\"Notes\":\"\"},\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"parsedmeta\",\"Status\":\"success\",\"Timestamp\":1465588843502,\"Notes\":\"\"},\n\t\t\t{\"ID\":\"0.0.LqO~iOvJV3sdUOd8\",\"Step\":\"rawmeta\",\"Status\":\"success\",\"Timestamp\":1465588543502,\"Notes\":\"\"}\n\t\t]\n\t\t*/\n\t\tdefer resp.Body.Close()\n\n\t\tvar bodyContent []byte\n\t\tif verbose {\n\t\t\tlog.Println(\"Status RS Status: \", resp.StatusCode)\n\t\t\tlog.Println(\"Status RS Headers: \", resp.Header)\n\t\t}\n\n\t\tbodyContent, err := ioutil.ReadAll(resp.Body)\n\n\t\tif verbose {\n\t\t\tlog.Println(\"Status RS Content: error? :\", err)\n\t\t\tlog.Println(\"Status RS Content: body: bytes: \", bodyContent)\n\t\t\tlog.Println(\"Status RS Content: body: string: \", string(bodyContent))\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\t// Check the step's status\n\t\t\tstatus, err := getStatusResponse(bodyContent)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error %v while checking status for %v, file: %v \\n\", err, job.JobId, job.Filename)\n\t\t\t\treturn false // let the caller func to handle retries\n\t\t\t} else {\n\t\t\t\tswitch requestType {\n\t\t\t\tcase RQ_Viewership:\n\t\t\t\t\tfor _, entry := range status {\n\t\t\t\t\t\tswitch entry.Step {\n\t\t\t\t\t\tcase string(IndexEventData): // \"eventindexstatus\":\n\t\t\t\t\t\t\tswitch entry.Status {\n\t\t\t\t\t\t\tcase string(Success): // \"success\":\n\t\t\t\t\t\t\t\tif verbose {\n\t\t\t\t\t\t\t\t\tlog.Printf(\"Complete for: %s, file: %s\\n\", job.JobId, job.Filename)\n\t\t\t\t\t\t\t\t\tlog.Println(\"Current state: \", status)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\tcase string(Failure): // \"failure\":\n\t\t\t\t\t\t\t\tfailedJobsChan <- job\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase string(ParsedEventData), string(RawEventData):\n\t\t\t\t\t\t\tif entry.Status == string(Failure) {\n\t\t\t\t\t\t\t\tfailedJobsChan <- job\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif verbose {\n\t\t\t\t\t\tlog.Printf(\"Not yet: %s, file: %s\\n\", job.JobId, job.Filename)\n\t\t\t\t\t\tlog.Println(\"Current state: \", status)\n\t\t\t\t\t}\n\n\t\t\t\t//\t(actually the new struct with file-name, id, and retry-number)\n\t\t\t\tcase RQ_MetaBilling, RQ_MetaProgram, RQ_MetaChanMap, RQ_MetaEventMap:\n\t\t\t\t\tfor _, entry := range status {\n\t\t\t\t\t\tswitch entry.Step {\n\t\t\t\t\t\tcase string(IndexMetaData): // \"metaindexstatus\":\n\t\t\t\t\t\t\tswitch entry.Status {\n\t\t\t\t\t\t\tcase string(Success): // \"success\":\n\t\t\t\t\t\t\t\tif verbose {\n\t\t\t\t\t\t\t\t\tlog.Printf(\"Complete for: %s, file: %s\\n\", job.JobId, job.Filename)\n\t\t\t\t\t\t\t\t\tlog.Println(\"Current state: \", status)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\tcase string(Failure): // \"failure\":\n\t\t\t\t\t\t\t\tfailedJobsChan <- job\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase string(ParsedMetaData), string(RawMetaData):\n\t\t\t\t\t\t\tif entry.Status == string(Failure) {\n\t\t\t\t\t\t\t\tfailedJobsChan <- job\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif verbose {\n\t\t\t\t\t\tlog.Printf(\"Not yet: %s, file: %s\\n\", job.JobId, job.Filename)\n\t\t\t\t\t\tlog.Println(\"Current state: \", status)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"Error Status %v while checking status for %v, file: %s \\n\", err, job.JobId, job.Filename)\n\t\t\tfailedJobsChan <- job\n\t\t\tif verbose {\n\t\t\t\tlog.Println(\"Error Status %v while checking status for %v, file: %s \\n\", err, job.JobId, job.Filename)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (p *NotebookWorkspacesClientStartPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraDataCentersUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (m *Master) finishTask(args *Args) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif m.status == MapStage {\n\t\tdelete(m.mapInProgress, args.TaskId)\n\t\tm.mapFinished++\n\t\tif m.mapFinished == len(m.mapTasks) {\n\t\t\tm.status = ReduceStage\n\t\t}\n\t\tfmt.Println(\"finished 1 map task\")\n\t} else if m.status == ReduceStage {\n\t\tdelete(m.reduceInProgress, args.TaskId)\n\t\tm.reduceFinished++\n\t\tif m.reduceFinished == m.reduceTasks {\n\t\t\tm.status = FinishedStage\n\t\t}\n\t\tm.deleteIntermediates(args.TaskId)\n\t\tfmt.Println(\"finished 1 reduce task\")\n\t}\n}", "func checkForJobSuccess(org, repo string, targetBuildNum int, client *circleci.Client) (err error) {\n\tcheckAttempts := 0\n\tcheckLimit := 60\n\tcheckInterval := 5 * time.Second\n\tlogger.Infof(\"Polling CircleCI for status of build: %d\", targetBuildNum)\n\tfor {\n\t\tvar build *circleci.Build\n\t\tif build, err = client.GetBuild(org, repo, targetBuildNum); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif build.Status == \"success\" {\n\t\t\tlogger.Infof(\"Detected success of CircleCI build: %d\", targetBuildNum)\n\t\t\tbreak\n\t\t} else if build.Status == \"failed\" {\n\t\t\treturn fmt.Errorf(\"CircleCI job: %d has failed\", targetBuildNum)\n\t\t}\n\t\tcheckAttempts++\n\t\tif checkAttempts == checkLimit {\n\t\t\treturn fmt.Errorf(\"Unable to verify CircleCI job was a success: https://circleci.com/gh/%s/%s/%d\",\n\t\t\t\torg, repo, targetBuildNum)\n\t\t}\n\t\ttime.Sleep(checkInterval)\n\t}\n\treturn\n}", "func Check(conf *config.Config, queue *Queue, running *Running, manager manager.Driver) error {\n\tlog.Println(\"Checking for a job to run\")\n\tlog.Println(\"Queue: \", *queue)\n\trunning.Watch(&manager)\n\tnext := queue.Pop(running, conf.Server.MaxBuilds)\n\tif next != nil {\n\t\tlog.Println(\"About to build: \", next.Project, next.Branch)\n\t\tfor i := range conf.Projects {\n\t\t\tif next.Project == conf.Projects[i].Name {\n\t\t\t\tshouldDeploy := false\n\t\t\t\tlog.Println(\"Found a job to run\")\n\t\t\t\tfor j := range conf.Projects[i].DeployBranches {\n\t\t\t\t\tif next.Branch == conf.Projects[i].DeployBranches[j] {\n\t\t\t\t\t\tlog.Println(\"Will Deploy\")\n\t\t\t\t\t\tshouldDeploy = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconfPath := conf.Projects[i].MaestroConfPath\n\t\t\t\tlog.Println(\"Running build\")\n\t\t\t\trunErr := manager.Run(\n\t\t\t\t\tfmt.Sprintf(\"%s-%s-%s\", next.Project, next.Branch, next.CurrCommit),\n\t\t\t\t\tconfDir(confPath),\n\t\t\t\t\tconfDir(confPath),\n\t\t\t\t\t[]string{\n\t\t\t\t\t\t\"maestro\",\n\t\t\t\t\t\tfmt.Sprintf(\"--branch=%s\", next.Branch),\n\t\t\t\t\t\tfmt.Sprintf(\"--deploy=%v\", shouldDeploy),\n\t\t\t\t\t\tfmt.Sprintf(\"--prev-commit=%s\", next.PrevCommit),\n\t\t\t\t\t\tfmt.Sprintf(\"--curr-commit=%s\", next.CurrCommit),\n\t\t\t\t\t\tfmt.Sprintf(\"--config=%s\", confPath),\n\t\t\t\t\t\tfmt.Sprintf(\"--clone-path=%s\", conf.Server.WorkspaceDir),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\treturn runErr\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *CustomDomainsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (Mr *Master) ReceiveFinish(filenames []string) {\n\tlog.Println(\"outside of lock\")\n\tMr.Timer.Lock()\n\tlog.Println(\"in lock\")\n\tfor _, filename := range filenames {\n\t\tMr.FileCondition[filename] = 2\n\t}\n\tMr.Timer.Unlock()\n}", "func (c *Coordinator) Done() bool {\n\treturn c.isDone.Load().(bool)\n}", "func (mr *Master) schedule(phase jobPhase) {\n\tvar ntasks int\n\tvar nios int // number of inputs (for reduce) or outputs (for map)\n\tswitch phase {\n\tcase mapPhase:\n\t\tntasks = len(mr.files)\n\t\tnios = mr.nReduce\n\tcase reducePhase:\n\t\tntasks = mr.nReduce\n\t\tnios = len(mr.files)\n\t}\n\n\tfmt.Printf(\"Schedule: %v %v tasks (%d I/Os)\\n\", ntasks, phase, nios)\n\n\t// them have been completed successfully should the function return.\n\t// Remember that workers may fail, and that any given worker may finish\n\t// multiple tasks.\t// All ntasks tasks have to be scheduled on workers, and only once all of\n\n\t//\n\t// TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO\n\t// mycode\n\tvar wg sync.WaitGroup\n\twg.Add(ntasks)\n\ti := int32(-1)\n\n\tif phase == mapPhase {\n\t\tfor {\n\t\t\tvar worker string\n\t\t\tworker = <-mr.registerChannel\n\t\t\tif worker == \"done\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\tt := atomic.AddInt32(&i, 1)\n\t\t\t\t\tfmt.Printf(\"map worker = %s, t = %d\\n\", worker, t)\n\t\t\t\t\tif t > int32(ntasks) {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif t == int32(ntasks) {\n\t\t\t\t\t\tmr.registerChannel <- \"done\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tfile := mr.files[t]\n\t\t\t\t\targs := DoTaskArgs{\"test\", file, phase, int(t), nios}\n\t\t\t\t\t//rpc worker possible have error\n\t\t\t\t\tif !call(worker, \"Worker.DoTask\", args, new(struct{})) {\n\t\t\t\t\t\tfmt.Printf(\"mapworkfailed %s\\n\", worker)\n\t\t\t\t\t\tt = atomic.AddInt32(&i, -1)\n\t\t\t\t\t\t//recall after one seconds\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Printf(\"success t = %d\\n\", t)\n\t\t\t\t\t\twg.Done()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n\n\tif phase == reducePhase {\n\t\tfmt.Printf(\"workers num=%d\\n\", len(mr.workers))\n\t\tfmt.Println(\"reduce begin\")\n\t\t//new worker\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tworker := <-mr.registerChannel\n\t\t\t\tfmt.Printf(\"new worker arrived name = %s\\n\", worker)\n\t\t\t\tif worker == \"done\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tgo func() {\n\t\t\t\t\tfor {\n\t\t\t\t\t\tt := atomic.AddInt32(&i, 1)\n\t\t\t\t\t\tfmt.Printf(\"reduce new worker = %s, t = %d\\n\", worker, t)\n\t\t\t\t\t\tif t >= int32(ntasks) {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// if t == int32(ntasks) {\n\t\t\t\t\t\t// \tmr.registerChannel <- \"done\"\n\t\t\t\t\t\t// \tbreak\n\t\t\t\t\t\t// }\n\t\t\t\t\t\tfile := mr.files[t]\n\t\t\t\t\t\targs := DoTaskArgs{\"test\", file, phase, int(t), nios}\n\t\t\t\t\t\t//rpc worker possible have error\n\t\t\t\t\t\tif !call(worker, \"Worker.DoTask\", args, new(struct{})) {\n\t\t\t\t\t\t\tt = atomic.AddInt32(&i, -1)\n\t\t\t\t\t\t\t//recall after one seconds\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twg.Done()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t}()\n\t\t//use previous worker\n\t\tfor _, val := range mr.workers {\n\t\t\t// fmt.Printf(\"reduce worker=%s\\n\", val)\n\t\t\tgo func(val string) {\n\t\t\t\tfor {\n\t\t\t\t\t// fmt.Printf(\"reduce4 worker=%s\\n\", val)\n\t\t\t\t\tt := atomic.AddInt32(&i, 1)\n\t\t\t\t\tif t >= int32(ntasks) {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tfile := mr.files[t]\n\t\t\t\t\targs := DoTaskArgs{\"test\", file, phase, int(t), nios}\n\t\t\t\t\t//rpc worker possible have error\n\t\t\t\t\tif !call(val, \"Worker.DoTask\", args, new(struct{})) {\n\t\t\t\t\t\tt = atomic.AddInt32(&i, -1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\twg.Done()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(val)\n\t\t}\n\n\t\twg.Wait()\n\t\tmr.registerChannel <- \"done\"\n\t}\n\n\tfmt.Printf(\"Schedule: %v phase done\\n\", phase)\n}", "func (m *HeavySyncMock) ResetFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.ResetMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.ResetCounter) == uint64(len(m.ResetMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.ResetMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.ResetCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.ResetFunc != nil {\n\t\treturn atomic.LoadUint64(&m.ResetCounter) > 0\n\t}\n\n\treturn true\n}", "func (p *CassandraClustersCreateUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *DatabaseAccountsOfflineRegionPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (j *Job) shouldRun() bool {\n\treturn time.Now().Unix() >= j.nextRun.Unix()\n}", "func (this *DeployLock) finish() {\n\tthis.mutex.Lock()\n\tthis.numFinished++\n\tthis.mutex.Unlock()\n}", "func (f *foreman) Start() {\n\tjobsChan := make(chan int, 100)\n\tresChan := make(chan string, 100)\n\tisCompletedChan := make(chan bool)\n\n\tfor w := 0; w < f.workers; w++ {\n\t\tgo worker(w, jobsChan, resChan)\n\t}\n\n\tfor j := 0; j < f.jobs; j++ {\n\t\tjobsChan <- j\n\t}\n\tclose(jobsChan)\n\n\tgo checkWork(f.jobs, resChan, isCompletedChan)\n\n\t<-isCompletedChan\n\tclose(resChan)\n\n\tfmt.Println(\"all jobs are completed\")\n}", "func (p *CassandraClustersStartPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (m *Master) TaskCompleted(args *Message, reply *NoArgs) error {\n\tswitch args.TaskType {\n\n\tcase \"map\":\n\t\t// fmt.Println(\"before map finish lock\")\n\t\tm.mu.Lock()\n\t\t// set job status to done\n\t\tm.mapState[args.TaskNum].Value = \"completed\"\n\t\t// add the file created to the list of reduceJobs\n\t\tfor _, f := range args.Filenames {\n\t\t\tn := findN(f)\n\t\t\tm.reduceJobs[n] = append(m.reduceJobs[n], f)\n\t\t}\n\n\t\t// check: by finishing this map task\n\t\t// are all map tasks compeleted\n\t\tisCompleted := true\n\t\tfor _, kv := range m.mapState {\n\t\t\tif kv.Value != \"completed\" {\n\t\t\t\tisCompleted = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tm.mapDone = isCompleted\n\t\tm.mu.Unlock()\n\t\t// fmt.Println(\"after map finish lock\")\n\tcase \"reduce\":\n\n\t\tm.mu.Lock()\n\t\t// set job status to done\n\t\tm.reduceState[args.TaskNum] = \"completed\"\n\n\t\t// check: by finishing this reduce task\n\t\t// are all reduce tasks compeleted\n\t\tisCompleted := true\n\t\tfor _, value := range m.reduceState {\n\t\t\tif value != \"completed\" {\n\t\t\t\tisCompleted = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif isCompleted {\n\t\t\tm.removeIntermediateFiles()\n\t\t}\n\t\tm.reduceDone = isCompleted\n\t\tm.mu.Unlock()\n\t}\n\treturn nil\n}", "func (p *DatabaseAccountsOnlineRegionPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *DeploymentsGenerateThreadDumpPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (i *UploadShrinker) Done() bool {\n\treturn i.chunk > i.total\n}", "func (p *CassandraClustersClientUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraDataCentersClientUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *CassandraClustersInvokeCommandPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (cs cmdStatus) isDone() bool {\n\treturn cs&(1<<12 /*busy*/) == 0\n}", "func (m *Master) Run() int {\n\tm.Build()\n\treturn m.Start()\n}", "func (p *GremlinResourcesCreateUpdateGremlinDatabasePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *DatabaseAccountsRegenerateKeyPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (t *Tileset) CheckJobStatus() error {\n\tfmt.Println(\"Awaiting job completion. This may take some time...\")\n\tfor {\n\t\tstatusResponse := &StatusResponse{}\n\t\tres, err := t.base.SimpleGET(t.postURL() + \"/status\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tjson.Unmarshal(res, statusResponse)\n\t\tif statusResponse.Status == \"failed\" {\n\t\t\tfmt.Println(\"Job failed\")\n\t\t\treturn nil\n\t\t}\n\t\tif statusResponse.Status == \"success\" {\n\t\t\tfmt.Println(\"Job complete\")\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Println(statusResponse.Status)\n\t\ttime.Sleep(5 * time.Second)\n\n\t}\n\n}", "func (p *DomainsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (op *DeleteReplicationOperation) Done() bool {\n\treturn op.lro.Done()\n}", "func (p *DatabaseAccountsUpdatePoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (p *NotebookWorkspacesRegenerateAuthTokenPoller) Done() bool {\n\treturn p.pt.Done()\n}", "func (s *JobStatus) Done() bool {\n\treturn s.State == Done\n}", "func (s *JobStatus) Done() bool {\n\treturn s.State == Done\n}" ]
[ "0.7823017", "0.76430684", "0.761561", "0.74849814", "0.7421957", "0.7361364", "0.73418754", "0.7336742", "0.730617", "0.7304654", "0.72612065", "0.72489536", "0.7237784", "0.7212441", "0.7203896", "0.71987164", "0.7190169", "0.7184905", "0.71776134", "0.71732163", "0.71365404", "0.7119928", "0.70886856", "0.7014535", "0.700787", "0.6935697", "0.6915297", "0.6886913", "0.6850366", "0.6820809", "0.6797319", "0.6615807", "0.66049135", "0.6413519", "0.6321555", "0.63074845", "0.62046635", "0.60425", "0.60135627", "0.6013147", "0.60077953", "0.59884506", "0.59746677", "0.59709364", "0.5965993", "0.59549874", "0.5902606", "0.58900243", "0.58851427", "0.5883504", "0.58726805", "0.5844602", "0.58341813", "0.5823982", "0.58160275", "0.5807777", "0.5787979", "0.57607746", "0.57511675", "0.5737547", "0.57313913", "0.5723525", "0.5698703", "0.56944716", "0.5683076", "0.56825334", "0.5646594", "0.5646251", "0.56335133", "0.56185365", "0.5617544", "0.5615362", "0.5613964", "0.56096905", "0.5606886", "0.55548954", "0.5554755", "0.5548026", "0.5546387", "0.5527664", "0.55197984", "0.5511037", "0.55082124", "0.5499017", "0.54964924", "0.5490686", "0.54865533", "0.54849565", "0.5483579", "0.54783237", "0.54665", "0.5466406", "0.5465664", "0.5465317", "0.54646415", "0.54610854", "0.5459905", "0.54563147", "0.5453023", "0.5453023" ]
0.6901854
27