repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
xyproto/permissions2
userstate.go
SetToken
func (state *UserState) SetToken(username, token string, expire time.Duration) { state.users.SetExpire(username, "token", token, expire) }
go
func (state *UserState) SetToken(username, token string, expire time.Duration) { state.users.SetExpire(username, "token", token, expire) }
[ "func", "(", "state", "*", "UserState", ")", "SetToken", "(", "username", ",", "token", "string", ",", "expire", "time", ".", "Duration", ")", "{", "state", ".", "users", ".", "SetExpire", "(", "username", ",", "\"", "\"", ",", "token", ",", "expire", ...
// SetToken sets a token for a user, for a given expiry time
[ "SetToken", "sets", "a", "token", "for", "a", "user", "for", "a", "given", "expiry", "time" ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L484-L486
train
xyproto/permissions2
userstate.go
GetToken
func (state *UserState) GetToken(username string) (string, error) { return state.users.Get(username, "token") }
go
func (state *UserState) GetToken(username string) (string, error) { return state.users.Get(username, "token") }
[ "func", "(", "state", "*", "UserState", ")", "GetToken", "(", "username", "string", ")", "(", "string", ",", "error", ")", "{", "return", "state", ".", "users", ".", "Get", "(", "username", ",", "\"", "\"", ")", "\n", "}" ]
// GetToken retrieves the token for a user
[ "GetToken", "retrieves", "the", "token", "for", "a", "user" ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L489-L491
train
xyproto/permissions2
userstate.go
SetPassword
func (state *UserState) SetPassword(username, password string) { state.users.Set(username, "password", state.HashPassword(username, password)) }
go
func (state *UserState) SetPassword(username, password string) { state.users.Set(username, "password", state.HashPassword(username, password)) }
[ "func", "(", "state", "*", "UserState", ")", "SetPassword", "(", "username", ",", "password", "string", ")", "{", "state", ".", "users", ".", "Set", "(", "username", ",", "\"", "\"", ",", "state", ".", "HashPassword", "(", "username", ",", "password", ...
// SetPassword sets the password for a user. The given password string will be hashed. // No validation or check of the given password is performed.
[ "SetPassword", "sets", "the", "password", "for", "a", "user", ".", "The", "given", "password", "string", "will", "be", "hashed", ".", "No", "validation", "or", "check", "of", "the", "given", "password", "is", "performed", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L500-L502
train
xyproto/permissions2
userstate.go
AddUser
func (state *UserState) AddUser(username, password, email string) { passwordHash := state.HashPassword(username, password) state.addUserUnchecked(username, passwordHash, email) }
go
func (state *UserState) AddUser(username, password, email string) { passwordHash := state.HashPassword(username, password) state.addUserUnchecked(username, passwordHash, email) }
[ "func", "(", "state", "*", "UserState", ")", "AddUser", "(", "username", ",", "password", ",", "email", "string", ")", "{", "passwordHash", ":=", "state", ".", "HashPassword", "(", "username", ",", "password", ")", "\n", "state", ".", "addUserUnchecked", "...
// Creates a user and hashes the password, does not check for rights. // The given data must be valid.
[ "Creates", "a", "user", "and", "hashes", "the", "password", "does", "not", "check", "for", "rights", ".", "The", "given", "data", "must", "be", "valid", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L522-L525
train
xyproto/permissions2
userstate.go
Login
func (state *UserState) Login(w http.ResponseWriter, username string) error { state.SetLoggedIn(username) return state.SetUsernameCookie(w, username) }
go
func (state *UserState) Login(w http.ResponseWriter, username string) error { state.SetLoggedIn(username) return state.SetUsernameCookie(w, username) }
[ "func", "(", "state", "*", "UserState", ")", "Login", "(", "w", "http", ".", "ResponseWriter", ",", "username", "string", ")", "error", "{", "state", ".", "SetLoggedIn", "(", "username", ")", "\n", "return", "state", ".", "SetUsernameCookie", "(", "w", "...
// Convenience function for logging a user in and storing the username in a cookie. // Returns an error if the cookie could not be set.
[ "Convenience", "function", "for", "logging", "a", "user", "in", "and", "storing", "the", "username", "in", "a", "cookie", ".", "Returns", "an", "error", "if", "the", "cookie", "could", "not", "be", "set", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L539-L542
train
xyproto/permissions2
userstate.go
CorrectPassword
func (state *UserState) CorrectPassword(username, password string) bool { if !state.HasUser(username) { return false } // Retrieve the stored password hash hash := state.storedHash(username) if len(hash) == 0 { return false } // Check the password with the right password algorithm switch state.passwordAlgorithm { case "sha256": return correctSha256(hash, state.cookieSecret, username, password) case "bcrypt": return correctBcrypt(hash, password) case "bcrypt+": // for backwards compatibility with sha256 if isSha256(hash) && correctSha256(hash, state.cookieSecret, username, password) { return true } return correctBcrypt(hash, password) } return false }
go
func (state *UserState) CorrectPassword(username, password string) bool { if !state.HasUser(username) { return false } // Retrieve the stored password hash hash := state.storedHash(username) if len(hash) == 0 { return false } // Check the password with the right password algorithm switch state.passwordAlgorithm { case "sha256": return correctSha256(hash, state.cookieSecret, username, password) case "bcrypt": return correctBcrypt(hash, password) case "bcrypt+": // for backwards compatibility with sha256 if isSha256(hash) && correctSha256(hash, state.cookieSecret, username, password) { return true } return correctBcrypt(hash, password) } return false }
[ "func", "(", "state", "*", "UserState", ")", "CorrectPassword", "(", "username", ",", "password", "string", ")", "bool", "{", "if", "!", "state", ".", "HasUser", "(", "username", ")", "{", "return", "false", "\n", "}", "\n\n", "// Retrieve the stored passwor...
// CorrectPassword checks if a password is correct. username is needed because it is part of the hash.
[ "CorrectPassword", "checks", "if", "a", "password", "is", "correct", ".", "username", "is", "needed", "because", "it", "is", "part", "of", "the", "hash", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L629-L654
train
xyproto/permissions2
userstate.go
AlreadyHasConfirmationCode
func (state *UserState) AlreadyHasConfirmationCode(confirmationCode string) bool { unconfirmedUsernames, err := state.AllUnconfirmedUsernames() if err != nil { return false } for _, aUsername := range unconfirmedUsernames { aConfirmationCode, err := state.ConfirmationCode(aUsername) if err != nil { // If the confirmation code can not be found, that's okay too return false } if confirmationCode == aConfirmationCode { // Found it return true } } return false }
go
func (state *UserState) AlreadyHasConfirmationCode(confirmationCode string) bool { unconfirmedUsernames, err := state.AllUnconfirmedUsernames() if err != nil { return false } for _, aUsername := range unconfirmedUsernames { aConfirmationCode, err := state.ConfirmationCode(aUsername) if err != nil { // If the confirmation code can not be found, that's okay too return false } if confirmationCode == aConfirmationCode { // Found it return true } } return false }
[ "func", "(", "state", "*", "UserState", ")", "AlreadyHasConfirmationCode", "(", "confirmationCode", "string", ")", "bool", "{", "unconfirmedUsernames", ",", "err", ":=", "state", ".", "AllUnconfirmedUsernames", "(", ")", "\n", "if", "err", "!=", "nil", "{", "r...
// AlreadyHasConfirmationCode runs through all confirmation codes of all unconfirmed // users and checks if this confirmationCode is already in use.
[ "AlreadyHasConfirmationCode", "runs", "through", "all", "confirmation", "codes", "of", "all", "unconfirmed", "users", "and", "checks", "if", "this", "confirmationCode", "is", "already", "in", "use", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L658-L675
train
xyproto/permissions2
userstate.go
Confirm
func (state *UserState) Confirm(username string) { // Remove from the list of unconfirmed usernames state.RemoveUnconfirmed(username) // Mark user as confirmed state.MarkConfirmed(username) }
go
func (state *UserState) Confirm(username string) { // Remove from the list of unconfirmed usernames state.RemoveUnconfirmed(username) // Mark user as confirmed state.MarkConfirmed(username) }
[ "func", "(", "state", "*", "UserState", ")", "Confirm", "(", "username", "string", ")", "{", "// Remove from the list of unconfirmed usernames", "state", ".", "RemoveUnconfirmed", "(", "username", ")", "\n\n", "// Mark user as confirmed", "state", ".", "MarkConfirmed", ...
// Confirm removes the username from the list of unconfirmed users and mark the user as confirmed.
[ "Confirm", "removes", "the", "username", "from", "the", "list", "of", "unconfirmed", "users", "and", "mark", "the", "user", "as", "confirmed", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L712-L718
train
xyproto/permissions2
userstate.go
Creator
func (state *UserState) Creator() pinterface.ICreator { return simpleredis.NewCreator(state.pool, state.dbindex) }
go
func (state *UserState) Creator() pinterface.ICreator { return simpleredis.NewCreator(state.pool, state.dbindex) }
[ "func", "(", "state", "*", "UserState", ")", "Creator", "(", ")", "pinterface", ".", "ICreator", "{", "return", "simpleredis", ".", "NewCreator", "(", "state", ".", "pool", ",", "state", ".", "dbindex", ")", "\n", "}" ]
// Creator returns a struct for creating data structures with
[ "Creator", "returns", "a", "struct", "for", "creating", "data", "structures", "with" ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L773-L775
train
xyproto/permissions2
userstate.go
Properties
func (state *UserState) Properties(username string) []string { props, err := state.users.Keys(username) if err != nil { return []string{} } return props }
go
func (state *UserState) Properties(username string) []string { props, err := state.users.Keys(username) if err != nil { return []string{} } return props }
[ "func", "(", "state", "*", "UserState", ")", "Properties", "(", "username", "string", ")", "[", "]", "string", "{", "props", ",", "err", ":=", "state", ".", "users", ".", "Keys", "(", "username", ")", "\n", "if", "err", "!=", "nil", "{", "return", ...
// Properties returns a list of user properties. // Returns an empty list if the user has no properties, or if there are errors.
[ "Properties", "returns", "a", "list", "of", "user", "properties", ".", "Returns", "an", "empty", "list", "if", "the", "user", "has", "no", "properties", "or", "if", "there", "are", "errors", "." ]
f47b0751729e767ee4c9dcc64a00e4720b95c8e0
https://github.com/xyproto/permissions2/blob/f47b0751729e767ee4c9dcc64a00e4720b95c8e0/userstate.go#L779-L785
train
denverdino/aliyungo
cms/client.go
NewCMSClient
func NewCMSClient(accessKeyId, accessKeySecret string) *CMSClient { endpoint := os.Getenv("CMS_ENDPOINT") if endpoint == "" { endpoint = CMSDefaultEndpoint } return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) }
go
func NewCMSClient(accessKeyId, accessKeySecret string) *CMSClient { endpoint := os.Getenv("CMS_ENDPOINT") if endpoint == "" { endpoint = CMSDefaultEndpoint } return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) }
[ "func", "NewCMSClient", "(", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "CMSClient", "{", "endpoint", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "endpoint", "==", "\"", "\"", "{", "endpoint", "=", "CMSDefaultEndpoint", "\n...
// NewClient creates a new instance of CMS client
[ "NewClient", "creates", "a", "new", "instance", "of", "CMS", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cms/client.go#L77-L83
train
denverdino/aliyungo
kms/client.go
NewClient
func NewClient(accessKeyId, accessKeySecret string) *Client { endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) }
go
func NewClient(accessKeyId, accessKeySecret string) *Client { endpoint := os.Getenv("KMS_ENDPOINT") if endpoint == "" { endpoint = KMSDefaultEndpoint } return NewClientWithEndpoint(endpoint, accessKeyId, accessKeySecret) }
[ "func", "NewClient", "(", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "Client", "{", "endpoint", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "endpoint", "==", "\"", "\"", "{", "endpoint", "=", "KMSDefaultEndpoint", "\n", "...
// NewClient creates a new instance of KMS client
[ "NewClient", "creates", "a", "new", "instance", "of", "KMS", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/kms/client.go#L21-L27
train
denverdino/aliyungo
ess/configuration.go
DeactivateScalingConfiguration
func (client *Client) DeactivateScalingConfiguration(args *DeactivateScalingConfigurationArgs) (resp *DeactivateScalingConfigurationResponse, err error) { response := DeactivateScalingConfigurationResponse{} err = client.InvokeByFlattenMethod("DeactivateScalingConfiguration", args, &response) if err != nil { return nil, err } return &response, nil }
go
func (client *Client) DeactivateScalingConfiguration(args *DeactivateScalingConfigurationArgs) (resp *DeactivateScalingConfigurationResponse, err error) { response := DeactivateScalingConfigurationResponse{} err = client.InvokeByFlattenMethod("DeactivateScalingConfiguration", args, &response) if err != nil { return nil, err } return &response, nil }
[ "func", "(", "client", "*", "Client", ")", "DeactivateScalingConfiguration", "(", "args", "*", "DeactivateScalingConfigurationArgs", ")", "(", "resp", "*", "DeactivateScalingConfigurationResponse", ",", "err", "error", ")", "{", "response", ":=", "DeactivateScalingConfi...
// DeactivateScalingConfiguration deactivate scaling configuration //
[ "DeactivateScalingConfiguration", "deactivate", "scaling", "configuration" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ess/configuration.go#L161-L169
train
denverdino/aliyungo
slb/servers.go
SetBackendServers
func (client *Client) SetBackendServers(loadBalancerId string, backendServers []BackendServerType) (result []BackendServerType, err error) { bytes, _ := json.Marshal(backendServers) args := &SetBackendServersArgs{ LoadBalancerId: loadBalancerId, BackendServers: string(bytes), } response := &SetBackendServersResponse{} err = client.Invoke("SetBackendServers", args, response) if err != nil { return nil, err } return response.BackendServers.BackendServer, err }
go
func (client *Client) SetBackendServers(loadBalancerId string, backendServers []BackendServerType) (result []BackendServerType, err error) { bytes, _ := json.Marshal(backendServers) args := &SetBackendServersArgs{ LoadBalancerId: loadBalancerId, BackendServers: string(bytes), } response := &SetBackendServersResponse{} err = client.Invoke("SetBackendServers", args, response) if err != nil { return nil, err } return response.BackendServers.BackendServer, err }
[ "func", "(", "client", "*", "Client", ")", "SetBackendServers", "(", "loadBalancerId", "string", ",", "backendServers", "[", "]", "BackendServerType", ")", "(", "result", "[", "]", "BackendServerType", ",", "err", "error", ")", "{", "bytes", ",", "_", ":=", ...
// SetBackendServers set weight of backend servers
[ "SetBackendServers", "set", "weight", "of", "backend", "servers" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/slb/servers.go#L27-L41
train
denverdino/aliyungo
util/encoding.go
ConvertToQueryValues
func ConvertToQueryValues(ifc interface{}) url.Values { values := url.Values{} SetQueryValues(ifc, &values) return values }
go
func ConvertToQueryValues(ifc interface{}) url.Values { values := url.Values{} SetQueryValues(ifc, &values) return values }
[ "func", "ConvertToQueryValues", "(", "ifc", "interface", "{", "}", ")", "url", ".", "Values", "{", "values", ":=", "url", ".", "Values", "{", "}", "\n", "SetQueryValues", "(", "ifc", ",", "&", "values", ")", "\n", "return", "values", "\n", "}" ]
//ConvertToQueryValues converts the struct to url.Values
[ "ConvertToQueryValues", "converts", "the", "struct", "to", "url", ".", "Values" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/encoding.go#L31-L35
train
denverdino/aliyungo
ecs/router_interface.go
WaitForRouterInterfaceAsyn
func (client *Client) WaitForRouterInterfaceAsyn(regionId common.Region, interfaceId string, status InterfaceStatus, timeout int) error { if timeout <= 0 { timeout = InstanceDefaultTimeout } for { interfaces, err := client.DescribeRouterInterfaces(&DescribeRouterInterfacesArgs{ RegionId: regionId, Filter: []Filter{{Key: "RouterInterfaceId", Value: []string{interfaceId}}}, }) if err != nil { return err } else if interfaces != nil && InterfaceStatus(interfaces.RouterInterfaceSet.RouterInterfaceType[0].Status) == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForRouterInterfaceAsyn(regionId common.Region, interfaceId string, status InterfaceStatus, timeout int) error { if timeout <= 0 { timeout = InstanceDefaultTimeout } for { interfaces, err := client.DescribeRouterInterfaces(&DescribeRouterInterfacesArgs{ RegionId: regionId, Filter: []Filter{{Key: "RouterInterfaceId", Value: []string{interfaceId}}}, }) if err != nil { return err } else if interfaces != nil && InterfaceStatus(interfaces.RouterInterfaceSet.RouterInterfaceType[0].Status) == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForRouterInterfaceAsyn", "(", "regionId", "common", ".", "Region", ",", "interfaceId", "string", ",", "status", "InterfaceStatus", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "tim...
// WaitForRouterInterface waits for router interface to given status
[ "WaitForRouterInterface", "waits", "for", "router", "interface", "to", "given", "status" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/router_interface.go#L234-L257
train
denverdino/aliyungo
slb/zones.go
DescribeZones
func (client *Client) DescribeZones(regionId common.Region) (zones []ZoneType, err error) { response, err := client.DescribeZonesWithRaw(regionId) if err == nil { return response.Zones.Zone, nil } return []ZoneType{}, err }
go
func (client *Client) DescribeZones(regionId common.Region) (zones []ZoneType, err error) { response, err := client.DescribeZonesWithRaw(regionId) if err == nil { return response.Zones.Zone, nil } return []ZoneType{}, err }
[ "func", "(", "client", "*", "Client", ")", "DescribeZones", "(", "regionId", "common", ".", "Region", ")", "(", "zones", "[", "]", "ZoneType", ",", "err", "error", ")", "{", "response", ",", "err", ":=", "client", ".", "DescribeZonesWithRaw", "(", "regio...
// DescribeZones describes zones
[ "DescribeZones", "describes", "zones" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/slb/zones.go#L29-L36
train
denverdino/aliyungo
rds/instances.go
CreateOrder
func (client *Client) CreateOrder(args *CreateOrderArgs) (resp CreateOrderResponse, err error) { response := CreateOrderResponse{} err = client.Invoke("CreateOrder", args, &response) return response, err }
go
func (client *Client) CreateOrder(args *CreateOrderArgs) (resp CreateOrderResponse, err error) { response := CreateOrderResponse{} err = client.Invoke("CreateOrder", args, &response) return response, err }
[ "func", "(", "client", "*", "Client", ")", "CreateOrder", "(", "args", "*", "CreateOrderArgs", ")", "(", "resp", "CreateOrderResponse", ",", "err", "error", ")", "{", "response", ":=", "CreateOrderResponse", "{", "}", "\n", "err", "=", "client", ".", "Invo...
// CreateOrder create db instance order
[ "CreateOrder", "create", "db", "instance", "order" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/rds/instances.go#L208-L212
train
denverdino/aliyungo
cs/clusters.go
ResizeKubernetes
func (client *Client) ResizeKubernetes(clusterID string, args *KubernetesCreationArgs) error { return client.Invoke("", http.MethodPut, "/clusters/"+clusterID, nil, args, nil) }
go
func (client *Client) ResizeKubernetes(clusterID string, args *KubernetesCreationArgs) error { return client.Invoke("", http.MethodPut, "/clusters/"+clusterID, nil, args, nil) }
[ "func", "(", "client", "*", "Client", ")", "ResizeKubernetes", "(", "clusterID", "string", ",", "args", "*", "KubernetesCreationArgs", ")", "error", "{", "return", "client", ".", "Invoke", "(", "\"", "\"", ",", "http", ".", "MethodPut", ",", "\"", "\"", ...
// deprecated // use ResizeKubernetesCluster instead
[ "deprecated", "use", "ResizeKubernetesCluster", "instead" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cs/clusters.go#L410-L412
train
denverdino/aliyungo
cs/clusters.go
WaitForClusterAsyn
func (client *Client) WaitForClusterAsyn(clusterId string, status ClusterState, timeout int) error { if timeout <= 0 { timeout = ClusterDefaultTimeout } // Sleep 20 second to check cluster creating or failed sleep := math.Min(float64(timeout), float64(DefaultPreCheckSleepTime)) time.Sleep(time.Duration(sleep) * time.Second) cluster, err := client.DescribeCluster(clusterId) if err != nil { return err } else if cluster.State == Failed { return fmt.Errorf("Waitting for cluster %s %s failed. Looking the specified reason in the web console.", clusterId, status) } else if cluster.State == status { //TODO return nil } // Create or Reset cluster usually cost at least 4 min, so there will sleep a long time before polling sleep = math.Min(float64(timeout), float64(DefaultPreSleepTime)) time.Sleep(time.Duration(sleep) * time.Second) for { cluster, err := client.DescribeCluster(clusterId) if err != nil { return err } else if cluster.State == Failed { return fmt.Errorf("Waitting for cluster %s %s failed. Looking the specified reason in the web console.", clusterId, status) } else if cluster.State == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForClusterAsyn(clusterId string, status ClusterState, timeout int) error { if timeout <= 0 { timeout = ClusterDefaultTimeout } // Sleep 20 second to check cluster creating or failed sleep := math.Min(float64(timeout), float64(DefaultPreCheckSleepTime)) time.Sleep(time.Duration(sleep) * time.Second) cluster, err := client.DescribeCluster(clusterId) if err != nil { return err } else if cluster.State == Failed { return fmt.Errorf("Waitting for cluster %s %s failed. Looking the specified reason in the web console.", clusterId, status) } else if cluster.State == status { //TODO return nil } // Create or Reset cluster usually cost at least 4 min, so there will sleep a long time before polling sleep = math.Min(float64(timeout), float64(DefaultPreSleepTime)) time.Sleep(time.Duration(sleep) * time.Second) for { cluster, err := client.DescribeCluster(clusterId) if err != nil { return err } else if cluster.State == Failed { return fmt.Errorf("Waitting for cluster %s %s failed. Looking the specified reason in the web console.", clusterId, status) } else if cluster.State == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForClusterAsyn", "(", "clusterId", "string", ",", "status", "ClusterState", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "ClusterDefaultTimeout", "\n", "}", "\n\n",...
// WaitForCluster waits for instance to given status // when instance.NotFound wait until timeout
[ "WaitForCluster", "waits", "for", "instance", "to", "given", "status", "when", "instance", ".", "NotFound", "wait", "until", "timeout" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cs/clusters.go#L513-L553
train
denverdino/aliyungo
ess/group.go
WaitForScalingGroup
func (client *Client) WaitForScalingGroup(regionId common.Region, groupId string, status LifecycleState, timeout int) error { if timeout <= 0 { timeout = DefaultWaitTimeout } for { sgs, _, err := client.DescribeScalingGroups(&DescribeScalingGroupsArgs{ RegionId: regionId, ScalingGroupId: []string{groupId}, }) if err != nil { return err } if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } timeout = timeout - DefaultWaitForInterval time.Sleep(DefaultWaitForInterval * time.Second) if len(sgs) < 1 { return common.GetClientErrorFromString("Not found") } if sgs[0].LifecycleState == status { break } } return nil }
go
func (client *Client) WaitForScalingGroup(regionId common.Region, groupId string, status LifecycleState, timeout int) error { if timeout <= 0 { timeout = DefaultWaitTimeout } for { sgs, _, err := client.DescribeScalingGroups(&DescribeScalingGroupsArgs{ RegionId: regionId, ScalingGroupId: []string{groupId}, }) if err != nil { return err } if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } timeout = timeout - DefaultWaitForInterval time.Sleep(DefaultWaitForInterval * time.Second) if len(sgs) < 1 { return common.GetClientErrorFromString("Not found") } if sgs[0].LifecycleState == status { break } } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForScalingGroup", "(", "regionId", "common", ".", "Region", ",", "groupId", "string", ",", "status", "LifecycleState", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "="...
// WaitForScalingGroup waits for group to given status
[ "WaitForScalingGroup", "waits", "for", "group", "to", "given", "status" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ess/group.go#L311-L340
train
denverdino/aliyungo
ecs/images.go
WaitForImageReady
func (client *Client) WaitForImageReady(regionId common.Region, imageId string, timeout int) error { if timeout <= 0 { timeout = ImageDefaultTimeout } for { args := DescribeImagesArgs{ RegionId: regionId, ImageId: imageId, Status: ImageStatusCreating, } images, _, err := client.DescribeImages(&args) if err != nil { return err } if images == nil || len(images) == 0 { args.Status = ImageStatusAvailable images, _, er := client.DescribeImages(&args) if er == nil && len(images) == 1 { break } else { return common.GetClientErrorFromString("Not found") } } if images[0].Progress == "100%" { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForImageReady(regionId common.Region, imageId string, timeout int) error { if timeout <= 0 { timeout = ImageDefaultTimeout } for { args := DescribeImagesArgs{ RegionId: regionId, ImageId: imageId, Status: ImageStatusCreating, } images, _, err := client.DescribeImages(&args) if err != nil { return err } if images == nil || len(images) == 0 { args.Status = ImageStatusAvailable images, _, er := client.DescribeImages(&args) if er == nil && len(images) == 1 { break } else { return common.GetClientErrorFromString("Not found") } } if images[0].Progress == "100%" { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForImageReady", "(", "regionId", "common", ".", "Region", ",", "imageId", "string", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "ImageDefaultTimeout", "\n", "}",...
//Wait Image ready
[ "Wait", "Image", "ready" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/images.go#L301-L335
train
denverdino/aliyungo
oss/regions.go
GetInternetEndpoint
func (r Region) GetInternetEndpoint(bucket string, secure bool) string { protocol := getProtocol(secure) if bucket == "" { return fmt.Sprintf("%s://oss.aliyuncs.com", protocol) } return fmt.Sprintf("%s://%s.%s.aliyuncs.com", protocol, bucket, string(r)) }
go
func (r Region) GetInternetEndpoint(bucket string, secure bool) string { protocol := getProtocol(secure) if bucket == "" { return fmt.Sprintf("%s://oss.aliyuncs.com", protocol) } return fmt.Sprintf("%s://%s.%s.aliyuncs.com", protocol, bucket, string(r)) }
[ "func", "(", "r", "Region", ")", "GetInternetEndpoint", "(", "bucket", "string", ",", "secure", "bool", ")", "string", "{", "protocol", ":=", "getProtocol", "(", "secure", ")", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "fmt", ".", "Sprintf",...
// GetInternetEndpoint returns internet endpoint of region
[ "GetInternetEndpoint", "returns", "internet", "endpoint", "of", "region" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/regions.go#L52-L58
train
denverdino/aliyungo
ecs/snapshots.go
WaitForSnapShotReady
func (client *Client) WaitForSnapShotReady(regionId common.Region, snapshotId string, timeout int) error { if timeout <= 0 { timeout = SnapshotDefaultTimeout } for { args := DescribeSnapshotsArgs{ RegionId: regionId, SnapshotIds: []string{snapshotId}, } snapshots, _, err := client.DescribeSnapshots(&args) if err != nil { return err } if snapshots == nil || len(snapshots) == 0 { return common.GetClientErrorFromString("Not found") } if snapshots[0].Progress == "100%" { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForSnapShotReady(regionId common.Region, snapshotId string, timeout int) error { if timeout <= 0 { timeout = SnapshotDefaultTimeout } for { args := DescribeSnapshotsArgs{ RegionId: regionId, SnapshotIds: []string{snapshotId}, } snapshots, _, err := client.DescribeSnapshots(&args) if err != nil { return err } if snapshots == nil || len(snapshots) == 0 { return common.GetClientErrorFromString("Not found") } if snapshots[0].Progress == "100%" { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForSnapShotReady", "(", "regionId", "common", ".", "Region", ",", "snapshotId", "string", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "SnapshotDefaultTimeout", "\n...
// WaitForSnapShotReady waits for snapshot ready
[ "WaitForSnapShotReady", "waits", "for", "snapshot", "ready" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/snapshots.go#L115-L142
train
denverdino/aliyungo
sls/client.go
NewClient
func NewClient(region common.Region, internal bool, accessKeyId, accessKeySecret string) *Client { endpoint := os.Getenv("SLS_ENDPOINT") if endpoint == "" { endpoint = SLSDefaultEndpoint } return NewClientWithEndpoint(endpoint, region, internal, accessKeyId, accessKeySecret) }
go
func NewClient(region common.Region, internal bool, accessKeyId, accessKeySecret string) *Client { endpoint := os.Getenv("SLS_ENDPOINT") if endpoint == "" { endpoint = SLSDefaultEndpoint } return NewClientWithEndpoint(endpoint, region, internal, accessKeyId, accessKeySecret) }
[ "func", "NewClient", "(", "region", "common", ".", "Region", ",", "internal", "bool", ",", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "Client", "{", "endpoint", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "endpoint", "=="...
// NewClient creates a new instance of ECS client
[ "NewClient", "creates", "a", "new", "instance", "of", "ECS", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/sls/client.go#L70-L76
train
denverdino/aliyungo
ros/client.go
NewClient
func NewClient(accessKeyId, accessKeySecret string) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, endpoint: ROSDefaultEndpoint, Version: ROSAPIVersion, httpClient: &http.Client{}, } }
go
func NewClient(accessKeyId, accessKeySecret string) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, endpoint: ROSDefaultEndpoint, Version: ROSAPIVersion, httpClient: &http.Client{}, } }
[ "func", "NewClient", "(", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "Client", "{", "return", "&", "Client", "{", "AccessKeyId", ":", "accessKeyId", ",", "AccessKeySecret", ":", "accessKeySecret", ",", "endpoint", ":", "ROSDefaultEndpoint", ",", ...
// NewClient creates a new instance of ROS client
[ "NewClient", "creates", "a", "new", "instance", "of", "ROS", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ros/client.go#L43-L51
train
denverdino/aliyungo
cdn/auth/sign_url.go
NewURLSigner
func NewURLSigner(authType string, privKey string) *URLSigner { return &URLSigner{ authType: authType, privKey: privKey, } }
go
func NewURLSigner(authType string, privKey string) *URLSigner { return &URLSigner{ authType: authType, privKey: privKey, } }
[ "func", "NewURLSigner", "(", "authType", "string", ",", "privKey", "string", ")", "*", "URLSigner", "{", "return", "&", "URLSigner", "{", "authType", ":", "authType", ",", "privKey", ":", "privKey", ",", "}", "\n", "}" ]
// NewURLSigner returns a new signer object.
[ "NewURLSigner", "returns", "a", "new", "signer", "object", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cdn/auth/sign_url.go#L19-L24
train
denverdino/aliyungo
cdn/auth/sign_url.go
Sign
func (s URLSigner) Sign(uri string, expires time.Time) (string, error) { r, err := url.Parse(uri) if err != nil { return "", fmt.Errorf("unable to parse url: %s", uri) } switch s.authType { case "a": return aTypeSign(r, s.privKey, expires), nil case "b": return bTypeSign(r, s.privKey, expires), nil case "c": return cTypeSign(r, s.privKey, expires), nil default: return "", fmt.Errorf("invalid authentication type") } }
go
func (s URLSigner) Sign(uri string, expires time.Time) (string, error) { r, err := url.Parse(uri) if err != nil { return "", fmt.Errorf("unable to parse url: %s", uri) } switch s.authType { case "a": return aTypeSign(r, s.privKey, expires), nil case "b": return bTypeSign(r, s.privKey, expires), nil case "c": return cTypeSign(r, s.privKey, expires), nil default: return "", fmt.Errorf("invalid authentication type") } }
[ "func", "(", "s", "URLSigner", ")", "Sign", "(", "uri", "string", ",", "expires", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "r", ",", "err", ":=", "url", ".", "Parse", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{",...
// Sign returns a signed aliyuncdn url based on authentication type
[ "Sign", "returns", "a", "signed", "aliyuncdn", "url", "based", "on", "authentication", "type" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cdn/auth/sign_url.go#L27-L43
train
denverdino/aliyungo
oss/multi.go
Complete
func (m *Multi) Complete(parts []Part) error { params := make(url.Values) params.Set("uploadId", m.UploadId) c := completeUpload{} for _, p := range parts { c.Parts = append(c.Parts, completePart{p.N, p.ETag}) } sort.Sort(c.Parts) data, err := xml.Marshal(&c) if err != nil { return err } for attempt := attempts.Start(); attempt.Next(); { req := &request{ method: "POST", bucket: m.Bucket.Name, path: m.Key, params: params, payload: bytes.NewReader(data), } err := m.Bucket.Client.query(req, nil) if shouldRetry(err) && attempt.HasNext() { continue } return err } panic("unreachable") }
go
func (m *Multi) Complete(parts []Part) error { params := make(url.Values) params.Set("uploadId", m.UploadId) c := completeUpload{} for _, p := range parts { c.Parts = append(c.Parts, completePart{p.N, p.ETag}) } sort.Sort(c.Parts) data, err := xml.Marshal(&c) if err != nil { return err } for attempt := attempts.Start(); attempt.Next(); { req := &request{ method: "POST", bucket: m.Bucket.Name, path: m.Key, params: params, payload: bytes.NewReader(data), } err := m.Bucket.Client.query(req, nil) if shouldRetry(err) && attempt.HasNext() { continue } return err } panic("unreachable") }
[ "func", "(", "m", "*", "Multi", ")", "Complete", "(", "parts", "[", "]", "Part", ")", "error", "{", "params", ":=", "make", "(", "url", ".", "Values", ")", "\n", "params", ".", "Set", "(", "\"", "\"", ",", "m", ".", "UploadId", ")", "\n\n", "c"...
// Complete assembles the given previously uploaded parts into the // final object. This operation may take several minutes. //
[ "Complete", "assembles", "the", "given", "previously", "uploaded", "parts", "into", "the", "final", "object", ".", "This", "operation", "may", "take", "several", "minutes", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/multi.go#L425-L453
train
denverdino/aliyungo
common/client.go
Init
func (client *Client) Init(endpoint, version, accessKeyId, accessKeySecret string) { client.AccessKeyId = accessKeyId ak := accessKeySecret if !strings.HasSuffix(ak, "&") { ak += "&" } client.AccessKeySecret = ak client.debug = false handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout")) if err != nil { handshakeTimeout = 0 } if handshakeTimeout == 0 { client.httpClient = &http.Client{} } else { t := &http.Transport{ TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second} client.httpClient = &http.Client{Transport: t} } client.endpoint = endpoint client.version = version }
go
func (client *Client) Init(endpoint, version, accessKeyId, accessKeySecret string) { client.AccessKeyId = accessKeyId ak := accessKeySecret if !strings.HasSuffix(ak, "&") { ak += "&" } client.AccessKeySecret = ak client.debug = false handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout")) if err != nil { handshakeTimeout = 0 } if handshakeTimeout == 0 { client.httpClient = &http.Client{} } else { t := &http.Transport{ TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second} client.httpClient = &http.Client{Transport: t} } client.endpoint = endpoint client.version = version }
[ "func", "(", "client", "*", "Client", ")", "Init", "(", "endpoint", ",", "version", ",", "accessKeyId", ",", "accessKeySecret", "string", ")", "{", "client", ".", "AccessKeyId", "=", "accessKeyId", "\n", "ak", ":=", "accessKeySecret", "\n", "if", "!", "str...
// Initialize properties of a client instance
[ "Initialize", "properties", "of", "a", "client", "instance" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L44-L65
train
denverdino/aliyungo
common/client.go
NewInit
func (client *Client) NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region) { client.Init(endpoint, version, accessKeyId, accessKeySecret) client.serviceCode = serviceCode client.regionID = regionID }
go
func (client *Client) NewInit(endpoint, version, accessKeyId, accessKeySecret, serviceCode string, regionID Region) { client.Init(endpoint, version, accessKeyId, accessKeySecret) client.serviceCode = serviceCode client.regionID = regionID }
[ "func", "(", "client", "*", "Client", ")", "NewInit", "(", "endpoint", ",", "version", ",", "accessKeyId", ",", "accessKeySecret", ",", "serviceCode", "string", ",", "regionID", "Region", ")", "{", "client", ".", "Init", "(", "endpoint", ",", "version", ",...
// Initialize properties of a client instance including regionID
[ "Initialize", "properties", "of", "a", "client", "instance", "including", "regionID" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L68-L72
train
denverdino/aliyungo
common/client.go
InitClient
func (client *Client) InitClient() *Client { client.debug = false handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout")) if err != nil { handshakeTimeout = 0 } if handshakeTimeout == 0 { client.httpClient = &http.Client{} } else { t := &http.Transport{ TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second} client.httpClient = &http.Client{Transport: t} } return client }
go
func (client *Client) InitClient() *Client { client.debug = false handshakeTimeout, err := strconv.Atoi(os.Getenv("TLSHandshakeTimeout")) if err != nil { handshakeTimeout = 0 } if handshakeTimeout == 0 { client.httpClient = &http.Client{} } else { t := &http.Transport{ TLSHandshakeTimeout: time.Duration(handshakeTimeout) * time.Second} client.httpClient = &http.Client{Transport: t} } return client }
[ "func", "(", "client", "*", "Client", ")", "InitClient", "(", ")", "*", "Client", "{", "client", ".", "debug", "=", "false", "\n", "handshakeTimeout", ",", "err", ":=", "strconv", ".", "Atoi", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ")", "\...
// Intialize client object when all properties are ready
[ "Intialize", "client", "object", "when", "all", "properties", "are", "ready" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L75-L89
train
denverdino/aliyungo
common/client.go
setEndpointByLocation
func (client *Client) setEndpointByLocation(region Region, serviceCode, accessKeyId, accessKeySecret, securityToken string) { locationClient := NewLocationClient(accessKeyId, accessKeySecret, securityToken) locationClient.SetDebug(true) ep := locationClient.DescribeOpenAPIEndpoint(region, serviceCode) if ep == "" { ep = loadEndpointFromFile(region, serviceCode) } if ep != "" { client.endpoint = ep } }
go
func (client *Client) setEndpointByLocation(region Region, serviceCode, accessKeyId, accessKeySecret, securityToken string) { locationClient := NewLocationClient(accessKeyId, accessKeySecret, securityToken) locationClient.SetDebug(true) ep := locationClient.DescribeOpenAPIEndpoint(region, serviceCode) if ep == "" { ep = loadEndpointFromFile(region, serviceCode) } if ep != "" { client.endpoint = ep } }
[ "func", "(", "client", "*", "Client", ")", "setEndpointByLocation", "(", "region", "Region", ",", "serviceCode", ",", "accessKeyId", ",", "accessKeySecret", ",", "securityToken", "string", ")", "{", "locationClient", ":=", "NewLocationClient", "(", "accessKeyId", ...
//NewClient using location service
[ "NewClient", "using", "location", "service" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L104-L115
train
denverdino/aliyungo
common/client.go
ensureProperties
func (client *Client) ensureProperties() error { var msg string if client.endpoint == "" { msg = fmt.Sprintf("endpoint cannot be empty!") } else if client.version == "" { msg = fmt.Sprintf("version cannot be empty!") } else if client.AccessKeyId == "" { msg = fmt.Sprintf("AccessKeyId cannot be empty!") } else if client.AccessKeySecret == "" { msg = fmt.Sprintf("AccessKeySecret cannot be empty!") } if msg != "" { return errors.New(msg) } return nil }
go
func (client *Client) ensureProperties() error { var msg string if client.endpoint == "" { msg = fmt.Sprintf("endpoint cannot be empty!") } else if client.version == "" { msg = fmt.Sprintf("version cannot be empty!") } else if client.AccessKeyId == "" { msg = fmt.Sprintf("AccessKeyId cannot be empty!") } else if client.AccessKeySecret == "" { msg = fmt.Sprintf("AccessKeySecret cannot be empty!") } if msg != "" { return errors.New(msg) } return nil }
[ "func", "(", "client", "*", "Client", ")", "ensureProperties", "(", ")", "error", "{", "var", "msg", "string", "\n\n", "if", "client", ".", "endpoint", "==", "\"", "\"", "{", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "}", "else...
// Ensure all necessary properties are valid
[ "Ensure", "all", "necessary", "properties", "are", "valid" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L118-L136
train
denverdino/aliyungo
common/client.go
WithVersion
func (client *Client) WithVersion(version string) *Client { client.SetVersion(version) return client }
go
func (client *Client) WithVersion(version string) *Client { client.SetVersion(version) return client }
[ "func", "(", "client", "*", "Client", ")", "WithVersion", "(", "version", "string", ")", "*", "Client", "{", "client", ".", "SetVersion", "(", "version", ")", "\n", "return", "client", "\n", "}" ]
// WithVersion sets custom version
[ "WithVersion", "sets", "custom", "version" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L149-L152
train
denverdino/aliyungo
common/client.go
WithRegionID
func (client *Client) WithRegionID(regionID Region) *Client { client.SetRegionID(regionID) return client }
go
func (client *Client) WithRegionID(regionID Region) *Client { client.SetRegionID(regionID) return client }
[ "func", "(", "client", "*", "Client", ")", "WithRegionID", "(", "regionID", "Region", ")", "*", "Client", "{", "client", ".", "SetRegionID", "(", "regionID", ")", "\n", "return", "client", "\n", "}" ]
// WithRegionID sets Region ID
[ "WithRegionID", "sets", "Region", "ID" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L155-L158
train
denverdino/aliyungo
common/client.go
WithServiceCode
func (client *Client) WithServiceCode(serviceCode string) *Client { client.SetServiceCode(serviceCode) return client }
go
func (client *Client) WithServiceCode(serviceCode string) *Client { client.SetServiceCode(serviceCode) return client }
[ "func", "(", "client", "*", "Client", ")", "WithServiceCode", "(", "serviceCode", "string", ")", "*", "Client", "{", "client", ".", "SetServiceCode", "(", "serviceCode", ")", "\n", "return", "client", "\n", "}" ]
//WithServiceCode sets serviceCode
[ "WithServiceCode", "sets", "serviceCode" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L161-L164
train
denverdino/aliyungo
common/client.go
WithAccessKeyId
func (client *Client) WithAccessKeyId(id string) *Client { client.SetAccessKeyId(id) return client }
go
func (client *Client) WithAccessKeyId(id string) *Client { client.SetAccessKeyId(id) return client }
[ "func", "(", "client", "*", "Client", ")", "WithAccessKeyId", "(", "id", "string", ")", "*", "Client", "{", "client", ".", "SetAccessKeyId", "(", "id", ")", "\n", "return", "client", "\n", "}" ]
// WithAccessKeyId sets new AccessKeyId
[ "WithAccessKeyId", "sets", "new", "AccessKeyId" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L167-L170
train
denverdino/aliyungo
common/client.go
WithAccessKeySecret
func (client *Client) WithAccessKeySecret(secret string) *Client { client.SetAccessKeySecret(secret) return client }
go
func (client *Client) WithAccessKeySecret(secret string) *Client { client.SetAccessKeySecret(secret) return client }
[ "func", "(", "client", "*", "Client", ")", "WithAccessKeySecret", "(", "secret", "string", ")", "*", "Client", "{", "client", ".", "SetAccessKeySecret", "(", "secret", ")", "\n", "return", "client", "\n", "}" ]
// WithAccessKeySecret sets new AccessKeySecret
[ "WithAccessKeySecret", "sets", "new", "AccessKeySecret" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L173-L176
train
denverdino/aliyungo
common/client.go
WithSecurityToken
func (client *Client) WithSecurityToken(securityToken string) *Client { client.SetSecurityToken(securityToken) return client }
go
func (client *Client) WithSecurityToken(securityToken string) *Client { client.SetSecurityToken(securityToken) return client }
[ "func", "(", "client", "*", "Client", ")", "WithSecurityToken", "(", "securityToken", "string", ")", "*", "Client", "{", "client", ".", "SetSecurityToken", "(", "securityToken", ")", "\n", "return", "client", "\n", "}" ]
// WithSecurityToken sets securityToken
[ "WithSecurityToken", "sets", "securityToken" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L179-L182
train
denverdino/aliyungo
common/client.go
Invoke
func (client *Client) Invoke(action string, args interface{}, response interface{}) error { if err := client.ensureProperties(); err != nil { return err } //init endpoint if err := client.initEndpoint(); err != nil { return err } request := Request{} request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID) query := util.ConvertToQueryValues(request) util.SetQueryValues(args, &query) // Sign request signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret) // Generate the request URL requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature) httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil) if err != nil { return GetClientError(err) } // TODO move to util and add build val flag httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo) httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent) t0 := time.Now() httpResp, err := client.httpClient.Do(httpReq) t1 := time.Now() if err != nil { return GetClientError(err) } statusCode := httpResp.StatusCode if client.debug { log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0)) } defer httpResp.Body.Close() body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return GetClientError(err) } if client.debug { var prettyJSON bytes.Buffer err = json.Indent(&prettyJSON, body, "", " ") log.Println(string(prettyJSON.Bytes())) } if statusCode >= 400 && statusCode <= 599 { errorResponse := ErrorResponse{} err = json.Unmarshal(body, &errorResponse) ecsError := &Error{ ErrorResponse: errorResponse, StatusCode: statusCode, } return ecsError } err = json.Unmarshal(body, response) //log.Printf("%++v", response) if err != nil { return GetClientError(err) } return nil }
go
func (client *Client) Invoke(action string, args interface{}, response interface{}) error { if err := client.ensureProperties(); err != nil { return err } //init endpoint if err := client.initEndpoint(); err != nil { return err } request := Request{} request.init(client.version, action, client.AccessKeyId, client.securityToken, client.regionID) query := util.ConvertToQueryValues(request) util.SetQueryValues(args, &query) // Sign request signature := util.CreateSignatureForRequest(ECSRequestMethod, &query, client.AccessKeySecret) // Generate the request URL requestURL := client.endpoint + "?" + query.Encode() + "&Signature=" + url.QueryEscape(signature) httpReq, err := http.NewRequest(ECSRequestMethod, requestURL, nil) if err != nil { return GetClientError(err) } // TODO move to util and add build val flag httpReq.Header.Set("X-SDK-Client", `AliyunGO/`+Version+client.businessInfo) httpReq.Header.Set("User-Agent", httpReq.UserAgent()+" "+client.userAgent) t0 := time.Now() httpResp, err := client.httpClient.Do(httpReq) t1 := time.Now() if err != nil { return GetClientError(err) } statusCode := httpResp.StatusCode if client.debug { log.Printf("Invoke %s %s %d (%v)", ECSRequestMethod, requestURL, statusCode, t1.Sub(t0)) } defer httpResp.Body.Close() body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return GetClientError(err) } if client.debug { var prettyJSON bytes.Buffer err = json.Indent(&prettyJSON, body, "", " ") log.Println(string(prettyJSON.Bytes())) } if statusCode >= 400 && statusCode <= 599 { errorResponse := ErrorResponse{} err = json.Unmarshal(body, &errorResponse) ecsError := &Error{ ErrorResponse: errorResponse, StatusCode: statusCode, } return ecsError } err = json.Unmarshal(body, response) //log.Printf("%++v", response) if err != nil { return GetClientError(err) } return nil }
[ "func", "(", "client", "*", "Client", ")", "Invoke", "(", "action", "string", ",", "args", "interface", "{", "}", ",", "response", "interface", "{", "}", ")", "error", "{", "if", "err", ":=", "client", ".", "ensureProperties", "(", ")", ";", "err", "...
// Invoke sends the raw HTTP request for ECS services
[ "Invoke", "sends", "the", "raw", "HTTP", "request", "for", "ECS", "services" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/client.go#L278-L353
train
denverdino/aliyungo
ecs/route_tables.go
WaitForAllRouteEntriesAvailable
func (client *Client) WaitForAllRouteEntriesAvailable(vrouterId string, routeTableId string, timeout int) error { if timeout <= 0 { timeout = DefaultTimeout } args := DescribeRouteTablesArgs{ VRouterId: vrouterId, RouteTableId: routeTableId, } for { routeTables, _, err := client.DescribeRouteTables(&args) if err != nil { return err } if len(routeTables) == 0 { return common.GetClientErrorFromString("Not found") } success := true loop: for _, routeTable := range routeTables { for _, routeEntry := range routeTable.RouteEntrys.RouteEntry { if routeEntry.Status != RouteEntryStatusAvailable { success = false break loop } } } if success { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForAllRouteEntriesAvailable(vrouterId string, routeTableId string, timeout int) error { if timeout <= 0 { timeout = DefaultTimeout } args := DescribeRouteTablesArgs{ VRouterId: vrouterId, RouteTableId: routeTableId, } for { routeTables, _, err := client.DescribeRouteTables(&args) if err != nil { return err } if len(routeTables) == 0 { return common.GetClientErrorFromString("Not found") } success := true loop: for _, routeTable := range routeTables { for _, routeEntry := range routeTable.RouteEntrys.RouteEntry { if routeEntry.Status != RouteEntryStatusAvailable { success = false break loop } } } if success { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForAllRouteEntriesAvailable", "(", "vrouterId", "string", ",", "routeTableId", "string", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "DefaultTimeout", "\n", "}", "...
// WaitForAllRouteEntriesAvailable waits for all route entries to Available status
[ "WaitForAllRouteEntriesAvailable", "waits", "for", "all", "route", "entries", "to", "Available", "status" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/route_tables.go#L147-L186
train
denverdino/aliyungo
cs/client.go
NewClient
func NewClient(accessKeyId, accessKeySecret string) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, endpoint: CSDefaultEndpoint, Version: CSAPIVersion, httpClient: &http.Client{}, } }
go
func NewClient(accessKeyId, accessKeySecret string) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, endpoint: CSDefaultEndpoint, Version: CSAPIVersion, httpClient: &http.Client{}, } }
[ "func", "NewClient", "(", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "Client", "{", "return", "&", "Client", "{", "AccessKeyId", ":", "accessKeyId", ",", "AccessKeySecret", ":", "accessKeySecret", ",", "endpoint", ":", "CSDefaultEndpoint", ",", "...
// NewClient creates a new instance of CRM client
[ "NewClient", "creates", "a", "new", "instance", "of", "CRM", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cs/client.go#L48-L56
train
denverdino/aliyungo
nas/client.go
NewClient
func NewClient(accessKeyId, accessKeySecret string) *Client { client := &Client{} client.Init(END_POINT, VERSION, accessKeyId, accessKeySecret) return client }
go
func NewClient(accessKeyId, accessKeySecret string) *Client { client := &Client{} client.Init(END_POINT, VERSION, accessKeyId, accessKeySecret) return client }
[ "func", "NewClient", "(", "accessKeyId", ",", "accessKeySecret", "string", ")", "*", "Client", "{", "client", ":=", "&", "Client", "{", "}", "\n", "client", ".", "Init", "(", "END_POINT", ",", "VERSION", ",", "accessKeyId", ",", "accessKeySecret", ")", "\n...
// NewClient creates a new instance of NAS client
[ "NewClient", "creates", "a", "new", "instance", "of", "NAS", "client" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/nas/client.go#L20-L24
train
denverdino/aliyungo
util/util.go
EncodeWithoutEscape
func EncodeWithoutEscape(v url.Values) string { if v == nil { return "" } var buf bytes.Buffer keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vs := v[k] prefix := k for _, v := range vs { if buf.Len() > 0 { buf.WriteByte('&') } buf.WriteString(prefix) if v != "" { buf.WriteString("=") buf.WriteString(v) } } } return buf.String() }
go
func EncodeWithoutEscape(v url.Values) string { if v == nil { return "" } var buf bytes.Buffer keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vs := v[k] prefix := k for _, v := range vs { if buf.Len() > 0 { buf.WriteByte('&') } buf.WriteString(prefix) if v != "" { buf.WriteString("=") buf.WriteString(v) } } } return buf.String() }
[ "func", "EncodeWithoutEscape", "(", "v", "url", ".", "Values", ")", "string", "{", "if", "v", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "keys", ":=", "make", "(", "[", "]", "string", ",", ...
// Like Encode, but key and value are not escaped
[ "Like", "Encode", "but", "key", "and", "value", "are", "not", "escaped" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/util.go#L70-L95
train
denverdino/aliyungo
ecs/instances.go
WaitForInstanceAsyn
func (client *Client) WaitForInstanceAsyn(instanceId string, status InstanceStatus, timeout int) error { if timeout <= 0 { timeout = InstanceDefaultTimeout } for { instance, err := client.DescribeInstanceAttribute(instanceId) if err != nil { e, _ := err.(*common.Error) if e.Code != "InvalidInstanceId.NotFound" && e.Code != "Forbidden.InstanceNotFound" { return err } } else if instance != nil && instance.Status == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForInstanceAsyn(instanceId string, status InstanceStatus, timeout int) error { if timeout <= 0 { timeout = InstanceDefaultTimeout } for { instance, err := client.DescribeInstanceAttribute(instanceId) if err != nil { e, _ := err.(*common.Error) if e.Code != "InvalidInstanceId.NotFound" && e.Code != "Forbidden.InstanceNotFound" { return err } } else if instance != nil && instance.Status == status { //TODO break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForInstanceAsyn", "(", "instanceId", "string", ",", "status", "InstanceStatus", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "InstanceDefaultTimeout", "\n", "}", "\...
// WaitForInstance waits for instance to given status // when instance.NotFound wait until timeout
[ "WaitForInstance", "waits", "for", "instance", "to", "given", "status", "when", "instance", ".", "NotFound", "wait", "until", "timeout" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/instances.go#L343-L366
train
denverdino/aliyungo
util/iso6801.go
GetISO8601TimeStamp
func GetISO8601TimeStamp(ts time.Time) string { t := ts.UTC() return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) }
go
func GetISO8601TimeStamp(ts time.Time) string { t := ts.UTC() return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) }
[ "func", "GetISO8601TimeStamp", "(", "ts", "time", ".", "Time", ")", "string", "{", "t", ":=", "ts", ".", "UTC", "(", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "Year", "(", ")", ",", "t", ".", "Month", "(", ")",...
// GetISO8601TimeStamp gets timestamp string in ISO8601 format
[ "GetISO8601TimeStamp", "gets", "timestamp", "string", "in", "ISO8601", "format" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/iso6801.go#L10-L13
train
denverdino/aliyungo
util/iso6801.go
MarshalJSON
func (it ISO6801Time) MarshalJSON() ([]byte, error) { return []byte(time.Time(it).Format(jsonFormatISO8601)), nil }
go
func (it ISO6801Time) MarshalJSON() ([]byte, error) { return []byte(time.Time(it).Format(jsonFormatISO8601)), nil }
[ "func", "(", "it", "ISO6801Time", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "time", ".", "Time", "(", "it", ")", ".", "Format", "(", "jsonFormatISO8601", ")", ")", ",", "nil", "\...
// MarshalJSON serializes the ISO6801Time into JSON string
[ "MarshalJSON", "serializes", "the", "ISO6801Time", "into", "JSON", "string" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/iso6801.go#L46-L48
train
denverdino/aliyungo
util/iso6801.go
UnmarshalJSON
func (it *ISO6801Time) UnmarshalJSON(data []byte) error { str := string(data) if str == "\"\"" || len(data) == 0 { return nil } var t time.Time var err error if str[0] == '"' { t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC) if err != nil { t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC) } } else { var i int64 i, err = strconv.ParseInt(str, 10, 64) if err == nil { t = time.Unix(i/1000, i%1000) } } if err == nil { *it = ISO6801Time(t) } return err }
go
func (it *ISO6801Time) UnmarshalJSON(data []byte) error { str := string(data) if str == "\"\"" || len(data) == 0 { return nil } var t time.Time var err error if str[0] == '"' { t, err = time.ParseInLocation(jsonFormatISO8601, str, time.UTC) if err != nil { t, err = time.ParseInLocation(jsonFormatISO8601withoutSeconds, str, time.UTC) } } else { var i int64 i, err = strconv.ParseInt(str, 10, 64) if err == nil { t = time.Unix(i/1000, i%1000) } } if err == nil { *it = ISO6801Time(t) } return err }
[ "func", "(", "it", "*", "ISO6801Time", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "str", ":=", "string", "(", "data", ")", "\n\n", "if", "str", "==", "\"", "\\\"", "\\\"", "\"", "||", "len", "(", "data", ")", "==", "0...
// UnmarshalJSON deserializes the ISO6801Time from JSON string
[ "UnmarshalJSON", "deserializes", "the", "ISO6801Time", "from", "JSON", "string" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/iso6801.go#L51-L75
train
denverdino/aliyungo
ecs/disks.go
WaitForDisk
func (client *Client) WaitForDisk(regionId common.Region, diskId string, status DiskStatus, timeout int) error { if timeout <= 0 { timeout = DefaultTimeout } args := DescribeDisksArgs{ RegionId: regionId, DiskIds: []string{diskId}, } for { disks, _, err := client.DescribeDisks(&args) if err != nil { return err } if disks == nil || len(disks) == 0 { return common.GetClientErrorFromString("Not found") } if disks[0].Status == status { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
go
func (client *Client) WaitForDisk(regionId common.Region, diskId string, status DiskStatus, timeout int) error { if timeout <= 0 { timeout = DefaultTimeout } args := DescribeDisksArgs{ RegionId: regionId, DiskIds: []string{diskId}, } for { disks, _, err := client.DescribeDisks(&args) if err != nil { return err } if disks == nil || len(disks) == 0 { return common.GetClientErrorFromString("Not found") } if disks[0].Status == status { break } timeout = timeout - DefaultWaitForInterval if timeout <= 0 { return common.GetClientErrorFromString("Timeout") } time.Sleep(DefaultWaitForInterval * time.Second) } return nil }
[ "func", "(", "client", "*", "Client", ")", "WaitForDisk", "(", "regionId", "common", ".", "Region", ",", "diskId", "string", ",", "status", "DiskStatus", ",", "timeout", "int", ")", "error", "{", "if", "timeout", "<=", "0", "{", "timeout", "=", "DefaultT...
// WaitForDisk waits for disk to given status
[ "WaitForDisk", "waits", "for", "disk", "to", "given", "status" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/ecs/disks.go#L336-L363
train
denverdino/aliyungo
cms/bytesbuffer/bytesbuffer.go
WriteByteString
func (this *BytesBuffer) WriteByteString(byteStr string) error { var tmp []byte = make([]byte, 2) re := regexp.MustCompile("[^a-fA-F0-9]") clean_str := re.ReplaceAllString(byteStr, "") src := bytes.NewBufferString(clean_str) cnt := src.Len() / 2 for i := 0; i < cnt; i++ { num := 0 _, err := src.Read(tmp) if err != nil { return err } fmt.Sscanf(string(tmp), "%X", &num) this.Buffer.WriteByte(byte(num)) } return nil }
go
func (this *BytesBuffer) WriteByteString(byteStr string) error { var tmp []byte = make([]byte, 2) re := regexp.MustCompile("[^a-fA-F0-9]") clean_str := re.ReplaceAllString(byteStr, "") src := bytes.NewBufferString(clean_str) cnt := src.Len() / 2 for i := 0; i < cnt; i++ { num := 0 _, err := src.Read(tmp) if err != nil { return err } fmt.Sscanf(string(tmp), "%X", &num) this.Buffer.WriteByte(byte(num)) } return nil }
[ "func", "(", "this", "*", "BytesBuffer", ")", "WriteByteString", "(", "byteStr", "string", ")", "error", "{", "var", "tmp", "[", "]", "byte", "=", "make", "(", "[", "]", "byte", ",", "2", ")", "\n\n", "re", ":=", "regexp", ".", "MustCompile", "(", ...
// \x31\x32\x33\x34 -> 1234 // %31%32%33%34 -> 1234 // 31323334 -> 1234
[ "\\", "x31", "\\", "x32", "\\", "x33", "\\", "x34", "-", ">", "1234", "%31%32%33%34", "-", ">", "1234", "31323334", "-", ">", "1234" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cms/bytesbuffer/bytesbuffer.go#L61-L81
train
denverdino/aliyungo
cms/bytesbuffer/bytesbuffer.go
WriteToByteString
func (this *BytesBuffer) WriteToByteString(w io.Writer, prefix string) (n int64, err error) { slen := this.Buffer.Len() dst := bytes.NewBufferString("") for i := 0; i < slen; i++ { c, _ := this.Buffer.ReadByte() dst.WriteString(fmt.Sprintf("%s%02X", prefix, c)) } return dst.WriteTo(w) }
go
func (this *BytesBuffer) WriteToByteString(w io.Writer, prefix string) (n int64, err error) { slen := this.Buffer.Len() dst := bytes.NewBufferString("") for i := 0; i < slen; i++ { c, _ := this.Buffer.ReadByte() dst.WriteString(fmt.Sprintf("%s%02X", prefix, c)) } return dst.WriteTo(w) }
[ "func", "(", "this", "*", "BytesBuffer", ")", "WriteToByteString", "(", "w", "io", ".", "Writer", ",", "prefix", "string", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "slen", ":=", "this", ".", "Buffer", ".", "Len", "(", ")", "\n", "dst"...
// Buffer will be empty after Write
[ "Buffer", "will", "be", "empty", "after", "Write" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/cms/bytesbuffer/bytesbuffer.go#L99-L109
train
denverdino/aliyungo
common/regions.go
IsValidRegion
func IsValidRegion(r string) bool { for _, v := range ValidRegions { if r == string(v) { return true } } return false }
go
func IsValidRegion(r string) bool { for _, v := range ValidRegions { if r == string(v) { return true } } return false }
[ "func", "IsValidRegion", "(", "r", "string", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "ValidRegions", "{", "if", "r", "==", "string", "(", "v", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsValidRegion checks if r is an Ali supported region.
[ "IsValidRegion", "checks", "if", "r", "is", "an", "Ali", "supported", "region", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/common/regions.go#L48-L55
train
denverdino/aliyungo
oss/client.go
NewOSSClientForAssumeRole
func NewOSSClientForAssumeRole(region Region, internal bool, accessKeyId string, accessKeySecret string, securityToken string, secure bool) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, SecurityToken: securityToken, Region: region, Internal: internal, debug: false, Secure: secure, } }
go
func NewOSSClientForAssumeRole(region Region, internal bool, accessKeyId string, accessKeySecret string, securityToken string, secure bool) *Client { return &Client{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, SecurityToken: securityToken, Region: region, Internal: internal, debug: false, Secure: secure, } }
[ "func", "NewOSSClientForAssumeRole", "(", "region", "Region", ",", "internal", "bool", ",", "accessKeyId", "string", ",", "accessKeySecret", "string", ",", "securityToken", "string", ",", "secure", "bool", ")", "*", "Client", "{", "return", "&", "Client", "{", ...
// NewOSSClient creates a new OSS.
[ "NewOSSClient", "creates", "a", "new", "OSS", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L96-L106
train
denverdino/aliyungo
oss/client.go
GetWithParams
func (b *Bucket) GetWithParams(path string, params url.Values) (data []byte, err error) { resp, err := b.GetResponseWithParamsAndHeaders(path, params, nil) if err != nil { return nil, err } data, err = ioutil.ReadAll(resp.Body) resp.Body.Close() return data, err }
go
func (b *Bucket) GetWithParams(path string, params url.Values) (data []byte, err error) { resp, err := b.GetResponseWithParamsAndHeaders(path, params, nil) if err != nil { return nil, err } data, err = ioutil.ReadAll(resp.Body) resp.Body.Close() return data, err }
[ "func", "(", "b", "*", "Bucket", ")", "GetWithParams", "(", "path", "string", ",", "params", "url", ".", "Values", ")", "(", "data", "[", "]", "byte", ",", "err", "error", ")", "{", "resp", ",", "err", ":=", "b", ".", "GetResponseWithParamsAndHeaders",...
// Get retrieves an object from an bucket.
[ "Get", "retrieves", "an", "object", "from", "an", "bucket", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L319-L327
train
denverdino/aliyungo
oss/client.go
Exists
func (b *Bucket) Exists(path string) (exists bool, err error) { for attempt := attempts.Start(); attempt.Next(); { req := &request{ method: "HEAD", bucket: b.Name, path: path, } err = b.Client.prepare(req) if err != nil { return } resp, err := b.Client.run(req, nil) if shouldRetry(err) && attempt.HasNext() { continue } if err != nil { // We can treat a 403 or 404 as non existence if e, ok := err.(*Error); ok && (e.StatusCode == 403 || e.StatusCode == 404) { return false, nil } return false, err } if resp.StatusCode/100 == 2 { exists = true } if resp.Body != nil { resp.Body.Close() } return exists, err } return false, fmt.Errorf("OSS Currently Unreachable") }
go
func (b *Bucket) Exists(path string) (exists bool, err error) { for attempt := attempts.Start(); attempt.Next(); { req := &request{ method: "HEAD", bucket: b.Name, path: path, } err = b.Client.prepare(req) if err != nil { return } resp, err := b.Client.run(req, nil) if shouldRetry(err) && attempt.HasNext() { continue } if err != nil { // We can treat a 403 or 404 as non existence if e, ok := err.(*Error); ok && (e.StatusCode == 403 || e.StatusCode == 404) { return false, nil } return false, err } if resp.StatusCode/100 == 2 { exists = true } if resp.Body != nil { resp.Body.Close() } return exists, err } return false, fmt.Errorf("OSS Currently Unreachable") }
[ "func", "(", "b", "*", "Bucket", ")", "Exists", "(", "path", "string", ")", "(", "exists", "bool", ",", "err", "error", ")", "{", "for", "attempt", ":=", "attempts", ".", "Start", "(", ")", ";", "attempt", ".", "Next", "(", ")", ";", "{", "req", ...
// Exists checks whether or not an object exists on an bucket using a HEAD request.
[ "Exists", "checks", "whether", "or", "not", "an", "object", "exists", "on", "an", "bucket", "using", "a", "HEAD", "request", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L355-L390
train
denverdino/aliyungo
oss/client.go
SignedURLWithArgs
func (b *Bucket) SignedURLWithArgs(path string, expires time.Time, params url.Values, headers http.Header) string { return b.SignedURLWithMethod("GET", path, expires, params, headers) }
go
func (b *Bucket) SignedURLWithArgs(path string, expires time.Time, params url.Values, headers http.Header) string { return b.SignedURLWithMethod("GET", path, expires, params, headers) }
[ "func", "(", "b", "*", "Bucket", ")", "SignedURLWithArgs", "(", "path", "string", ",", "expires", "time", ".", "Time", ",", "params", "url", ".", "Values", ",", "headers", "http", ".", "Header", ")", "string", "{", "return", "b", ".", "SignedURLWithMetho...
// SignedURLWithArgs returns a signed URL that allows anyone holding the URL // to retrieve the object at path. The signature is valid until expires.
[ "SignedURLWithArgs", "returns", "a", "signed", "URL", "that", "allows", "anyone", "holding", "the", "URL", "to", "retrieve", "the", "object", "at", "path", ".", "The", "signature", "is", "valid", "until", "expires", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L850-L852
train
denverdino/aliyungo
oss/client.go
SignedURLWithMethod
func (b *Bucket) SignedURLWithMethod(method, path string, expires time.Time, params url.Values, headers http.Header) string { var uv = url.Values{} if params != nil { uv = params } uv.Set("Expires", strconv.FormatInt(expires.Unix(), 10)) uv.Set("OSSAccessKeyId", b.AccessKeyId) req := &request{ method: method, bucket: b.Name, path: path, params: uv, headers: headers, } err := b.Client.prepare(req) if err != nil { panic(err) } u, err := req.url() if err != nil { panic(err) } return u.String() }
go
func (b *Bucket) SignedURLWithMethod(method, path string, expires time.Time, params url.Values, headers http.Header) string { var uv = url.Values{} if params != nil { uv = params } uv.Set("Expires", strconv.FormatInt(expires.Unix(), 10)) uv.Set("OSSAccessKeyId", b.AccessKeyId) req := &request{ method: method, bucket: b.Name, path: path, params: uv, headers: headers, } err := b.Client.prepare(req) if err != nil { panic(err) } u, err := req.url() if err != nil { panic(err) } return u.String() }
[ "func", "(", "b", "*", "Bucket", ")", "SignedURLWithMethod", "(", "method", ",", "path", "string", ",", "expires", "time", ".", "Time", ",", "params", "url", ".", "Values", ",", "headers", "http", ".", "Header", ")", "string", "{", "var", "uv", "=", ...
// SignedURLWithMethod returns a signed URL that allows anyone holding the URL // to either retrieve the object at path or make a HEAD request against it. The signature is valid until expires.
[ "SignedURLWithMethod", "returns", "a", "signed", "URL", "that", "allows", "anyone", "holding", "the", "URL", "to", "either", "retrieve", "the", "object", "at", "path", "or", "make", "a", "HEAD", "request", "against", "it", ".", "The", "signature", "is", "val...
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L867-L894
train
denverdino/aliyungo
oss/client.go
PostFormArgsEx
func (b *Bucket) PostFormArgsEx(path string, expires time.Time, redirect string, conds []string) (action string, fields map[string]string) { conditions := []string{} fields = map[string]string{ "AWSAccessKeyId": b.AccessKeyId, "key": path, } if conds != nil { conditions = append(conditions, conds...) } conditions = append(conditions, fmt.Sprintf("{\"key\": \"%s\"}", path)) conditions = append(conditions, fmt.Sprintf("{\"bucket\": \"%s\"}", b.Name)) if redirect != "" { conditions = append(conditions, fmt.Sprintf("{\"success_action_redirect\": \"%s\"}", redirect)) fields["success_action_redirect"] = redirect } vExpiration := expires.Format("2006-01-02T15:04:05Z") vConditions := strings.Join(conditions, ",") policy := fmt.Sprintf("{\"expiration\": \"%s\", \"conditions\": [%s]}", vExpiration, vConditions) policy64 := base64.StdEncoding.EncodeToString([]byte(policy)) fields["policy"] = policy64 signer := hmac.New(sha1.New, []byte(b.AccessKeySecret)) signer.Write([]byte(policy64)) fields["signature"] = base64.StdEncoding.EncodeToString(signer.Sum(nil)) action = fmt.Sprintf("%s/%s/", b.Client.Region, b.Name) return }
go
func (b *Bucket) PostFormArgsEx(path string, expires time.Time, redirect string, conds []string) (action string, fields map[string]string) { conditions := []string{} fields = map[string]string{ "AWSAccessKeyId": b.AccessKeyId, "key": path, } if conds != nil { conditions = append(conditions, conds...) } conditions = append(conditions, fmt.Sprintf("{\"key\": \"%s\"}", path)) conditions = append(conditions, fmt.Sprintf("{\"bucket\": \"%s\"}", b.Name)) if redirect != "" { conditions = append(conditions, fmt.Sprintf("{\"success_action_redirect\": \"%s\"}", redirect)) fields["success_action_redirect"] = redirect } vExpiration := expires.Format("2006-01-02T15:04:05Z") vConditions := strings.Join(conditions, ",") policy := fmt.Sprintf("{\"expiration\": \"%s\", \"conditions\": [%s]}", vExpiration, vConditions) policy64 := base64.StdEncoding.EncodeToString([]byte(policy)) fields["policy"] = policy64 signer := hmac.New(sha1.New, []byte(b.AccessKeySecret)) signer.Write([]byte(policy64)) fields["signature"] = base64.StdEncoding.EncodeToString(signer.Sum(nil)) action = fmt.Sprintf("%s/%s/", b.Client.Region, b.Name) return }
[ "func", "(", "b", "*", "Bucket", ")", "PostFormArgsEx", "(", "path", "string", ",", "expires", "time", ".", "Time", ",", "redirect", "string", ",", "conds", "[", "]", "string", ")", "(", "action", "string", ",", "fields", "map", "[", "string", "]", "...
// PostFormArgsEx returns the action and input fields needed to allow anonymous // uploads to a bucket within the expiration limit // Additional conditions can be specified with conds
[ "PostFormArgsEx", "returns", "the", "action", "and", "input", "fields", "needed", "to", "allow", "anonymous", "uploads", "to", "a", "bucket", "within", "the", "expiration", "limit", "Additional", "conditions", "can", "be", "specified", "with", "conds" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L936-L966
train
denverdino/aliyungo
oss/client.go
PostFormArgs
func (b *Bucket) PostFormArgs(path string, expires time.Time, redirect string) (action string, fields map[string]string) { return b.PostFormArgsEx(path, expires, redirect, nil) }
go
func (b *Bucket) PostFormArgs(path string, expires time.Time, redirect string) (action string, fields map[string]string) { return b.PostFormArgsEx(path, expires, redirect, nil) }
[ "func", "(", "b", "*", "Bucket", ")", "PostFormArgs", "(", "path", "string", ",", "expires", "time", ".", "Time", ",", "redirect", "string", ")", "(", "action", "string", ",", "fields", "map", "[", "string", "]", "string", ")", "{", "return", "b", "....
// PostFormArgs returns the action and input fields needed to allow anonymous // uploads to a bucket within the expiration limit
[ "PostFormArgs", "returns", "the", "action", "and", "input", "fields", "needed", "to", "allow", "anonymous", "uploads", "to", "a", "bucket", "within", "the", "expiration", "limit" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L970-L972
train
denverdino/aliyungo
oss/client.go
prepare
func (client *Client) prepare(req *request) error { // Copy so they can be mutated without affecting on retries. headers := copyHeader(req.headers) // security-token should be in either Params or Header, cannot be in both if len(req.params.Get("security-token")) == 0 && len(client.SecurityToken) != 0 { headers.Set("x-oss-security-token", client.SecurityToken) } params := make(url.Values) for k, v := range req.params { params[k] = v } req.params = params req.headers = headers if !req.prepared { req.prepared = true if req.method == "" { req.method = "GET" } if !strings.HasPrefix(req.path, "/") { req.path = "/" + req.path } err := client.setBaseURL(req) if err != nil { return err } } req.headers.Set("Date", util.GetGMTime()) client.signRequest(req) return nil }
go
func (client *Client) prepare(req *request) error { // Copy so they can be mutated without affecting on retries. headers := copyHeader(req.headers) // security-token should be in either Params or Header, cannot be in both if len(req.params.Get("security-token")) == 0 && len(client.SecurityToken) != 0 { headers.Set("x-oss-security-token", client.SecurityToken) } params := make(url.Values) for k, v := range req.params { params[k] = v } req.params = params req.headers = headers if !req.prepared { req.prepared = true if req.method == "" { req.method = "GET" } if !strings.HasPrefix(req.path, "/") { req.path = "/" + req.path } err := client.setBaseURL(req) if err != nil { return err } } req.headers.Set("Date", util.GetGMTime()) client.signRequest(req) return nil }
[ "func", "(", "client", "*", "Client", ")", "prepare", "(", "req", "*", "request", ")", "error", "{", "// Copy so they can be mutated without affecting on retries.", "headers", ":=", "copyHeader", "(", "req", ".", "headers", ")", "\n", "// security-token should be in e...
// prepare sets up req to be delivered to OSS.
[ "prepare", "sets", "up", "req", "to", "be", "delivered", "to", "OSS", "." ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L1050-L1087
train
denverdino/aliyungo
oss/client.go
CopyLargeFileInParallel
func (b *Bucket) CopyLargeFileInParallel(sourcePath string, destPath string, contentType string, perm ACL, options Options, maxConcurrency int) error { if maxConcurrency < 1 { maxConcurrency = 1 } currentLength, err := b.GetContentLength(sourcePath) log.Printf("Parallel Copy large file[size: %d] from %s to %s\n", currentLength, sourcePath, destPath) if err != nil { return err } if currentLength < maxCopytSize { _, err := b.PutCopy(destPath, perm, CopyOptions{}, b.Path(sourcePath)) return err } multi, err := b.InitMulti(destPath, contentType, perm, options) if err != nil { return err } numParts := (currentLength + defaultChunkSize - 1) / defaultChunkSize completedParts := make([]Part, numParts) errChan := make(chan error, numParts) limiter := make(chan struct{}, maxConcurrency) var start int64 = 0 var to int64 = 0 var partNumber = 0 sourcePathForCopy := b.Path(sourcePath) for start = 0; start < currentLength; start = to { to = start + defaultChunkSize if to > currentLength { to = currentLength } partNumber++ rangeStr := fmt.Sprintf("bytes=%d-%d", start, to-1) limiter <- struct{}{} go func(partNumber int, rangeStr string) { _, part, err := multi.PutPartCopyWithContentLength(partNumber, CopyOptions{CopySourceOptions: rangeStr}, sourcePathForCopy, currentLength) if err == nil { completedParts[partNumber-1] = part } else { log.Printf("Unable in PutPartCopy of part %d for %s: %v\n", partNumber, sourcePathForCopy, err) } errChan <- err <-limiter }(partNumber, rangeStr) } fullyCompleted := true for range completedParts { err := <-errChan if err != nil { fullyCompleted = false } } if fullyCompleted { err = multi.Complete(completedParts) } else { err = multi.Abort() } return err }
go
func (b *Bucket) CopyLargeFileInParallel(sourcePath string, destPath string, contentType string, perm ACL, options Options, maxConcurrency int) error { if maxConcurrency < 1 { maxConcurrency = 1 } currentLength, err := b.GetContentLength(sourcePath) log.Printf("Parallel Copy large file[size: %d] from %s to %s\n", currentLength, sourcePath, destPath) if err != nil { return err } if currentLength < maxCopytSize { _, err := b.PutCopy(destPath, perm, CopyOptions{}, b.Path(sourcePath)) return err } multi, err := b.InitMulti(destPath, contentType, perm, options) if err != nil { return err } numParts := (currentLength + defaultChunkSize - 1) / defaultChunkSize completedParts := make([]Part, numParts) errChan := make(chan error, numParts) limiter := make(chan struct{}, maxConcurrency) var start int64 = 0 var to int64 = 0 var partNumber = 0 sourcePathForCopy := b.Path(sourcePath) for start = 0; start < currentLength; start = to { to = start + defaultChunkSize if to > currentLength { to = currentLength } partNumber++ rangeStr := fmt.Sprintf("bytes=%d-%d", start, to-1) limiter <- struct{}{} go func(partNumber int, rangeStr string) { _, part, err := multi.PutPartCopyWithContentLength(partNumber, CopyOptions{CopySourceOptions: rangeStr}, sourcePathForCopy, currentLength) if err == nil { completedParts[partNumber-1] = part } else { log.Printf("Unable in PutPartCopy of part %d for %s: %v\n", partNumber, sourcePathForCopy, err) } errChan <- err <-limiter }(partNumber, rangeStr) } fullyCompleted := true for range completedParts { err := <-errChan if err != nil { fullyCompleted = false } } if fullyCompleted { err = multi.Complete(completedParts) } else { err = multi.Abort() } return err }
[ "func", "(", "b", "*", "Bucket", ")", "CopyLargeFileInParallel", "(", "sourcePath", "string", ",", "destPath", "string", ",", "contentType", "string", ",", "perm", "ACL", ",", "options", "Options", ",", "maxConcurrency", "int", ")", "error", "{", "if", "maxC...
// Copy large file in the same bucket
[ "Copy", "large", "file", "in", "the", "same", "bucket" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/oss/client.go#L1346-L1421
train
denverdino/aliyungo
util/signature.go
CreateSignature
func CreateSignature(stringToSignature, accessKeySecret string) string { // Crypto by HMAC-SHA1 hmacSha1 := hmac.New(sha1.New, []byte(accessKeySecret)) hmacSha1.Write([]byte(stringToSignature)) sign := hmacSha1.Sum(nil) // Encode to Base64 base64Sign := base64.StdEncoding.EncodeToString(sign) return base64Sign }
go
func CreateSignature(stringToSignature, accessKeySecret string) string { // Crypto by HMAC-SHA1 hmacSha1 := hmac.New(sha1.New, []byte(accessKeySecret)) hmacSha1.Write([]byte(stringToSignature)) sign := hmacSha1.Sum(nil) // Encode to Base64 base64Sign := base64.StdEncoding.EncodeToString(sign) return base64Sign }
[ "func", "CreateSignature", "(", "stringToSignature", ",", "accessKeySecret", "string", ")", "string", "{", "// Crypto by HMAC-SHA1", "hmacSha1", ":=", "hmac", ".", "New", "(", "sha1", ".", "New", ",", "[", "]", "byte", "(", "accessKeySecret", ")", ")", "\n", ...
//CreateSignature creates signature for string following Aliyun rules
[ "CreateSignature", "creates", "signature", "for", "string", "following", "Aliyun", "rules" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/signature.go#L12-L22
train
denverdino/aliyungo
util/signature.go
CreateSignatureForRequest
func CreateSignatureForRequest(method string, values *url.Values, accessKeySecret string) string { canonicalizedQueryString := percentReplace(values.Encode()) stringToSign := method + "&%2F&" + url.QueryEscape(canonicalizedQueryString) return CreateSignature(stringToSign, accessKeySecret) }
go
func CreateSignatureForRequest(method string, values *url.Values, accessKeySecret string) string { canonicalizedQueryString := percentReplace(values.Encode()) stringToSign := method + "&%2F&" + url.QueryEscape(canonicalizedQueryString) return CreateSignature(stringToSign, accessKeySecret) }
[ "func", "CreateSignatureForRequest", "(", "method", "string", ",", "values", "*", "url", ".", "Values", ",", "accessKeySecret", "string", ")", "string", "{", "canonicalizedQueryString", ":=", "percentReplace", "(", "values", ".", "Encode", "(", ")", ")", "\n\n",...
// CreateSignatureForRequest creates signature for query string values
[ "CreateSignatureForRequest", "creates", "signature", "for", "query", "string", "values" ]
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/signature.go#L33-L39
train
alecthomas/jsonschema
reflect.go
ReflectFromType
func ReflectFromType(t reflect.Type) *Schema { r := &Reflector{} return r.ReflectFromType(t) }
go
func ReflectFromType(t reflect.Type) *Schema { r := &Reflector{} return r.ReflectFromType(t) }
[ "func", "ReflectFromType", "(", "t", "reflect", ".", "Type", ")", "*", "Schema", "{", "r", ":=", "&", "Reflector", "{", "}", "\n", "return", "r", ".", "ReflectFromType", "(", "t", ")", "\n", "}" ]
// ReflectFromType generates root schema using the default Reflector
[ "ReflectFromType", "generates", "root", "schema", "using", "the", "default", "Reflector" ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L81-L84
train
alecthomas/jsonschema
reflect.go
Reflect
func (r *Reflector) Reflect(v interface{}) *Schema { return r.ReflectFromType(reflect.TypeOf(v)) }
go
func (r *Reflector) Reflect(v interface{}) *Schema { return r.ReflectFromType(reflect.TypeOf(v)) }
[ "func", "(", "r", "*", "Reflector", ")", "Reflect", "(", "v", "interface", "{", "}", ")", "*", "Schema", "{", "return", "r", ".", "ReflectFromType", "(", "reflect", ".", "TypeOf", "(", "v", ")", ")", "\n", "}" ]
// Reflect reflects to Schema from a value.
[ "Reflect", "reflects", "to", "Schema", "from", "a", "value", "." ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L106-L108
train
alecthomas/jsonschema
reflect.go
ReflectFromType
func (r *Reflector) ReflectFromType(t reflect.Type) *Schema { definitions := Definitions{} if r.ExpandedStruct { st := &Type{ Version: Version, Type: "object", Properties: map[string]*Type{}, AdditionalProperties: []byte("false"), } if r.AllowAdditionalProperties { st.AdditionalProperties = []byte("true") } r.reflectStructFields(st, definitions, t) r.reflectStruct(definitions, t) delete(definitions, t.Name()) return &Schema{Type: st, Definitions: definitions} } s := &Schema{ Type: r.reflectTypeToSchema(definitions, t), Definitions: definitions, } return s }
go
func (r *Reflector) ReflectFromType(t reflect.Type) *Schema { definitions := Definitions{} if r.ExpandedStruct { st := &Type{ Version: Version, Type: "object", Properties: map[string]*Type{}, AdditionalProperties: []byte("false"), } if r.AllowAdditionalProperties { st.AdditionalProperties = []byte("true") } r.reflectStructFields(st, definitions, t) r.reflectStruct(definitions, t) delete(definitions, t.Name()) return &Schema{Type: st, Definitions: definitions} } s := &Schema{ Type: r.reflectTypeToSchema(definitions, t), Definitions: definitions, } return s }
[ "func", "(", "r", "*", "Reflector", ")", "ReflectFromType", "(", "t", "reflect", ".", "Type", ")", "*", "Schema", "{", "definitions", ":=", "Definitions", "{", "}", "\n", "if", "r", ".", "ExpandedStruct", "{", "st", ":=", "&", "Type", "{", "Version", ...
// ReflectFromType generates root schema
[ "ReflectFromType", "generates", "root", "schema" ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L111-L134
train
alecthomas/jsonschema
reflect.go
reflectStruct
func (r *Reflector) reflectStruct(definitions Definitions, t reflect.Type) *Type { st := &Type{ Type: "object", Properties: map[string]*Type{}, AdditionalProperties: []byte("false"), } if r.AllowAdditionalProperties { st.AdditionalProperties = []byte("true") } definitions[t.Name()] = st r.reflectStructFields(st, definitions, t) return &Type{ Version: Version, Ref: "#/definitions/" + t.Name(), } }
go
func (r *Reflector) reflectStruct(definitions Definitions, t reflect.Type) *Type { st := &Type{ Type: "object", Properties: map[string]*Type{}, AdditionalProperties: []byte("false"), } if r.AllowAdditionalProperties { st.AdditionalProperties = []byte("true") } definitions[t.Name()] = st r.reflectStructFields(st, definitions, t) return &Type{ Version: Version, Ref: "#/definitions/" + t.Name(), } }
[ "func", "(", "r", "*", "Reflector", ")", "reflectStruct", "(", "definitions", "Definitions", ",", "t", "reflect", ".", "Type", ")", "*", "Type", "{", "st", ":=", "&", "Type", "{", "Type", ":", "\"", "\"", ",", "Properties", ":", "map", "[", "string",...
// Refects a struct to a JSON Schema type.
[ "Refects", "a", "struct", "to", "a", "JSON", "Schema", "type", "." ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L248-L264
train
alecthomas/jsonschema
reflect.go
genericKeywords
func (t *Type) genericKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "title": t.Title = val case "description": t.Description = val } } } }
go
func (t *Type) genericKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "title": t.Title = val case "description": t.Description = val } } } }
[ "func", "(", "t", "*", "Type", ")", "genericKeywords", "(", "tags", "[", "]", "string", ")", "{", "for", "_", ",", "tag", ":=", "range", "tags", "{", "nameValue", ":=", "strings", ".", "Split", "(", "tag", ",", "\"", "\"", ")", "\n", "if", "len",...
// read struct tags for generic keyworks
[ "read", "struct", "tags", "for", "generic", "keyworks" ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L312-L325
train
alecthomas/jsonschema
reflect.go
stringKeywords
func (t *Type) stringKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "minLength": i, _ := strconv.Atoi(val) t.MinLength = i case "maxLength": i, _ := strconv.Atoi(val) t.MaxLength = i case "pattern": t.Pattern = val case "format": switch val { case "date-time", "email", "hostname", "ipv4", "ipv6", "uri": t.Format = val break } case "default": t.Default = val case "example": t.Examples = append(t.Examples, val) } } } }
go
func (t *Type) stringKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "minLength": i, _ := strconv.Atoi(val) t.MinLength = i case "maxLength": i, _ := strconv.Atoi(val) t.MaxLength = i case "pattern": t.Pattern = val case "format": switch val { case "date-time", "email", "hostname", "ipv4", "ipv6", "uri": t.Format = val break } case "default": t.Default = val case "example": t.Examples = append(t.Examples, val) } } } }
[ "func", "(", "t", "*", "Type", ")", "stringKeywords", "(", "tags", "[", "]", "string", ")", "{", "for", "_", ",", "tag", ":=", "range", "tags", "{", "nameValue", ":=", "strings", ".", "Split", "(", "tag", ",", "\"", "\"", ")", "\n", "if", "len", ...
// read struct tags for string type keyworks
[ "read", "struct", "tags", "for", "string", "type", "keyworks" ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L328-L355
train
alecthomas/jsonschema
reflect.go
numbericKeywords
func (t *Type) numbericKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "multipleOf": i, _ := strconv.Atoi(val) t.MultipleOf = i case "minimum": i, _ := strconv.Atoi(val) t.Minimum = i case "maximum": i, _ := strconv.Atoi(val) t.Maximum = i case "exclusiveMaximum": b, _ := strconv.ParseBool(val) t.ExclusiveMaximum = b case "exclusiveMinimum": b, _ := strconv.ParseBool(val) t.ExclusiveMinimum = b case "default": i, _ := strconv.Atoi(val) t.Default = i case "example": if i, err := strconv.Atoi(val); err == nil { t.Examples = append(t.Examples, i) } } } } }
go
func (t *Type) numbericKeywords(tags []string) { for _, tag := range tags { nameValue := strings.Split(tag, "=") if len(nameValue) == 2 { name, val := nameValue[0], nameValue[1] switch name { case "multipleOf": i, _ := strconv.Atoi(val) t.MultipleOf = i case "minimum": i, _ := strconv.Atoi(val) t.Minimum = i case "maximum": i, _ := strconv.Atoi(val) t.Maximum = i case "exclusiveMaximum": b, _ := strconv.ParseBool(val) t.ExclusiveMaximum = b case "exclusiveMinimum": b, _ := strconv.ParseBool(val) t.ExclusiveMinimum = b case "default": i, _ := strconv.Atoi(val) t.Default = i case "example": if i, err := strconv.Atoi(val); err == nil { t.Examples = append(t.Examples, i) } } } } }
[ "func", "(", "t", "*", "Type", ")", "numbericKeywords", "(", "tags", "[", "]", "string", ")", "{", "for", "_", ",", "tag", ":=", "range", "tags", "{", "nameValue", ":=", "strings", ".", "Split", "(", "tag", ",", "\"", "\"", ")", "\n", "if", "len"...
// read struct tags for numberic type keyworks
[ "read", "struct", "tags", "for", "numberic", "type", "keyworks" ]
eff3f6c90428ddd2d988c9b686d92488c6430b77
https://github.com/alecthomas/jsonschema/blob/eff3f6c90428ddd2d988c9b686d92488c6430b77/reflect.go#L358-L389
train
bitfinexcom/bitfinex-api-go
utils/nonce.go
GetNonce
func (u *EpochNonceGenerator) GetNonce() string { return strconv.FormatUint(atomic.AddUint64(&u.nonce, 1), 10) }
go
func (u *EpochNonceGenerator) GetNonce() string { return strconv.FormatUint(atomic.AddUint64(&u.nonce, 1), 10) }
[ "func", "(", "u", "*", "EpochNonceGenerator", ")", "GetNonce", "(", ")", "string", "{", "return", "strconv", ".", "FormatUint", "(", "atomic", ".", "AddUint64", "(", "&", "u", ".", "nonce", ",", "1", ")", ",", "10", ")", "\n", "}" ]
// GetNonce is a naive nonce producer that takes the current Unix nano epoch // and counts upwards. // This is a naive approach because the nonce bound to the currently used API // key and as such needs to be synchronised with other instances using the same // key in order to avoid race conditions.
[ "GetNonce", "is", "a", "naive", "nonce", "producer", "that", "takes", "the", "current", "Unix", "nano", "epoch", "and", "counts", "upwards", ".", "This", "is", "a", "naive", "approach", "because", "the", "nonce", "bound", "to", "the", "currently", "used", ...
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/utils/nonce.go#L24-L26
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
Send
func (c *Client) Send(ctx context.Context, msg interface{}) error { return c.asynchronous.Send(ctx, msg) }
go
func (c *Client) Send(ctx context.Context, msg interface{}) error { return c.asynchronous.Send(ctx, msg) }
[ "func", "(", "c", "*", "Client", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "msg", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "asynchronous", ".", "Send", "(", "ctx", ",", "msg", ")", "\n", "}" ]
// API for end-users to interact with Bitfinex. // Send publishes a generic message to the Bitfinex API.
[ "API", "for", "end", "-", "users", "to", "interact", "with", "Bitfinex", ".", "Send", "publishes", "a", "generic", "message", "to", "the", "Bitfinex", "API", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L17-L19
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
Subscribe
func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (string, error) { c.subscriptions.add(req) err := c.asynchronous.Send(ctx, req) if err != nil { // propagate send error return "", err } return req.SubID, nil }
go
func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (string, error) { c.subscriptions.add(req) err := c.asynchronous.Send(ctx, req) if err != nil { // propagate send error return "", err } return req.SubID, nil }
[ "func", "(", "c", "*", "Client", ")", "Subscribe", "(", "ctx", "context", ".", "Context", ",", "req", "*", "SubscriptionRequest", ")", "(", "string", ",", "error", ")", "{", "c", ".", "subscriptions", ".", "add", "(", "req", ")", "\n", "err", ":=", ...
// Subscribe sends a subscription request to the Bitfinex API and tracks the subscription status by ID.
[ "Subscribe", "sends", "a", "subscription", "request", "to", "the", "Bitfinex", "API", "and", "tracks", "the", "subscription", "status", "by", "ID", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L34-L42
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
SubscribeTicker
func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanTicker, Symbol: symbol, } return c.Subscribe(ctx, req) }
go
func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanTicker, Symbol: symbol, } return c.Subscribe(ctx, req) }
[ "func", "(", "c", "*", "Client", ")", "SubscribeTicker", "(", "ctx", "context", ".", "Context", ",", "symbol", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "SubscriptionRequest", "{", "SubID", ":", "c", ".", "nonce", ".", "...
// SubscribeTicker sends a subscription request for the ticker.
[ "SubscribeTicker", "sends", "a", "subscription", "request", "for", "the", "ticker", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L45-L53
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
SubscribeBook
func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision bitfinex.BookPrecision, frequency bitfinex.BookFrequency, priceLevel int) (string, error) { if priceLevel < 0 { return "", fmt.Errorf("negative price levels not supported: %d", priceLevel) } req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanBook, Symbol: symbol, Precision: string(precision), Len: fmt.Sprintf("%d", priceLevel), // needed for R0? } if !bitfinex.IsRawBook(string(precision)) { req.Frequency = string(frequency) } return c.Subscribe(ctx, req) }
go
func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision bitfinex.BookPrecision, frequency bitfinex.BookFrequency, priceLevel int) (string, error) { if priceLevel < 0 { return "", fmt.Errorf("negative price levels not supported: %d", priceLevel) } req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanBook, Symbol: symbol, Precision: string(precision), Len: fmt.Sprintf("%d", priceLevel), // needed for R0? } if !bitfinex.IsRawBook(string(precision)) { req.Frequency = string(frequency) } return c.Subscribe(ctx, req) }
[ "func", "(", "c", "*", "Client", ")", "SubscribeBook", "(", "ctx", "context", ".", "Context", ",", "symbol", "string", ",", "precision", "bitfinex", ".", "BookPrecision", ",", "frequency", "bitfinex", ".", "BookFrequency", ",", "priceLevel", "int", ")", "(",...
// SubscribeBook sends a subscription request for market data for a given symbol, at a given frequency, with a given precision, returning no more than priceLevels price entries. // Default values are Precision0, Frequency0, and priceLevels=25.
[ "SubscribeBook", "sends", "a", "subscription", "request", "for", "market", "data", "for", "a", "given", "symbol", "at", "a", "given", "frequency", "with", "a", "given", "precision", "returning", "no", "more", "than", "priceLevels", "price", "entries", ".", "De...
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L68-L84
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
SubscribeCandles
func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution bitfinex.CandleResolution) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanCandles, Key: fmt.Sprintf("trade:%s:%s", resolution, symbol), } return c.Subscribe(ctx, req) }
go
func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution bitfinex.CandleResolution) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), Event: EventSubscribe, Channel: ChanCandles, Key: fmt.Sprintf("trade:%s:%s", resolution, symbol), } return c.Subscribe(ctx, req) }
[ "func", "(", "c", "*", "Client", ")", "SubscribeCandles", "(", "ctx", "context", ".", "Context", ",", "symbol", "string", ",", "resolution", "bitfinex", ".", "CandleResolution", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "SubscriptionReq...
// SubscribeCandles sends a subscription request for OHLC candles.
[ "SubscribeCandles", "sends", "a", "subscription", "request", "for", "OHLC", "candles", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L87-L95
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
SubmitOrder
func (c *Client) SubmitOrder(ctx context.Context, order *bitfinex.OrderNewRequest) error { return c.asynchronous.Send(ctx, order) }
go
func (c *Client) SubmitOrder(ctx context.Context, order *bitfinex.OrderNewRequest) error { return c.asynchronous.Send(ctx, order) }
[ "func", "(", "c", "*", "Client", ")", "SubmitOrder", "(", "ctx", "context", ".", "Context", ",", "order", "*", "bitfinex", ".", "OrderNewRequest", ")", "error", "{", "return", "c", ".", "asynchronous", ".", "Send", "(", "ctx", ",", "order", ")", "\n", ...
// SubmitOrder sends an order request.
[ "SubmitOrder", "sends", "an", "order", "request", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L106-L108
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
SubmitCancel
func (c *Client) SubmitCancel(ctx context.Context, cancel *bitfinex.OrderCancelRequest) error { return c.asynchronous.Send(ctx, cancel) }
go
func (c *Client) SubmitCancel(ctx context.Context, cancel *bitfinex.OrderCancelRequest) error { return c.asynchronous.Send(ctx, cancel) }
[ "func", "(", "c", "*", "Client", ")", "SubmitCancel", "(", "ctx", "context", ".", "Context", ",", "cancel", "*", "bitfinex", ".", "OrderCancelRequest", ")", "error", "{", "return", "c", ".", "asynchronous", ".", "Send", "(", "ctx", ",", "cancel", ")", ...
// SubmitCancel sends a cancel request.
[ "SubmitCancel", "sends", "a", "cancel", "request", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L115-L117
train
bitfinexcom/bitfinex-api-go
v2/websocket/api.go
LookupSubscription
func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error) { s, err := c.subscriptions.lookupBySubscriptionID(subID) if err != nil { return nil, err } return s.Request, nil }
go
func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error) { s, err := c.subscriptions.lookupBySubscriptionID(subID) if err != nil { return nil, err } return s.Request, nil }
[ "func", "(", "c", "*", "Client", ")", "LookupSubscription", "(", "subID", "string", ")", "(", "*", "SubscriptionRequest", ",", "error", ")", "{", "s", ",", "err", ":=", "c", ".", "subscriptions", ".", "lookupBySubscriptionID", "(", "subID", ")", "\n", "i...
// LookupSubscription looks up a subscription request by ID
[ "LookupSubscription", "looks", "up", "a", "subscription", "request", "by", "ID" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/api.go#L120-L126
train
bitfinexcom/bitfinex-api-go
v2/websocket/transport.go
Send
func (w *ws) Send(ctx context.Context, msg interface{}) error { if w.ws == nil { return ErrWSNotConnected } bs, err := json.Marshal(msg) if err != nil { return err } select { case <- ctx.Done(): return ctx.Err() case <- w.quit: // ws closed return fmt.Errorf("websocket connection closed") default: } w.wsLock.Lock() defer w.wsLock.Unlock() w.log.Debug("ws->srv: %s", string(bs)) err = w.ws.WriteMessage(websocket.TextMessage, bs) if err != nil { return err } return nil }
go
func (w *ws) Send(ctx context.Context, msg interface{}) error { if w.ws == nil { return ErrWSNotConnected } bs, err := json.Marshal(msg) if err != nil { return err } select { case <- ctx.Done(): return ctx.Err() case <- w.quit: // ws closed return fmt.Errorf("websocket connection closed") default: } w.wsLock.Lock() defer w.wsLock.Unlock() w.log.Debug("ws->srv: %s", string(bs)) err = w.ws.WriteMessage(websocket.TextMessage, bs) if err != nil { return err } return nil }
[ "func", "(", "w", "*", "ws", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "msg", "interface", "{", "}", ")", "error", "{", "if", "w", ".", "ws", "==", "nil", "{", "return", "ErrWSNotConnected", "\n", "}", "\n\n", "bs", ",", "err", ":=...
// Send marshals the given interface and then sends it to the API. This method // can block so specify a context with timeout if you don't want to wait for too // long.
[ "Send", "marshals", "the", "given", "interface", "and", "then", "sends", "it", "to", "the", "API", ".", "This", "method", "can", "block", "so", "specify", "a", "context", "with", "timeout", "if", "you", "don", "t", "want", "to", "wait", "for", "too", "...
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/transport.go#L69-L95
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
Create
func (w *WebsocketAsynchronousFactory) Create() Asynchronous { return newWs(w.parameters.URL, w.parameters.LogTransport, w.parameters.Logger) }
go
func (w *WebsocketAsynchronousFactory) Create() Asynchronous { return newWs(w.parameters.URL, w.parameters.LogTransport, w.parameters.Logger) }
[ "func", "(", "w", "*", "WebsocketAsynchronousFactory", ")", "Create", "(", ")", "Asynchronous", "{", "return", "newWs", "(", "w", ".", "parameters", ".", "URL", ",", "w", ".", "parameters", ".", "LogTransport", ",", "w", ".", "parameters", ".", "Logger", ...
// Create returns a new websocket transport.
[ "Create", "returns", "a", "new", "websocket", "transport", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L89-L91
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
Credentials
func (c *Client) Credentials(key string, secret string) *Client { c.apiKey = key c.apiSecret = secret return c }
go
func (c *Client) Credentials(key string, secret string) *Client { c.apiKey = key c.apiSecret = secret return c }
[ "func", "(", "c", "*", "Client", ")", "Credentials", "(", "key", "string", ",", "secret", "string", ")", "*", "Client", "{", "c", ".", "apiKey", "=", "key", "\n", "c", ".", "apiSecret", "=", "secret", "\n", "return", "c", "\n", "}" ]
// Credentials assigns authentication credentials to a connection request.
[ "Credentials", "assigns", "authentication", "credentials", "to", "a", "connection", "request", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L132-L136
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
CancelOnDisconnect
func (c *Client) CancelOnDisconnect(cxl bool) *Client { c.cancelOnDisconnect = cxl return c }
go
func (c *Client) CancelOnDisconnect(cxl bool) *Client { c.cancelOnDisconnect = cxl return c }
[ "func", "(", "c", "*", "Client", ")", "CancelOnDisconnect", "(", "cxl", "bool", ")", "*", "Client", "{", "c", ".", "cancelOnDisconnect", "=", "cxl", "\n", "return", "c", "\n", "}" ]
// CancelOnDisconnect ensures all orders will be canceled if this API session is disconnected.
[ "CancelOnDisconnect", "ensures", "all", "orders", "will", "be", "canceled", "if", "this", "API", "session", "is", "disconnected", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L139-L142
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
NewWithAsyncFactoryNonce
func NewWithAsyncFactoryNonce(async AsynchronousFactory, nonce utils.NonceGenerator) *Client { return NewWithParamsAsyncFactoryNonce(NewDefaultParameters(), async, nonce) }
go
func NewWithAsyncFactoryNonce(async AsynchronousFactory, nonce utils.NonceGenerator) *Client { return NewWithParamsAsyncFactoryNonce(NewDefaultParameters(), async, nonce) }
[ "func", "NewWithAsyncFactoryNonce", "(", "async", "AsynchronousFactory", ",", "nonce", "utils", ".", "NonceGenerator", ")", "*", "Client", "{", "return", "NewWithParamsAsyncFactoryNonce", "(", "NewDefaultParameters", "(", ")", ",", "async", ",", "nonce", ")", "\n", ...
// NewWithAsyncFactoryNonce creates a new default client with a given asynchronous transport factory and nonce generator.
[ "NewWithAsyncFactoryNonce", "creates", "a", "new", "default", "client", "with", "a", "given", "asynchronous", "transport", "factory", "and", "nonce", "generator", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L173-L175
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
NewWithParamsNonce
func NewWithParamsNonce(params *Parameters, nonce utils.NonceGenerator) *Client { return NewWithParamsAsyncFactoryNonce(params, NewWebsocketAsynchronousFactory(params), nonce) }
go
func NewWithParamsNonce(params *Parameters, nonce utils.NonceGenerator) *Client { return NewWithParamsAsyncFactoryNonce(params, NewWebsocketAsynchronousFactory(params), nonce) }
[ "func", "NewWithParamsNonce", "(", "params", "*", "Parameters", ",", "nonce", "utils", ".", "NonceGenerator", ")", "*", "Client", "{", "return", "NewWithParamsAsyncFactoryNonce", "(", "params", ",", "NewWebsocketAsynchronousFactory", "(", "params", ")", ",", "nonce"...
// NewWithParamsNonce creates a new default client with a given set of parameters and nonce generator.
[ "NewWithParamsNonce", "creates", "a", "new", "default", "client", "with", "a", "given", "set", "of", "parameters", "and", "nonce", "generator", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L178-L180
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
NewWithParamsAsyncFactory
func NewWithParamsAsyncFactory(params *Parameters, async AsynchronousFactory) *Client { return NewWithParamsAsyncFactoryNonce(params, async, utils.NewEpochNonceGenerator()) }
go
func NewWithParamsAsyncFactory(params *Parameters, async AsynchronousFactory) *Client { return NewWithParamsAsyncFactoryNonce(params, async, utils.NewEpochNonceGenerator()) }
[ "func", "NewWithParamsAsyncFactory", "(", "params", "*", "Parameters", ",", "async", "AsynchronousFactory", ")", "*", "Client", "{", "return", "NewWithParamsAsyncFactoryNonce", "(", "params", ",", "async", ",", "utils", ".", "NewEpochNonceGenerator", "(", ")", ")", ...
// NewWithParamsAsyncFactory creates a new default client with a given set of parameters and asynchronous transport factory interface.
[ "NewWithParamsAsyncFactory", "creates", "a", "new", "default", "client", "with", "a", "given", "set", "of", "parameters", "and", "asynchronous", "transport", "factory", "interface", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L183-L185
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
NewWithParamsAsyncFactoryNonce
func NewWithParamsAsyncFactoryNonce(params *Parameters, async AsynchronousFactory, nonce utils.NonceGenerator) *Client { c := &Client{ asyncFactory: async, Authentication: NoAuthentication, factories: make(map[string]messageFactory), subscriptions: newSubscriptions(params.HeartbeatTimeout, params.Logger), orderbooks: make(map[string]*Orderbook), nonce: nonce, isConnected: false, parameters: params, listener: make(chan interface{}), terminal: false, resetWebsocket: make(chan bool), shutdown: make(chan bool), asynchronous: async.Create(), log: params.Logger, } c.registerPublicFactories() return c }
go
func NewWithParamsAsyncFactoryNonce(params *Parameters, async AsynchronousFactory, nonce utils.NonceGenerator) *Client { c := &Client{ asyncFactory: async, Authentication: NoAuthentication, factories: make(map[string]messageFactory), subscriptions: newSubscriptions(params.HeartbeatTimeout, params.Logger), orderbooks: make(map[string]*Orderbook), nonce: nonce, isConnected: false, parameters: params, listener: make(chan interface{}), terminal: false, resetWebsocket: make(chan bool), shutdown: make(chan bool), asynchronous: async.Create(), log: params.Logger, } c.registerPublicFactories() return c }
[ "func", "NewWithParamsAsyncFactoryNonce", "(", "params", "*", "Parameters", ",", "async", "AsynchronousFactory", ",", "nonce", "utils", ".", "NonceGenerator", ")", "*", "Client", "{", "c", ":=", "&", "Client", "{", "asyncFactory", ":", "async", ",", "Authenticat...
// NewWithParamsAsyncFactoryNonce creates a new client with a given set of parameters, asynchronous transport factory, and nonce generator interfaces.
[ "NewWithParamsAsyncFactoryNonce", "creates", "a", "new", "client", "with", "a", "given", "set", "of", "parameters", "asynchronous", "transport", "factory", "and", "nonce", "generator", "interfaces", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L188-L207
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
Connect
func (c *Client) Connect() error { c.dumpParams() c.terminal = false // wait for reset websocket signals go c.listenDisconnect() c.reset() return c.connect() }
go
func (c *Client) Connect() error { c.dumpParams() c.terminal = false // wait for reset websocket signals go c.listenDisconnect() c.reset() return c.connect() }
[ "func", "(", "c", "*", "Client", ")", "Connect", "(", ")", "error", "{", "c", ".", "dumpParams", "(", ")", "\n", "c", ".", "terminal", "=", "false", "\n", "// wait for reset websocket signals", "go", "c", ".", "listenDisconnect", "(", ")", "\n", "c", "...
// Connect to the Bitfinex API, this should only be called once.
[ "Connect", "to", "the", "Bitfinex", "API", "this", "should", "only", "be", "called", "once", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L287-L294
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
reset
func (c *Client) reset() { subs := c.subscriptions.Reset() if subs != nil { c.resetSubscriptions = subs } c.init = true ws := c.asyncFactory.Create() c.asynchronous = ws // listen to data from async go c.listenUpstream(ws) }
go
func (c *Client) reset() { subs := c.subscriptions.Reset() if subs != nil { c.resetSubscriptions = subs } c.init = true ws := c.asyncFactory.Create() c.asynchronous = ws // listen to data from async go c.listenUpstream(ws) }
[ "func", "(", "c", "*", "Client", ")", "reset", "(", ")", "{", "subs", ":=", "c", ".", "subscriptions", ".", "Reset", "(", ")", "\n", "if", "subs", "!=", "nil", "{", "c", ".", "resetSubscriptions", "=", "subs", "\n", "}", "\n", "c", ".", "init", ...
// reset assumes transport has already died or been closed
[ "reset", "assumes", "transport", "has", "already", "died", "or", "been", "closed" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L297-L308
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
listenUpstream
func (c *Client) listenUpstream(ws Asynchronous) { for { select { case <- ws.Done(): // transport shutdown c.resetWebsocket <- true return case msg := <- ws.Listen(): if msg != nil { // Errors here should be non critical so we just log them. // log.Printf("[DEBUG]: %s\n", msg) err := c.handleMessage(msg) if err != nil { c.log.Warning(err) } } } } }
go
func (c *Client) listenUpstream(ws Asynchronous) { for { select { case <- ws.Done(): // transport shutdown c.resetWebsocket <- true return case msg := <- ws.Listen(): if msg != nil { // Errors here should be non critical so we just log them. // log.Printf("[DEBUG]: %s\n", msg) err := c.handleMessage(msg) if err != nil { c.log.Warning(err) } } } } }
[ "func", "(", "c", "*", "Client", ")", "listenUpstream", "(", "ws", "Asynchronous", ")", "{", "for", "{", "select", "{", "case", "<-", "ws", ".", "Done", "(", ")", ":", "// transport shutdown", "c", ".", "resetWebsocket", "<-", "true", "\n", "return", "...
// start this goroutine before connecting, but this should die during a connection failure
[ "start", "this", "goroutine", "before", "connecting", "but", "this", "should", "die", "during", "a", "connection", "failure" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L359-L376
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
killListener
func (c *Client) killListener(e error) { if c.listener != nil { if e != nil { c.listener <- e } close(c.listener) } }
go
func (c *Client) killListener(e error) { if c.listener != nil { if e != nil { c.listener <- e } close(c.listener) } }
[ "func", "(", "c", "*", "Client", ")", "killListener", "(", "e", "error", ")", "{", "if", "c", ".", "listener", "!=", "nil", "{", "if", "e", "!=", "nil", "{", "c", ".", "listener", "<-", "e", "\n", "}", "\n", "close", "(", "c", ".", "listener", ...
// terminal, unrecoverable state. called after async is closed.
[ "terminal", "unrecoverable", "state", ".", "called", "after", "async", "is", "closed", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L379-L386
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
handleOpen
func (c *Client) handleOpen() error { if c.hasCredentials() { err_auth := c.authenticate(context.Background()) if err_auth != nil { return err_auth } } else { c.checkResubscription() } return nil }
go
func (c *Client) handleOpen() error { if c.hasCredentials() { err_auth := c.authenticate(context.Background()) if err_auth != nil { return err_auth } } else { c.checkResubscription() } return nil }
[ "func", "(", "c", "*", "Client", ")", "handleOpen", "(", ")", "error", "{", "if", "c", ".", "hasCredentials", "(", ")", "{", "err_auth", ":=", "c", ".", "authenticate", "(", "context", ".", "Background", "(", ")", ")", "\n", "if", "err_auth", "!=", ...
// called when an info event is received
[ "called", "when", "an", "info", "event", "is", "received" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L478-L488
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
handleAuthAck
func (c *Client) handleAuthAck(auth *AuthEvent) { if c.Authentication == SuccessfulAuthentication { err := c.subscriptions.activate(auth.SubID, auth.ChanID) if err != nil { c.log.Errorf("could not activate auth subscription: %s", err.Error()) } c.checkResubscription() } else { c.log.Error("authentication failed") } }
go
func (c *Client) handleAuthAck(auth *AuthEvent) { if c.Authentication == SuccessfulAuthentication { err := c.subscriptions.activate(auth.SubID, auth.ChanID) if err != nil { c.log.Errorf("could not activate auth subscription: %s", err.Error()) } c.checkResubscription() } else { c.log.Error("authentication failed") } }
[ "func", "(", "c", "*", "Client", ")", "handleAuthAck", "(", "auth", "*", "AuthEvent", ")", "{", "if", "c", ".", "Authentication", "==", "SuccessfulAuthentication", "{", "err", ":=", "c", ".", "subscriptions", ".", "activate", "(", "auth", ".", "SubID", "...
// called when an auth event is received
[ "called", "when", "an", "auth", "event", "is", "received" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L491-L501
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
Unsubscribe
func (c *Client) Unsubscribe(ctx context.Context, id string) error { sub, err := c.subscriptions.lookupBySubscriptionID(id) if err != nil { return err } // sub is removed from manager on ack from API return c.sendUnsubscribeMessage(ctx, sub.ChanID) }
go
func (c *Client) Unsubscribe(ctx context.Context, id string) error { sub, err := c.subscriptions.lookupBySubscriptionID(id) if err != nil { return err } // sub is removed from manager on ack from API return c.sendUnsubscribeMessage(ctx, sub.ChanID) }
[ "func", "(", "c", "*", "Client", ")", "Unsubscribe", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "sub", ",", "err", ":=", "c", ".", "subscriptions", ".", "lookupBySubscriptionID", "(", "id", ")", "\n", "if", "err", ...
// Unsubscribe looks up an existing subscription by ID and sends an unsubscribe request.
[ "Unsubscribe", "looks", "up", "an", "existing", "subscription", "by", "ID", "and", "sends", "an", "unsubscribe", "request", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L508-L515
train
bitfinexcom/bitfinex-api-go
v2/websocket/client.go
authenticate
func (c *Client) authenticate(ctx context.Context, filter ...string) error { nonce := c.nonce.GetNonce() payload := "AUTH" + nonce sig, err := c.sign(payload) if err != nil { return err } s := &SubscriptionRequest{ Event: "auth", APIKey: c.apiKey, AuthSig: sig, AuthPayload: payload, AuthNonce: nonce, Filter: filter, SubID: nonce, } if c.cancelOnDisconnect { s.DMS = DMSCancelOnDisconnect } c.subscriptions.add(s) if err := c.asynchronous.Send(ctx, s); err != nil { return err } c.Authentication = PendingAuthentication return nil }
go
func (c *Client) authenticate(ctx context.Context, filter ...string) error { nonce := c.nonce.GetNonce() payload := "AUTH" + nonce sig, err := c.sign(payload) if err != nil { return err } s := &SubscriptionRequest{ Event: "auth", APIKey: c.apiKey, AuthSig: sig, AuthPayload: payload, AuthNonce: nonce, Filter: filter, SubID: nonce, } if c.cancelOnDisconnect { s.DMS = DMSCancelOnDisconnect } c.subscriptions.add(s) if err := c.asynchronous.Send(ctx, s); err != nil { return err } c.Authentication = PendingAuthentication return nil }
[ "func", "(", "c", "*", "Client", ")", "authenticate", "(", "ctx", "context", ".", "Context", ",", "filter", "...", "string", ")", "error", "{", "nonce", ":=", "c", ".", "nonce", ".", "GetNonce", "(", ")", "\n", "payload", ":=", "\"", "\"", "+", "no...
// Authenticate creates the payload for the authentication request and sends it // to the API. The filters will be applied to the authenticated channel, i.e. // only subscribe to the filtered messages.
[ "Authenticate", "creates", "the", "payload", "for", "the", "authentication", "request", "and", "sends", "it", "to", "the", "API", ".", "The", "filters", "will", "be", "applied", "to", "the", "authenticated", "channel", "i", ".", "e", ".", "only", "subscribe"...
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v2/websocket/client.go#L520-L547
train
bitfinexcom/bitfinex-api-go
v1/websocket.go
NewWebSocketService
func NewWebSocketService(c *Client) *WebSocketService { return &WebSocketService{ client: c, chanMap: make(map[float64]chan []float64), subscribes: make([]subscribeToChannel, 0), } }
go
func NewWebSocketService(c *Client) *WebSocketService { return &WebSocketService{ client: c, chanMap: make(map[float64]chan []float64), subscribes: make([]subscribeToChannel, 0), } }
[ "func", "NewWebSocketService", "(", "c", "*", "Client", ")", "*", "WebSocketService", "{", "return", "&", "WebSocketService", "{", "client", ":", "c", ",", "chanMap", ":", "make", "(", "map", "[", "float64", "]", "chan", "[", "]", "float64", ")", ",", ...
// NewWebSocketService returns a WebSocketService using the given client.
[ "NewWebSocketService", "returns", "a", "WebSocketService", "using", "the", "given", "client", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/websocket.go#L82-L88
train
bitfinexcom/bitfinex-api-go
v1/websocket.go
Connect
func (w *WebSocketService) Connect() error { var d = websocket.Dialer{ Subprotocols: []string{"p1", "p2"}, ReadBufferSize: 1024, WriteBufferSize: 1024, Proxy: http.ProxyFromEnvironment, } if w.client.WebSocketTLSSkipVerify { d.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} } ws, _, err := d.Dial(w.client.WebSocketURL, nil) if err != nil { return err } w.ws = ws return nil }
go
func (w *WebSocketService) Connect() error { var d = websocket.Dialer{ Subprotocols: []string{"p1", "p2"}, ReadBufferSize: 1024, WriteBufferSize: 1024, Proxy: http.ProxyFromEnvironment, } if w.client.WebSocketTLSSkipVerify { d.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} } ws, _, err := d.Dial(w.client.WebSocketURL, nil) if err != nil { return err } w.ws = ws return nil }
[ "func", "(", "w", "*", "WebSocketService", ")", "Connect", "(", ")", "error", "{", "var", "d", "=", "websocket", ".", "Dialer", "{", "Subprotocols", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "ReadBufferSize", ":", "1024", ...
// Connect create new bitfinex websocket connection
[ "Connect", "create", "new", "bitfinex", "websocket", "connection" ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/websocket.go#L91-L109
train
bitfinexcom/bitfinex-api-go
v1/client.go
newRequest
func (c *Client) newRequest(method string, refURL string, params url.Values) (*http.Request, error) { rel, err := url.Parse(refURL) if err != nil { return nil, err } if params != nil { rel.RawQuery = params.Encode() } var req *http.Request u := c.BaseURL.ResolveReference(rel) req, err = http.NewRequest(method, u.String(), nil) if err != nil { return nil, err } return req, nil }
go
func (c *Client) newRequest(method string, refURL string, params url.Values) (*http.Request, error) { rel, err := url.Parse(refURL) if err != nil { return nil, err } if params != nil { rel.RawQuery = params.Encode() } var req *http.Request u := c.BaseURL.ResolveReference(rel) req, err = http.NewRequest(method, u.String(), nil) if err != nil { return nil, err } return req, nil }
[ "func", "(", "c", "*", "Client", ")", "newRequest", "(", "method", "string", ",", "refURL", "string", ",", "params", "url", ".", "Values", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "rel", ",", "err", ":=", "url", ".", "Parse", ...
// NewRequest create new API request. Relative url can be provided in refURL.
[ "NewRequest", "create", "new", "API", "request", ".", "Relative", "url", "can", "be", "provided", "in", "refURL", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/client.go#L86-L103
train
bitfinexcom/bitfinex-api-go
v1/client.go
newAuthenticatedRequest
func (c *Client) newAuthenticatedRequest(m string, refURL string, data map[string]interface{}) (*http.Request, error) { req, err := c.newRequest(m, refURL, nil) if err != nil { return nil, err } nonce := utils.GetNonce() payload := map[string]interface{}{ "request": "/v1/" + refURL, "nonce": nonce, } for k, v := range data { payload[k] = v } p, err := json.Marshal(payload) if err != nil { return nil, err } encoded := base64.StdEncoding.EncodeToString(p) req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") req.Header.Add("X-BFX-APIKEY", c.APIKey) req.Header.Add("X-BFX-PAYLOAD", encoded) sig, err := c.signPayload(encoded) if err != nil { return nil, err } req.Header.Add("X-BFX-SIGNATURE", sig) return req, nil }
go
func (c *Client) newAuthenticatedRequest(m string, refURL string, data map[string]interface{}) (*http.Request, error) { req, err := c.newRequest(m, refURL, nil) if err != nil { return nil, err } nonce := utils.GetNonce() payload := map[string]interface{}{ "request": "/v1/" + refURL, "nonce": nonce, } for k, v := range data { payload[k] = v } p, err := json.Marshal(payload) if err != nil { return nil, err } encoded := base64.StdEncoding.EncodeToString(p) req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") req.Header.Add("X-BFX-APIKEY", c.APIKey) req.Header.Add("X-BFX-PAYLOAD", encoded) sig, err := c.signPayload(encoded) if err != nil { return nil, err } req.Header.Add("X-BFX-SIGNATURE", sig) return req, nil }
[ "func", "(", "c", "*", "Client", ")", "newAuthenticatedRequest", "(", "m", "string", ",", "refURL", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", ...
// newAuthenticatedRequest creates new http request for authenticated routes.
[ "newAuthenticatedRequest", "creates", "new", "http", "request", "for", "authenticated", "routes", "." ]
c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b
https://github.com/bitfinexcom/bitfinex-api-go/blob/c16c61b288fbf09bfe1b22ee0a0e66b83f6c326b/v1/client.go#L106-L140
train